From 90ee61b0f91996335af9ce9460c7bb262a35a61b Mon Sep 17 00:00:00 2001 From: Philippe Laflamme Date: Thu, 16 Oct 2008 20:19:10 +0000 Subject: [PATCH] Added Copyright notice to all Java files. This had the side-effect of changing the line delimiter to the Unix format. As such, some files have had all their lines affected, others only a subset. --- LICENSE | 674 ++++++++ .../participant/ParticipantExcelReader.java | 111 +- .../cartagene/hibernate/util/CreateDDL.java | 237 +-- .../util/CreateQuestionnaire.java | 345 +++-- .../org/obiba/onyx/core/domain/IMemento.java | 59 +- .../application/ApplicationConfiguration.java | 113 +- .../core/domain/participant/Appointment.java | 127 +- .../onyx/core/domain/participant/Gender.java | 19 +- .../core/domain/participant/Interview.java | 201 +-- .../domain/participant/InterviewStatus.java | 19 +- .../core/domain/participant/Participant.java | 431 +++--- .../core/domain/participant/Province.java | 19 +- .../domain/stage/StageExecutionMemento.java | 9 + .../org/obiba/onyx/core/domain/user/Role.java | 129 +- .../obiba/onyx/core/domain/user/Status.java | 19 +- .../org/obiba/onyx/core/domain/user/User.java | 359 ++--- .../AbstractParticipantExcelReader.java | 399 ++--- .../participant/IParticipantReadListener.java | 53 +- .../etl/participant/IParticipantReader.java | 41 +- .../core/service/ActiveInterviewService.java | 177 ++- .../ApplicationConfigurationService.java | 27 +- .../onyx/core/service/ParticipantService.java | 125 +- .../obiba/onyx/core/service/UserService.java | 201 +-- .../onyx/core/service/UserSessionService.java | 37 +- .../DefaultActiveInterviewServiceImpl.java | 429 ++--- ...ltApplicationConfigurationServiceImpl.java | 39 +- .../impl/DefaultParticipantServiceImpl.java | 427 ++--- .../service/impl/DefaultUserServiceImpl.java | 195 +-- .../impl/UserSessionServiceBeanImpl.java | 9 + .../ParticipantServiceHibernateImpl.java | 307 ++-- .../hibernate/UserServiceHibernateImpl.java | 139 +- .../java/org/obiba/onyx/engine/Action.java | 245 +-- .../obiba/onyx/engine/ActionDefinition.java | 305 ++-- .../onyx/engine/ActionDefinitionBuilder.java | 201 +-- .../org/obiba/onyx/engine/ActionType.java | 159 +- .../ConsentStageDependencyCondition.java | 127 +- .../obiba/onyx/engine/IInterviewListener.java | 49 +- .../InverseStageDependencyCondition.java | 75 +- .../java/org/obiba/onyx/engine/Module.java | 9 + .../engine/ModuleDependencyCondition.java | 177 ++- .../engine/ModuleRegistrationListener.java | 9 + .../org/obiba/onyx/engine/ModuleRegistry.java | 9 + .../MultipleStageDependencyCondition.java | 137 +- .../java/org/obiba/onyx/engine/Operator.java | 19 +- .../PreviousStageDependencyCondition.java | 101 +- .../java/org/obiba/onyx/engine/Stage.java | 9 + .../onyx/engine/StageDependencyCondition.java | 65 +- .../onyx/engine/state/AbstractStageState.java | 369 ++--- .../onyx/engine/state/IStageExecution.java | 305 ++-- .../engine/state/ITransitionEventSink.java | 45 +- .../engine/state/ITransitionListener.java | 55 +- .../onyx/engine/state/ITransitionSource.java | 57 +- .../engine/state/StageExecutionContext.java | 543 +++---- .../onyx/engine/state/TransitionEvent.java | 199 +-- .../AnnotatedBeanFinderFactoryBean.java | 821 +++++----- .../remoting/CookieRequestExecutor.java | 79 +- .../onyx/wicket/IEngineComponentAware.java | 59 +- .../org/obiba/onyx/wicket/StageModel.java | 11 +- .../wicket/action/ActionDefinitionPanel.java | 421 ++--- .../onyx/wicket/action/ActionWindow.java | 221 +-- .../behavior/RequiredFormFieldBehavior.java | 55 +- .../obiba/onyx/wicket/data/DataConverter.java | 157 +- .../org/obiba/onyx/wicket/data/DataField.java | 567 +++---- .../model/SpringStringResourceModel.java | 497 +++--- .../test/ExtendedApplicationContextMock.java | 83 +- .../onyx/wicket/util/DateModelUtils.java | 155 +- .../wicket/util/JavascriptEventAlert.java | 61 +- .../obiba/onyx/wicket/wizard/WizardForm.java | 439 +++--- .../obiba/onyx/wicket/wizard/WizardPanel.java | 9 + .../onyx/wicket/wizard/WizardStepPanel.java | 201 +-- .../core/engine/state/StageExecutionTest.java | 1051 ++++++------- .../core/service/ParticipantExcelReader.java | 121 +- .../core/service/ParticipantServiceTest.java | 401 ++--- .../onyx/core/service/UserServiceTest.java | 251 +-- .../java/org/obiba/onyx/engine/StageTest.java | 171 +- .../obiba/onyx/jade/client/JnlpClient.java | 9 + .../instrument/ExternalAppLauncherHelper.java | 317 ++-- .../jade/instrument/InstrumentRunner.java | 41 +- .../jade/instrument/LocalSettingsHelper.java | 257 +-- .../org/obiba/onyx/jade/util/FileUtil.java | 9 + .../atcor/SphygmoCorInstrumentRunner.java | 451 +++--- .../instrument/atcor/dao/SphygmoCorDao.java | 47 +- .../atcor/dao/impl/JdbcSphygmoCorDao.java | 233 +-- .../atcor/SphygmoCorInstrumentRunnerTest.java | 533 +++---- .../tanita/Bc418InstrumentRunner.java | 965 ++++++------ .../instrument/tanita/TanitaInstrument.java | 1373 +++++++++-------- .../tanita/Tbf310InstrumentRunner.java | 401 ++--- .../tanita/Tbf310InstrumentRunnerTest.java | 157 +- .../AchillesExpressInstrumentRunner.java | 387 ++--- .../CardiosoftInstrumentResultParser.java | 619 ++++---- .../CardiosoftInstrumentRunner.java | 487 +++--- .../CardiosoftInstrumentRunnerTest.java | 353 ++--- .../mir/MiniSpirInstrumentRunner.java | 599 +++---- .../mir/MiniSpirInstrumentRunnerTest.java | 503 +++--- .../domain/instrument/ContraIndication.java | 9 + .../DateParameterValueConverter.java | 77 +- .../core/domain/instrument/FixedSource.java | 89 +- .../core/domain/instrument/InputSource.java | 95 +- .../core/domain/instrument/Instrument.java | 307 ++-- .../InstrumentComputedOutputParameter.java | 107 +- .../instrument/InstrumentDescriptor.java | 75 +- .../instrument/InstrumentInputParameter.java | 69 +- .../instrument/InstrumentOutputParameter.java | 39 +- .../InstrumentOutputParameterAlgorithm.java | 19 +- .../instrument/InstrumentParameter.java | 319 ++-- .../InstrumentParameterCaptureMethod.java | 19 +- .../InstrumentParameterValueConverter.java | 37 +- .../domain/instrument/InstrumentStatus.java | 19 +- .../domain/instrument/InstrumentType.java | 199 +-- .../instrument/InterpretativeParameter.java | 75 +- .../MultipleOutputParameterSource.java | 107 +- .../domain/instrument/OperatorSource.java | 91 +- .../instrument/OutputParameterSource.java | 117 +- .../ParticipantInteractionType.java | 19 +- .../instrument/ParticipantPropertySource.java | 87 +- .../UnitParameterValueConverter.java | 129 +- .../validation/AbstractIntegrityCheck.java | 229 +-- .../validation/EqualsParameterCheck.java | 209 +-- .../validation/EqualsValueCheck.java | 331 ++-- .../instrument/validation/IntegrityCheck.java | 151 +- .../validation/IntegrityCheckType.java | 19 +- .../validation/ParameterSpreadCheck.java | 413 ++--- .../instrument/validation/RangeCheck.java | 355 ++--- .../domain/run/ContraIndicationAnswer.java | 9 + .../jade/core/domain/run/InstrumentRun.java | 349 +++-- .../run/InstrumentRunRefusalReason.java | 19 +- .../core/domain/run/InstrumentRunStatus.java | 19 +- .../core/domain/run/InstrumentRunValue.java | 351 +++-- .../core/domain/run/ParticipantInterview.java | 111 +- .../jade/core/domain/run/ValueIntegrity.java | 19 +- .../service/ActiveInstrumentRunService.java | 281 ++-- .../core/service/InputDataSourceVisitor.java | 31 +- .../jade/core/service/InputSourceVisitor.java | 51 +- .../service/InstrumentDescriptorService.java | 53 +- .../core/service/InstrumentRunService.java | 115 +- .../jade/core/service/InstrumentService.java | 177 ++- ...DefaultActiveInstrumentRunServiceImpl.java | 635 ++++---- ...efaultInstrumentDescriptorServiceImpl.java | 75 +- .../impl/DefaultInstrumentRunServiceImpl.java | 73 +- .../impl/DefaultInstrumentServiceImpl.java | 185 +-- .../impl/InputDataSourceVisitorImpl.java | 259 ++-- .../InstrumentRunServiceHibernateImpl.java | 123 +- .../onyx/jade/core/wicket/JadePanel.java | 285 ++-- .../AskedContraIndicationPanel.java | 319 ++-- .../wicket/instrument/ConclusionPanel.java | 75 +- .../instrument/ContraIndicatedPanel.java | 89 +- .../InstrumentBarcodeConverter.java | 135 +- .../InstrumentInputParameterPanel.java | 585 +++---- .../instrument/InstrumentLaunchPanel.java | 299 ++-- .../wicket/instrument/InstrumentLauncher.java | 323 ++-- .../InstrumentOutputParameterPanel.java | 189 +-- .../wicket/instrument/InstrumentSelector.java | 171 +- .../ObservedContraIndicationPanel.java | 375 ++--- .../wicket/instrument/RunValueLabelModel.java | 43 +- .../validation/IntegrityCheckValidator.java | 197 +-- .../core/wicket/run/InstrumentRunPanel.java | 343 ++-- .../core/wicket/seed/JadeDatabaseSeed.java | 317 ++-- .../wizard/AbstractContraIndicationStep.java | 133 +- .../wizard/AskedContraIndicationStep.java | 95 +- .../core/wicket/wizard/ConclusionStep.java | 97 +- .../wicket/wizard/ContraIndicatedStep.java | 107 +- .../wicket/wizard/InputParametersStep.java | 95 +- .../wicket/wizard/InstrumentLaunchStep.java | 335 ++-- .../wizard/InstrumentSelectionStep.java | 149 +- .../wicket/wizard/InstrumentWizardForm.java | 443 +++--- .../wizard/ObservedContraIndicationStep.java | 79 +- .../wicket/wizard/OutputParametersStep.java | 245 +-- .../jade/core/wicket/wizard/WarningsStep.java | 177 ++- .../obiba/onyx/jade/engine/JadeModule.java | 9 + .../jade/engine/state/JadeCompletedState.java | 11 +- .../state/JadeContraIndicatedState.java | 115 +- .../engine/state/JadeInProgressState.java | 11 +- .../engine/state/JadeNotApplicableState.java | 67 +- .../jade/engine/state/JadeReadyState.java | 11 +- .../jade/engine/state/JadeSkippedState.java | 11 +- .../state/JadeStageDependencyCondition.java | 155 +- .../jade/engine/state/JadeWaitingState.java | 11 +- .../domain/instrument/InputSourceTest.java | 241 +-- .../instrument/InstrumentParameterTest.java | 187 +-- .../validation/EqualsParameterCheckTest.java | 257 +-- .../validation/EqualsValueCheckTest.java | 445 +++--- .../validation/ParameterSpreadCheckTest.java | 651 ++++---- .../instrument/validation/RangeCheckTest.java | 639 ++++---- .../core/service/InstrumentServiceTest.java | 117 +- .../engine/state/JadeSkippedStateTest.java | 115 +- .../JadeStageDependencyConditionTest.java | 349 +++-- .../service/InstrumentExecutionService.java | 9 + .../InstrumentExecutionServiceImpl.java | 203 +-- .../InstrumentExecutionServiceTest.java | 195 +-- .../MockActiveInstrumentRunServiceImpl.java | 259 ++-- .../core/service/ActiveConsentService.java | 37 +- .../impl/DefaultActiveConsentServiceImpl.java | 67 +- .../onyx/marble/core/wicket/MarblePanel.java | 287 ++-- .../consent/ConsentConfirmationPanel.java | 125 +- .../consent/ConsentModeSelectionPanel.java | 181 +-- .../consent/ElectronicConsentPanel.java | 47 +- .../wizard/ConsentConfirmationStep.java | 87 +- .../wizard/ConsentModeSelectionStep.java | 123 +- .../core/wicket/wizard/ConsentWizardForm.java | 181 +-- .../wicket/wizard/ElectronicConsentStep.java | 105 +- .../onyx/marble/domain/consent/Consent.java | 123 +- .../marble/domain/consent/ConsentMode.java | 19 +- .../onyx/marble/engine/MarbleModule.java | 135 +- .../state/AbstractMarbleStageState.java | 73 +- .../engine/state/MarbleCompletedState.java | 11 +- .../engine/state/MarbleInProgressState.java | 11 +- .../marble/engine/state/MarbleReadyState.java | 11 +- .../core/service/ActiveConclusionService.java | 31 +- .../DefaultActiveConclusionServiceImpl.java | 63 +- .../onyx/mica/core/wicket/MicaPanel.java | 209 +-- .../obiba/onyx/mica/engine/MicaModule.java | 185 +-- .../engine/state/AbstractMicaStageState.java | 85 +- .../mica/engine/state/MicaCompletedState.java | 83 +- .../engine/state/MicaInProgressState.java | 111 +- .../mica/engine/state/MicaReadyState.java | 101 +- .../mica/engine/state/MicaWaitingState.java | 11 +- .../state/ModuleStageDependencyCondition.java | 187 +-- .../core/domain/answer/CategoryAnswer.java | 265 ++-- .../core/domain/answer/QuestionAnswer.java | 9 + .../answer/QuestionnaireParticipant.java | 9 + .../engine/questionnaire/IAnswerListener.java | 9 + .../engine/questionnaire/ILocalizable.java | 41 +- .../core/engine/questionnaire/IVisitable.java | 45 +- .../core/engine/questionnaire/IVisitor.java | 73 +- .../questionnaire/answer/AnswerSource.java | 9 + .../questionnaire/answer/FixedSource.java | 9 + .../answer/ParticipantPropertySource.java | 9 + .../questionnaire/answer/TimestampSource.java | 9 + .../questionnaire/answer/TimestampType.java | 9 + .../bundle/QuestionnaireBundle.java | 185 +-- .../bundle/QuestionnaireBundleManager.java | 73 +- .../bundle/impl/QuestionnaireBundleImpl.java | 473 +++--- .../impl/QuestionnaireBundleManagerImpl.java | 643 ++++---- .../condition/AnswerCondition.java | 9 + .../condition/ComparisionOperator.java | 9 + .../questionnaire/condition/Condition.java | 9 + .../condition/ConditionOperator.java | 9 + .../condition/DataComparator.java | 71 +- .../condition/MultipleCondition.java | 9 + .../condition/NoAnswerCondition.java | 51 +- .../questionnaire/question/Category.java | 9 + .../question/OpenAnswerDefinition.java | 9 + .../engine/questionnaire/question/Page.java | 9 + .../questionnaire/question/Question.java | 9 + .../question/QuestionCategory.java | 9 + .../questionnaire/question/Questionnaire.java | 9 + .../questionnaire/question/Section.java | 9 + .../questionnaire/util/IWalkerVisitor.java | 47 +- .../util/QuestionnaireBuilder.java | 295 ++-- .../util/QuestionnaireFinder.java | 295 ++-- .../util/QuestionnaireStreamer.java | 253 +-- .../util/QuestionnaireWalker.java | 275 ++-- .../AbstractQuestionnaireElementBuilder.java | 207 +-- .../util/builder/CategoryBuilder.java | 379 ++--- .../util/builder/IPropertyKeyWriter.java | 97 +- .../builder/OpenAnswerDefinitionBuilder.java | 353 ++--- .../util/builder/PageBuilder.java | 287 ++-- .../builder/PropertyKeyWriterVisitor.java | 271 ++-- .../util/builder/QuestionBuilder.java | 535 +++---- .../util/builder/SectionBuilder.java | 225 +-- .../OutputStreamPropertyKeyWriterImpl.java | 105 +- .../impl/PropertiesPropertyKeyWriterImpl.java | 123 +- .../util/finder/AbstractFinderVisitor.java | 211 +-- .../util/finder/CategoryFinder.java | 223 +-- .../finder/OpenAnswerDefinitionFinder.java | 123 +- .../questionnaire/util/finder/PageFinder.java | 123 +- .../util/finder/QuestionFinder.java | 123 +- .../util/finder/SectionFinder.java | 123 +- .../localization/IPropertyKeyProvider.java | 69 +- .../impl/DefaultPropertyKeyProviderImpl.java | 361 ++--- ...iveQuestionnaireAdministrationService.java | 87 +- .../core/service/INavigationStrategy.java | 115 +- .../QuestionnaireParticipantService.java | 55 +- ...uestionnaireAdministrationServiceImpl.java | 201 +-- .../impl/DefaultNavigationStrategyImpl.java | 327 ++-- ...ltQuestionnaireParticipantServiceImpl.java | 91 +- .../impl/NavigationStrategySupport.java | 107 +- ...nnaireParticipantServiceHibernateImpl.java | 75 +- .../onyx/quartz/core/wicket/QuartzPanel.java | 247 +-- .../wicket/layout/IPageLayoutFactory.java | 41 +- .../wicket/layout/IQuestionPanelFactory.java | 31 +- .../quartz/core/wicket/layout/PageLayout.java | 65 +- .../layout/PageLayoutFactoryRegistry.java | 67 +- .../wicket/layout/PageQuestionsProvider.java | 87 +- .../core/wicket/layout/QuestionPanel.java | 65 +- .../layout/QuestionPanelFactoryRegistry.java | 67 +- ...ionnaireUIFactoryRegistrationListener.java | 157 +- .../wicket/layout/impl/DefaultPageLayout.java | 131 +- .../layout/impl/DefaultPageLayoutFactory.java | 45 +- .../impl/DefaultQuestionPanelFactory.java | 55 +- .../impl/MultipleChoiceQuestionPanel.java | 71 +- .../impl/SingleChoiceQuestionPanel.java | 207 +-- .../QuestionnaireStringResourceModel.java | 241 +-- .../questionnaire/LanguageSelectorPanel.java | 147 +- .../core/wicket/wizard/ConclusionStep.java | 89 +- .../wicket/wizard/LanguageSelectionStep.java | 131 +- .../core/wicket/wizard/PageStepPanel.java | 9 + .../wizard/QuestionnaireWizardForm.java | 211 +-- .../onyx/quartz/engine/QuartzModule.java | 231 +-- .../engine/state/QuartzCompletedState.java | 161 +- .../engine/state/QuartzInProgressState.java | 171 +- .../engine/state/QuartzInterruptedState.java | 141 +- .../state/QuartzNotApplicableState.java | 77 +- .../quartz/engine/state/QuartzReadyState.java | 119 +- .../engine/state/QuartzSkippedState.java | 161 +- .../state/QuartzStageDependencyCondition.java | 87 +- .../engine/state/QuartzWaitingState.java | 69 +- .../impl/QuestionnaireBundleImplTest.java | 257 +-- .../QuestionnaireBundleManagerImplTest.java | 261 ++-- .../util/QuestionnaireBuilderTest.java | 9 + .../util/QuestionnaireStreamerTest.java | 9 + .../QuestionnaireLocalizationTest.java | 143 +- ...uestionnaireAdministrationServiceTest.java | 119 +- .../QuestionnaireParticipantServiceTest.java | 97 +- .../quartz/core/wicket/QuartzPanelTest.java | 333 ++-- .../QuestionnaireStringResourceModelTest.java | 377 ++--- .../state/QuartzCompletedStateTest.java | 285 ++-- .../state/QuartzInProgressStateTest.java | 241 +-- .../state/QuartzInterruptedStateTest.java | 285 ++-- ...tringReferenceCompatibleMessageFormat.java | 109 +- .../java/org/obiba/onyx/util/StringUtil.java | 85 +- .../java/org/obiba/onyx/util/data/Data.java | 315 ++-- .../org/obiba/onyx/util/data/DataBuilder.java | 239 +-- .../org/obiba/onyx/util/data/DataType.java | 19 +- .../onyx/util/testconfig/CustomScope.java | 57 +- .../obiba/onyx/util/data/DataBuilderTest.java | 199 +-- .../obiba/onyx/webapp/OnyxApplication.java | 355 ++--- .../onyx/webapp/OnyxAuthenticatedSession.java | 9 + .../webapp/action/panel/ActionsPanel.java | 103 +- .../authentication/UserRolesAuthorizer.java | 39 +- .../obiba/onyx/webapp/base/page/BasePage.java | 145 +- .../base/panel/AjaxLanguageChoicePanel.java | 9 + .../onyx/webapp/base/panel/HeaderPanel.java | 9 + .../obiba/onyx/webapp/base/panel/MenuBar.java | 11 +- .../onyx/webapp/base/panel/MenuBuilder.java | 9 + .../onyx/webapp/base/panel/MenuItem.java | 11 +- .../page/ApplicationConfigurationPage.java | 519 ++++--- .../obiba/onyx/webapp/home/page/HomePage.java | 155 +- .../onyx/webapp/login/page/LoginPage.java | 43 +- .../onyx/webapp/login/panel/LoginPanel.java | 11 +- .../onyx/webapp/panel/OnyxEntityList.java | 63 +- .../participant/page/InterviewPage.java | 453 +++--- .../page/ParticipantReceptionPage.java | 115 +- .../page/ParticipantSearchPage.java | 947 ++++++------ .../panel/AssignCodeToParticipantPanel.java | 243 +-- .../participant/panel/CommentsModalPanel.java | 441 +++--- .../panel/EditParticipantPanel.java | 379 ++--- .../panel/ParticipantModalPanel.java | 57 +- .../participant/panel/ParticipantPanel.java | 111 +- .../onyx/webapp/seed/OnyxDatabaseSeed.java | 103 +- .../onyx/webapp/seed/TestDatabaseSeed.java | 207 +-- .../service/impl/UserSessionServiceImpl.java | 55 +- .../onyx/webapp/stage/page/StagePage.java | 179 ++- .../webapp/stage/panel/StageHeaderPanel.java | 39 +- .../onyx/webapp/stage/panel/StageMenuBar.java | 73 +- .../stage/panel/StageSelectionPanel.java | 469 +++--- .../stage/panel/StageStartEndTimePanel.java | 127 +- .../stage/panel/ViewCommentsActionPanel.java | 59 +- .../onyx/webapp/user/page/ProfilePage.java | 147 +- .../onyx/webapp/user/page/UserSearchPage.java | 495 +++--- .../user/panel/ChangePasswordPanel.java | 275 ++-- .../webapp/user/panel/UserModalPanel.java | 39 +- .../onyx/webapp/user/panel/UserPanel.java | 421 ++--- .../panel/CommentsModalPanelTest.java | 487 +++--- .../panel/EditParticipantPanelTest.java | 193 +-- .../onyx/webapp/user/panel/UserPanelTest.java | 449 +++--- 366 files changed, 34307 insertions(+), 30348 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..20d40b6bc --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/etl/participant/ParticipantExcelReader.java b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/etl/participant/ParticipantExcelReader.java index 410c7d30d..d1f5849f3 100644 --- a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/etl/participant/ParticipantExcelReader.java +++ b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/etl/participant/ParticipantExcelReader.java @@ -1,51 +1,60 @@ -package org.obiba.onyx.cartagene.etl.participant; - -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.obiba.onyx.core.domain.participant.Appointment; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.participant.Province; -import org.obiba.onyx.core.etl.participant.AbstractParticipantExcelReader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ParticipantExcelReader extends AbstractParticipantExcelReader { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ParticipantExcelReader.class); - - protected Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator) { - Participant participant = new Participant(); - - participant.setSiteNo(getTextValue(row, evaluator, row.getCell(2))); - participant.setFirstName(getTextValue(row, evaluator, row.getCell(5))); - participant.setLastName(getTextValue(row, evaluator, row.getCell(4))); - Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); - participant.setEnrollmentId(id == null ? null : id.toString()); - participant.setBirthDate(getDateValue(row, evaluator, row.getCell(7))); - String gender = getTextValue(row, evaluator, row.getCell(6)); - if(gender.equals("M")) { - participant.setGender(Gender.MALE); - } else if(gender.equals("F")) { - participant.setGender(Gender.FEMALE); - } - participant.setStreet(getTextValue(row, evaluator, row.getCell(8))); - participant.setCity(getTextValue(row, evaluator, row.getCell(9))); - participant.setProvince(Province.valueOf(getTextValue(row, evaluator, row.getCell(10)))); - participant.setCountry(getTextValue(row, evaluator, row.getCell(11))); - participant.setPostalCode(getTextValue(row, evaluator, row.getCell(12))); - participant.setPhone(getTextValue(row, evaluator, row.getCell(13))); - - return participant; - } - - protected Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator) { - Appointment appointment = new Appointment(); - - appointment.setAppointmentCode(getTextValue(row, evaluator, row.getCell(3))); - appointment.setDate(getDateValue(row, evaluator, row.getCell(0))); - - return appointment; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.cartagene.etl.participant; + +import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.obiba.onyx.core.domain.participant.Appointment; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.participant.Province; +import org.obiba.onyx.core.etl.participant.AbstractParticipantExcelReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ParticipantExcelReader extends AbstractParticipantExcelReader { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ParticipantExcelReader.class); + + protected Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator) { + Participant participant = new Participant(); + + participant.setSiteNo(getTextValue(row, evaluator, row.getCell(2))); + participant.setFirstName(getTextValue(row, evaluator, row.getCell(5))); + participant.setLastName(getTextValue(row, evaluator, row.getCell(4))); + Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); + participant.setEnrollmentId(id == null ? null : id.toString()); + participant.setBirthDate(getDateValue(row, evaluator, row.getCell(7))); + String gender = getTextValue(row, evaluator, row.getCell(6)); + if(gender.equals("M")) { + participant.setGender(Gender.MALE); + } else if(gender.equals("F")) { + participant.setGender(Gender.FEMALE); + } + participant.setStreet(getTextValue(row, evaluator, row.getCell(8))); + participant.setCity(getTextValue(row, evaluator, row.getCell(9))); + participant.setProvince(Province.valueOf(getTextValue(row, evaluator, row.getCell(10)))); + participant.setCountry(getTextValue(row, evaluator, row.getCell(11))); + participant.setPostalCode(getTextValue(row, evaluator, row.getCell(12))); + participant.setPhone(getTextValue(row, evaluator, row.getCell(13))); + + return participant; + } + + protected Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator) { + Appointment appointment = new Appointment(); + + appointment.setAppointmentCode(getTextValue(row, evaluator, row.getCell(3))); + appointment.setDate(getDateValue(row, evaluator, row.getCell(0))); + + return appointment; + } +} diff --git a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/hibernate/util/CreateDDL.java b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/hibernate/util/CreateDDL.java index bcadffe17..bd573aeab 100644 --- a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/hibernate/util/CreateDDL.java +++ b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/hibernate/util/CreateDDL.java @@ -1,114 +1,123 @@ -package org.obiba.onyx.cartagene.hibernate.util; - -import java.io.ByteArrayInputStream; -import java.util.Properties; -import java.util.Set; - -import org.hibernate.cfg.AnnotationConfiguration; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.ImprovedNamingStrategy; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.FileSystemResource; - -public class CreateDDL { - - // System constants for the current platform directory token - static String fileSep = System.getProperty("file.separator"); - - private String path = ""; - - private static GenericApplicationContext appContext; - - public static void main(String args[]) { - - // Create application context. - appContext = loadAppContext(); - - CreateDDL c = new CreateDDL(); - c.createDDL(); - System.err.println("Finish"); - } - - protected static GenericApplicationContext loadAppContext() { - - // Load bootstrap context files. - GenericApplicationContext appContext = new GenericApplicationContext(); - XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext); - xmlReader.loadBeanDefinitions(new FileSystemResource("src/main/webapp/WEB-INF/spring/context.xml")); - appContext.refresh(); - - return appContext; - } - - protected static Properties loadServiceParams(String[] args) { - - Properties params = new Properties(); - try { - - params.loadFromXML(new ByteArrayInputStream(args[0].getBytes("UTF-8"))); - return params; - - } catch(Exception wErrorLoadingXml) { - throw new RuntimeException("Error! Client was unable to load application parameters."); - } - - } - - public CreateDDL() { - } - - private AnnotationConfiguration getConfiguration() { - try { - AnnotationConfiguration conf = new AnnotationConfiguration(); - - Set> annotatedClasses = (Set>) appContext.getBean("annotatedHibernateClasses"); - for(Class cl : annotatedClasses) { - conf.addAnnotatedClass(cl); - } - - // naming strategie - conf.setNamingStrategy(ImprovedNamingStrategy.INSTANCE); - - Properties props = new Properties(); - props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect"); - - conf.addProperties(props); - return conf; - } catch(Throwable ex) { - // Log exception! - throw new ExceptionInInitializerError(ex); - } - } - - /** - * Loads the Hibernate configuration information, sets up the database and the Hibernate session factory. - */ - public void createDDL() { - System.out.println("testCreateDDL"); - try { - Configuration conf = getConfiguration(); - String dialect_file = "mysql.sql"; - - System.out.println("Generating: " + dialect_file); - SchemaExport mySchemaExport = new SchemaExport(conf, conf.buildSettings()); - mySchemaExport.setDelimiter(";"); - - // Despite the name, the generated create - // scripts WILL include drop statements at - // the top of the script! - mySchemaExport.setOutputFile(path + "create_" + dialect_file); - mySchemaExport.create(false, false); - - // Generates DROP statements only - mySchemaExport.setOutputFile(path + "drop_" + dialect_file); - mySchemaExport.drop(false, false); - - System.out.println(dialect_file + " OK."); - } catch(Exception e) { - e.printStackTrace(); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.cartagene.hibernate.util; + +import java.io.ByteArrayInputStream; +import java.util.Properties; +import java.util.Set; + +import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.ImprovedNamingStrategy; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.FileSystemResource; + +public class CreateDDL { + + // System constants for the current platform directory token + static String fileSep = System.getProperty("file.separator"); + + private String path = ""; + + private static GenericApplicationContext appContext; + + public static void main(String args[]) { + + // Create application context. + appContext = loadAppContext(); + + CreateDDL c = new CreateDDL(); + c.createDDL(); + System.err.println("Finish"); + } + + protected static GenericApplicationContext loadAppContext() { + + // Load bootstrap context files. + GenericApplicationContext appContext = new GenericApplicationContext(); + XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext); + xmlReader.loadBeanDefinitions(new FileSystemResource("src/main/webapp/WEB-INF/spring/context.xml")); + appContext.refresh(); + + return appContext; + } + + protected static Properties loadServiceParams(String[] args) { + + Properties params = new Properties(); + try { + + params.loadFromXML(new ByteArrayInputStream(args[0].getBytes("UTF-8"))); + return params; + + } catch(Exception wErrorLoadingXml) { + throw new RuntimeException("Error! Client was unable to load application parameters."); + } + + } + + public CreateDDL() { + } + + private AnnotationConfiguration getConfiguration() { + try { + AnnotationConfiguration conf = new AnnotationConfiguration(); + + Set> annotatedClasses = (Set>) appContext.getBean("annotatedHibernateClasses"); + for(Class cl : annotatedClasses) { + conf.addAnnotatedClass(cl); + } + + // naming strategie + conf.setNamingStrategy(ImprovedNamingStrategy.INSTANCE); + + Properties props = new Properties(); + props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect"); + + conf.addProperties(props); + return conf; + } catch(Throwable ex) { + // Log exception! + throw new ExceptionInInitializerError(ex); + } + } + + /** + * Loads the Hibernate configuration information, sets up the database and the Hibernate session factory. + */ + public void createDDL() { + System.out.println("testCreateDDL"); + try { + Configuration conf = getConfiguration(); + String dialect_file = "mysql.sql"; + + System.out.println("Generating: " + dialect_file); + SchemaExport mySchemaExport = new SchemaExport(conf, conf.buildSettings()); + mySchemaExport.setDelimiter(";"); + + // Despite the name, the generated create + // scripts WILL include drop statements at + // the top of the script! + mySchemaExport.setOutputFile(path + "create_" + dialect_file); + mySchemaExport.create(false, false); + + // Generates DROP statements only + mySchemaExport.setOutputFile(path + "drop_" + dialect_file); + mySchemaExport.drop(false, false); + + System.out.println(dialect_file + " OK."); + } catch(Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/questionnaire/util/CreateQuestionnaire.java b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/questionnaire/util/CreateQuestionnaire.java index 1a1b8de82..99855c1ad 100644 --- a/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/questionnaire/util/CreateQuestionnaire.java +++ b/cartagene-webapp/src/main/java/org/obiba/onyx/cartagene/questionnaire/util/CreateQuestionnaire.java @@ -1,168 +1,177 @@ -package org.obiba.onyx.cartagene.questionnaire.util; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl.QuestionnaireBundleManagerImpl; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; -import org.obiba.onyx.util.data.DataType; - -public class CreateQuestionnaire { - - private File bundleRootDirectory = new File("target", "questionnaires"); - - private QuestionnaireBundle bundle; - - private static final String NO = "NO"; - - private static final String YES = "YES"; - - private static final String OTHER = "OTHER"; - - private static final String FULL_TIME = "FULL_TIME"; - - private static final String PART_TIME = "PART_TIME"; - - private static final String NO_ANSWER = "NO_ANSWER"; - - private static final String DONT_KNOW = "DONT_KNOW"; - - public static void main(String args[]) { - CreateQuestionnaire c = new CreateQuestionnaire(); - c.createQuestionnaire(); - } - - public CreateQuestionnaire() { - } - - public void createQuestionnaire() { - QuestionnaireBuilder builder = QuestionnaireBuilder.createQuestionnaire("HealthQuestionnaire", "1.0"); - - builder.withSection("SB").withSection("GENDER").withPage("P1").withQuestion("Q1").withCategories("1", "2"); - builder.inQuestion("Q1").withSharedCategory(OTHER).setExportName("3"); - builder.inQuestion("Q1").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q1").withSharedCategory(DONT_KNOW).setExportName("9"); - - builder.inSection("SB").withSection("BIRTHDATE").withPage("P2").withQuestion("Q2").withCategory("1").withOpenAnswerDefinition("year", DataType.INTEGER).setOpenAnswerDefinitionFormat("YYYY"); - builder.inQuestion("Q2").withSharedCategory(NO_ANSWER).setExportName("8888"); - builder.inQuestion("Q2").withSharedCategory(DONT_KNOW).setExportName("9999"); - builder.inSection("BIRTHDATE").withPage("P3").withQuestion("Q3").withCategory("1").withOpenAnswerDefinition("month", DataType.INTEGER).setOpenAnswerDefinitionFormat("MM"); - builder.inQuestion("Q3").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q3").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("BIRTHDATE").withPage("P4").withQuestion("Q4").withCategory("1").withOpenAnswerDefinition("age", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("40", "70"); - builder.inQuestion("Q4").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q4").withSharedCategory(DONT_KNOW).setExportName("99"); - - builder.inSection("SB").withSection("MARITALSTATUS").withPage("P5").withQuestion("Q5").withCategories("1", "2", "3", "4", "5"); - builder.inQuestion("Q5").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q5").withSharedCategory(DONT_KNOW).setExportName("99"); - - builder.inSection("SB").withSection("HOUSEHOLDSTATUS").withPage("P6").withQuestion("Q6").withCategory("1").withOpenAnswerDefinition("adults", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("1", "100"); - builder.inQuestion("Q6").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q6").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("HOUSEHOLDSTATUS").withPage("P7").withQuestion("Q7").withCategory("1").withOpenAnswerDefinition("children", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "100"); - builder.inQuestion("Q7").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q7").withSharedCategory(DONT_KNOW).setExportName("99"); - - builder.inSection("SB").withSection("SIBLING").withPage("P8").withQuestion("Q8").withCategory("1").withOpenAnswerDefinition("siblings", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); - builder.inQuestion("Q8").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q8").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("SIBLING").withPage("P9").withQuestion("Q9").withCategory("1").withOpenAnswerDefinition("olderSiblings", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); - builder.inQuestion("Q9").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q9").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("SIBLING").withPage("P10").withQuestion("Q10").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q10").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q10").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q10").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inSection("SIBLING").withPage("P11").withQuestion("Q11").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q11").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q11").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q11").withSharedCategory(DONT_KNOW).setExportName("9"); - - builder.inSection("SB").withSection("EDUCATIONLEVEL").withPage("P12").withQuestion("Q12"); - builder.inSection("EDUCATIONLEVEL").withPage("P13").withQuestion("Q13").withCategory("1").withOpenAnswerDefinition("years", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); - builder.inQuestion("Q13").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q13").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("EDUCATIONLEVEL").withPage("P14").withQuestion("Q14").withCategories("1", "2", "3", "4", "5", "6", "7", "8"); - builder.inQuestion("Q14").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q14").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("EDUCATIONLEVEL").withPage("P15").withQuestion("Q15").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q15").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q15").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q15").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inSection("SB").withSection("WORKINGSTATUS").withPage("P16").withQuestion("Q16"); - builder.inSection("WORKINGSTATUS").withPage("P17").withQuestion("GLOBAL"); - builder.inQuestion("GLOBAL").withQuestion("Q17").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q17").withSharedCategory(FULL_TIME).setExportName("1"); - builder.inQuestion("Q17").withSharedCategory(PART_TIME).setExportName("2"); - builder.inQuestion("Q17").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q17").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q18").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q18").withSharedCategory(FULL_TIME).setExportName("1"); - builder.inQuestion("Q18").withSharedCategory(PART_TIME).setExportName("2"); - builder.inQuestion("Q18").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q18").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q19").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q19").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q19").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q19").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q20").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q20").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q20").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q20").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q21").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q21").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q21").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q21").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q22").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q22").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q22").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q22").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q23").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q23").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q23").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q23").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inQuestion("GLOBAL").withQuestion("Q24").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q24").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q24").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q24").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inSection("WORKINGSTATUS").withPage("P18").withQuestion("Q25").withCategory("1").withOpenAnswerDefinition("job", DataType.TEXT); - builder.inQuestion("Q25").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q25").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("WORKINGSTATUS").withPage("P19").withQuestion("Q26").withCategories("1", "2", "3", "4", "5", "6", "7", "8"); - builder.inQuestion("Q26").withSharedCategory(OTHER).setExportName("9"); - builder.inQuestion("Q26").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q26").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("WORKINGSTATUS").withPage("P20").withQuestion("Q27").withCategory("1").withOpenAnswerDefinition("specify", DataType.TEXT); - builder.inQuestion("Q27").withSharedCategory(NO_ANSWER).setExportName("88"); - builder.inQuestion("Q27").withSharedCategory(DONT_KNOW).setExportName("99"); - builder.inSection("WORKINGSTATUS").withPage("P21").withQuestion("Q28").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q28").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q28").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q28").withSharedCategory(DONT_KNOW).setExportName("9"); - builder.inSection("WORKINGSTATUS").withPage("P22").withQuestion("Q29").withSharedCategory(NO).setExportName("0"); - builder.inQuestion("Q29").withSharedCategory(YES).setExportName("1"); - builder.inQuestion("Q29").withSharedCategory(NO_ANSWER).setExportName("8"); - builder.inQuestion("Q29").withSharedCategory(DONT_KNOW).setExportName("9"); - - // Create the bundle manager. - QuestionnaireBundleManager bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); - ((QuestionnaireBundleManagerImpl) bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); - - // Create the bundle questionnaire. - try { - bundle = bundleManager.createBundle(builder.getQuestionnaire()); - } catch(IOException e) { - e.printStackTrace(); - } - - bundle.setLanguage(Locale.ENGLISH, new Properties()); - bundle.setLanguage(Locale.FRENCH, new Properties()); - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.cartagene.questionnaire.util; + +import java.io.File; +import java.io.IOException; +import java.util.Locale; +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl.QuestionnaireBundleManagerImpl; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; +import org.obiba.onyx.util.data.DataType; + +public class CreateQuestionnaire { + + private File bundleRootDirectory = new File("target", "questionnaires"); + + private QuestionnaireBundle bundle; + + private static final String NO = "NO"; + + private static final String YES = "YES"; + + private static final String OTHER = "OTHER"; + + private static final String FULL_TIME = "FULL_TIME"; + + private static final String PART_TIME = "PART_TIME"; + + private static final String NO_ANSWER = "NO_ANSWER"; + + private static final String DONT_KNOW = "DONT_KNOW"; + + public static void main(String args[]) { + CreateQuestionnaire c = new CreateQuestionnaire(); + c.createQuestionnaire(); + } + + public CreateQuestionnaire() { + } + + public void createQuestionnaire() { + QuestionnaireBuilder builder = QuestionnaireBuilder.createQuestionnaire("HealthQuestionnaire", "1.0"); + + builder.withSection("SB").withSection("GENDER").withPage("P1").withQuestion("Q1").withCategories("1", "2"); + builder.inQuestion("Q1").withSharedCategory(OTHER).setExportName("3"); + builder.inQuestion("Q1").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q1").withSharedCategory(DONT_KNOW).setExportName("9"); + + builder.inSection("SB").withSection("BIRTHDATE").withPage("P2").withQuestion("Q2").withCategory("1").withOpenAnswerDefinition("year", DataType.INTEGER).setOpenAnswerDefinitionFormat("YYYY"); + builder.inQuestion("Q2").withSharedCategory(NO_ANSWER).setExportName("8888"); + builder.inQuestion("Q2").withSharedCategory(DONT_KNOW).setExportName("9999"); + builder.inSection("BIRTHDATE").withPage("P3").withQuestion("Q3").withCategory("1").withOpenAnswerDefinition("month", DataType.INTEGER).setOpenAnswerDefinitionFormat("MM"); + builder.inQuestion("Q3").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q3").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("BIRTHDATE").withPage("P4").withQuestion("Q4").withCategory("1").withOpenAnswerDefinition("age", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("40", "70"); + builder.inQuestion("Q4").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q4").withSharedCategory(DONT_KNOW).setExportName("99"); + + builder.inSection("SB").withSection("MARITALSTATUS").withPage("P5").withQuestion("Q5").withCategories("1", "2", "3", "4", "5"); + builder.inQuestion("Q5").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q5").withSharedCategory(DONT_KNOW).setExportName("99"); + + builder.inSection("SB").withSection("HOUSEHOLDSTATUS").withPage("P6").withQuestion("Q6").withCategory("1").withOpenAnswerDefinition("adults", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("1", "100"); + builder.inQuestion("Q6").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q6").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("HOUSEHOLDSTATUS").withPage("P7").withQuestion("Q7").withCategory("1").withOpenAnswerDefinition("children", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "100"); + builder.inQuestion("Q7").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q7").withSharedCategory(DONT_KNOW).setExportName("99"); + + builder.inSection("SB").withSection("SIBLING").withPage("P8").withQuestion("Q8").withCategory("1").withOpenAnswerDefinition("siblings", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); + builder.inQuestion("Q8").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q8").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("SIBLING").withPage("P9").withQuestion("Q9").withCategory("1").withOpenAnswerDefinition("olderSiblings", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); + builder.inQuestion("Q9").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q9").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("SIBLING").withPage("P10").withQuestion("Q10").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q10").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q10").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q10").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inSection("SIBLING").withPage("P11").withQuestion("Q11").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q11").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q11").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q11").withSharedCategory(DONT_KNOW).setExportName("9"); + + builder.inSection("SB").withSection("EDUCATIONLEVEL").withPage("P12").withQuestion("Q12"); + builder.inSection("EDUCATIONLEVEL").withPage("P13").withQuestion("Q13").withCategory("1").withOpenAnswerDefinition("years", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues("0", "20"); + builder.inQuestion("Q13").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q13").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("EDUCATIONLEVEL").withPage("P14").withQuestion("Q14").withCategories("1", "2", "3", "4", "5", "6", "7", "8"); + builder.inQuestion("Q14").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q14").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("EDUCATIONLEVEL").withPage("P15").withQuestion("Q15").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q15").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q15").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q15").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inSection("SB").withSection("WORKINGSTATUS").withPage("P16").withQuestion("Q16"); + builder.inSection("WORKINGSTATUS").withPage("P17").withQuestion("GLOBAL"); + builder.inQuestion("GLOBAL").withQuestion("Q17").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q17").withSharedCategory(FULL_TIME).setExportName("1"); + builder.inQuestion("Q17").withSharedCategory(PART_TIME).setExportName("2"); + builder.inQuestion("Q17").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q17").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q18").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q18").withSharedCategory(FULL_TIME).setExportName("1"); + builder.inQuestion("Q18").withSharedCategory(PART_TIME).setExportName("2"); + builder.inQuestion("Q18").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q18").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q19").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q19").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q19").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q19").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q20").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q20").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q20").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q20").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q21").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q21").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q21").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q21").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q22").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q22").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q22").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q22").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q23").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q23").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q23").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q23").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inQuestion("GLOBAL").withQuestion("Q24").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q24").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q24").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q24").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inSection("WORKINGSTATUS").withPage("P18").withQuestion("Q25").withCategory("1").withOpenAnswerDefinition("job", DataType.TEXT); + builder.inQuestion("Q25").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q25").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("WORKINGSTATUS").withPage("P19").withQuestion("Q26").withCategories("1", "2", "3", "4", "5", "6", "7", "8"); + builder.inQuestion("Q26").withSharedCategory(OTHER).setExportName("9"); + builder.inQuestion("Q26").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q26").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("WORKINGSTATUS").withPage("P20").withQuestion("Q27").withCategory("1").withOpenAnswerDefinition("specify", DataType.TEXT); + builder.inQuestion("Q27").withSharedCategory(NO_ANSWER).setExportName("88"); + builder.inQuestion("Q27").withSharedCategory(DONT_KNOW).setExportName("99"); + builder.inSection("WORKINGSTATUS").withPage("P21").withQuestion("Q28").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q28").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q28").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q28").withSharedCategory(DONT_KNOW).setExportName("9"); + builder.inSection("WORKINGSTATUS").withPage("P22").withQuestion("Q29").withSharedCategory(NO).setExportName("0"); + builder.inQuestion("Q29").withSharedCategory(YES).setExportName("1"); + builder.inQuestion("Q29").withSharedCategory(NO_ANSWER).setExportName("8"); + builder.inQuestion("Q29").withSharedCategory(DONT_KNOW).setExportName("9"); + + // Create the bundle manager. + QuestionnaireBundleManager bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); + ((QuestionnaireBundleManagerImpl) bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); + + // Create the bundle questionnaire. + try { + bundle = bundleManager.createBundle(builder.getQuestionnaire()); + } catch(IOException e) { + e.printStackTrace(); + } + + bundle.setLanguage(Locale.ENGLISH, new Properties()); + bundle.setLanguage(Locale.FRENCH, new Properties()); + + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/IMemento.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/IMemento.java index b2e4cc4c1..07a7b3149 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/IMemento.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/IMemento.java @@ -1,25 +1,34 @@ -package org.obiba.onyx.core.domain; - -import org.obiba.core.domain.IEntity; - -/** - * This interface must be implemented to support persistence by memeto pattern. - * @author Yannick Marcon - * - */ -public interface IMemento { - - /** - * Save the state into the memento. - * @param memento to be created if null, to be updated if not - * @return the memto to persist - */ - public IEntity saveToMemento(IEntity memento); - - /** - * Given the memento, restore the persisted state. - * @param memento - */ - public void restoreFromMemento(IEntity memento); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain; + +import org.obiba.core.domain.IEntity; + +/** + * This interface must be implemented to support persistence by memeto pattern. + * @author Yannick Marcon + * + */ +public interface IMemento { + + /** + * Save the state into the memento. + * @param memento to be created if null, to be updated if not + * @return the memto to persist + */ + public IEntity saveToMemento(IEntity memento); + + /** + * Given the memento, restore the persisted state. + * @param memento + */ + public void restoreFromMemento(IEntity memento); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/application/ApplicationConfiguration.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/application/ApplicationConfiguration.java index 3f6c98c03..dcb7fdf21 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/application/ApplicationConfiguration.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/application/ApplicationConfiguration.java @@ -1,52 +1,61 @@ -package org.obiba.onyx.core.domain.application; - -import javax.persistence.Entity; - -import org.obiba.core.domain.AbstractEntity; - -@Entity -public class ApplicationConfiguration extends AbstractEntity { - - private static final long serialVersionUID = -943397281652866650L; - - private String studyName; - - private String siteName; - - private String siteNo; - - private String participantDirectoryPath; - - public String getStudyName() { - return studyName; - } - - public void setStudyName(String studyName) { - this.studyName = studyName; - } - - public String getSiteName() { - return siteName; - } - - public void setSiteName(String siteName) { - this.siteName = siteName; - } - - public String getSiteNo() { - return siteNo; - } - - public void setSiteNo(String siteNo) { - this.siteNo = siteNo; - } - - public String getParticipantDirectoryPath() { - return participantDirectoryPath; - } - - public void setParticipantDirectoryPath(String participantDirectoryPath) { - this.participantDirectoryPath = participantDirectoryPath; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.application; + +import javax.persistence.Entity; + +import org.obiba.core.domain.AbstractEntity; + +@Entity +public class ApplicationConfiguration extends AbstractEntity { + + private static final long serialVersionUID = -943397281652866650L; + + private String studyName; + + private String siteName; + + private String siteNo; + + private String participantDirectoryPath; + + public String getStudyName() { + return studyName; + } + + public void setStudyName(String studyName) { + this.studyName = studyName; + } + + public String getSiteName() { + return siteName; + } + + public void setSiteName(String siteName) { + this.siteName = siteName; + } + + public String getSiteNo() { + return siteNo; + } + + public void setSiteNo(String siteNo) { + this.siteNo = siteNo; + } + + public String getParticipantDirectoryPath() { + return participantDirectoryPath; + } + + public void setParticipantDirectoryPath(String participantDirectoryPath) { + this.participantDirectoryPath = participantDirectoryPath; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Appointment.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Appointment.java index bdac0232b..b97b21980 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Appointment.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Appointment.java @@ -1,59 +1,68 @@ -package org.obiba.onyx.core.domain.participant; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.obiba.core.domain.AbstractEntity; - -@Entity -public class Appointment extends AbstractEntity { - - private static final long serialVersionUID = 6009569414177913575L; - - private String appointmentCode; - - @Temporal(TemporalType.TIMESTAMP) - public Date date; - - @OneToOne - @JoinColumn(name = "participant_id") - public Participant participant; - - public Appointment() { - } - - public Appointment(Participant participant, Date date) { - this.participant = participant; - this.date = date; - } - - public String getAppointmentCode() { - return appointmentCode; - } - - public void setAppointmentCode(String appointmentCode) { - this.appointmentCode = appointmentCode; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Participant getParticipant() { - return participant; - } - - public void setParticipant(Participant participant) { - this.participant = participant; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.obiba.core.domain.AbstractEntity; + +@Entity +public class Appointment extends AbstractEntity { + + private static final long serialVersionUID = 6009569414177913575L; + + private String appointmentCode; + + @Temporal(TemporalType.TIMESTAMP) + public Date date; + + @OneToOne + @JoinColumn(name = "participant_id") + public Participant participant; + + public Appointment() { + } + + public Appointment(Participant participant, Date date) { + this.participant = participant; + this.date = date; + } + + public String getAppointmentCode() { + return appointmentCode; + } + + public void setAppointmentCode(String appointmentCode) { + this.appointmentCode = appointmentCode; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public Participant getParticipant() { + return participant; + } + + public void setParticipant(Participant participant) { + this.participant = participant; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Gender.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Gender.java index 4309c940e..a61d18147 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Gender.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Gender.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.core.domain.participant; - -public enum Gender { - FEMALE, MALE -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +public enum Gender { + FEMALE, MALE +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Interview.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Interview.java index d1cd1cf23..bbaee1a53 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Interview.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Interview.java @@ -1,96 +1,105 @@ -package org.obiba.onyx.core.domain.participant; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.user.User; - -@Entity -public class Interview extends AbstractEntity { - - private static final long serialVersionUID = -8786498940712113896L; - - @Temporal(TemporalType.TIMESTAMP) - private Date startDate; - - @Temporal(TemporalType.TIMESTAMP) - private Date endDate; - - @OneToOne - @JoinColumn(name = "participant_id") - private Participant participant; - - @Enumerated(EnumType.STRING) - private InterviewStatus status; - - @ManyToOne - @JoinColumn(name = "user_id") - private User user; - - private Boolean closed; - - public Interview() { - } - - public Interview(Participant participant) { - this.participant = participant; - this.startDate = new Date(); - } - - public Date getStartDate() { - return startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public Participant getParticipant() { - return participant; - } - - public void setParticipant(Participant participant) { - this.participant = participant; - } - - public InterviewStatus getStatus() { - return status; - } - - public void setStatus(InterviewStatus status) { - this.status = status; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public void setClosed(Boolean closed) { - this.closed = closed; - } - - public boolean isClosed() { - return closed != null ? closed : (closed = false); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.user.User; + +@Entity +public class Interview extends AbstractEntity { + + private static final long serialVersionUID = -8786498940712113896L; + + @Temporal(TemporalType.TIMESTAMP) + private Date startDate; + + @Temporal(TemporalType.TIMESTAMP) + private Date endDate; + + @OneToOne + @JoinColumn(name = "participant_id") + private Participant participant; + + @Enumerated(EnumType.STRING) + private InterviewStatus status; + + @ManyToOne + @JoinColumn(name = "user_id") + private User user; + + private Boolean closed; + + public Interview() { + } + + public Interview(Participant participant) { + this.participant = participant; + this.startDate = new Date(); + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Participant getParticipant() { + return participant; + } + + public void setParticipant(Participant participant) { + this.participant = participant; + } + + public InterviewStatus getStatus() { + return status; + } + + public void setStatus(InterviewStatus status) { + this.status = status; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public void setClosed(Boolean closed) { + this.closed = closed; + } + + public boolean isClosed() { + return closed != null ? closed : (closed = false); + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/InterviewStatus.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/InterviewStatus.java index 922c7f194..2b52c7fb3 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/InterviewStatus.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/InterviewStatus.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.core.domain.participant; - -public enum InterviewStatus { - NOT_STARTED, IN_PROGRESS, COMPLETED, INTERRUPTED, CANCELLED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +public enum InterviewStatus { + NOT_STARTED, IN_PROGRESS, COMPLETED, INTERRUPTED, CANCELLED +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Participant.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Participant.java index 3861a5b11..59bb1c59b 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Participant.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Participant.java @@ -1,211 +1,220 @@ -package org.obiba.onyx.core.domain.participant; - -import java.util.Calendar; -import java.util.Date; - -import javax.measure.unit.NonSI; -import javax.measure.unit.SI; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; - -import org.obiba.core.domain.AbstractEntity; - -@Entity -@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "barcode", "enrollmentId" }) }) -public class Participant extends AbstractEntity { - - private static final long serialVersionUID = 7720576329990574921L; - - private String firstName; - - private String lastName; - - @Enumerated(EnumType.STRING) - private Gender gender; - - @Temporal(TemporalType.DATE) - private Date birthDate; - - private String barcode; - - private String enrollmentId; - - private String siteNo; - - private String street; - - private String apartment; - - private String city; - - @Enumerated(EnumType.STRING) - private Province province; - - private String country; - - private String postalCode; - - private String phone; - - @OneToOne(mappedBy = "participant") - private Appointment appointment; - - @OneToOne(mappedBy = "participant") - private Interview interview; - - public String getSiteNo() { - return siteNo; - } - - public void setSiteNo(String siteNo) { - this.siteNo = siteNo; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public Gender getGender() { - return gender; - } - - public void setGender(Gender gender) { - this.gender = gender; - } - - public Date getBirthDate() { - return birthDate; - } - - public void setBirthDate(Date birthDate) { - this.birthDate = birthDate; - } - - public Appointment getAppointment() { - return appointment; - } - - public void setAppointment(Appointment appointment) { - this.appointment = appointment; - this.appointment.setParticipant(this); - } - - public Interview getInterview() { - return interview; - } - - public void setInterview(Interview interview) { - this.interview = interview; - this.interview.setParticipant(this); - } - - public String getBarcode() { - return barcode; - } - - public void setBarcode(String barcode) { - this.barcode = barcode; - } - - public String getEnrollmentId() { - return enrollmentId; - } - - public void setEnrollmentId(String enrollmentId) { - this.enrollmentId = enrollmentId; - } - - public String getFullName() { - return getFirstName() + " " + getLastName(); - } - - @Transient - public Long getAge() { - Calendar todayCal = Calendar.getInstance(); - Calendar birthCal = Calendar.getInstance(); - - birthCal.setTime((Date) getBirthDate()); - Long age = todayCal.getTimeInMillis() - birthCal.getTimeInMillis(); - Double ageDouble = SI.MILLI(SI.SECOND).getConverterTo(NonSI.YEAR).convert(Double.valueOf(age.toString())); - ageDouble = Math.floor(ageDouble); - age = Math.round(ageDouble); - - return (age); - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getApartment() { - return apartment; - } - - public void setApartment(String apartment) { - this.apartment = apartment; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public Province getProvince() { - return province; - } - - public void setProvince(Province province) { - this.province = province; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getPostalCode() { - return postalCode; - } - - public void setPostalCode(String postalCode) { - this.postalCode = postalCode; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +import java.util.Calendar; +import java.util.Date; + +import javax.measure.unit.NonSI; +import javax.measure.unit.SI; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; +import javax.persistence.UniqueConstraint; + +import org.obiba.core.domain.AbstractEntity; + +@Entity +@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "barcode", "enrollmentId" }) }) +public class Participant extends AbstractEntity { + + private static final long serialVersionUID = 7720576329990574921L; + + private String firstName; + + private String lastName; + + @Enumerated(EnumType.STRING) + private Gender gender; + + @Temporal(TemporalType.DATE) + private Date birthDate; + + private String barcode; + + private String enrollmentId; + + private String siteNo; + + private String street; + + private String apartment; + + private String city; + + @Enumerated(EnumType.STRING) + private Province province; + + private String country; + + private String postalCode; + + private String phone; + + @OneToOne(mappedBy = "participant") + private Appointment appointment; + + @OneToOne(mappedBy = "participant") + private Interview interview; + + public String getSiteNo() { + return siteNo; + } + + public void setSiteNo(String siteNo) { + this.siteNo = siteNo; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Gender getGender() { + return gender; + } + + public void setGender(Gender gender) { + this.gender = gender; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + public Appointment getAppointment() { + return appointment; + } + + public void setAppointment(Appointment appointment) { + this.appointment = appointment; + this.appointment.setParticipant(this); + } + + public Interview getInterview() { + return interview; + } + + public void setInterview(Interview interview) { + this.interview = interview; + this.interview.setParticipant(this); + } + + public String getBarcode() { + return barcode; + } + + public void setBarcode(String barcode) { + this.barcode = barcode; + } + + public String getEnrollmentId() { + return enrollmentId; + } + + public void setEnrollmentId(String enrollmentId) { + this.enrollmentId = enrollmentId; + } + + public String getFullName() { + return getFirstName() + " " + getLastName(); + } + + @Transient + public Long getAge() { + Calendar todayCal = Calendar.getInstance(); + Calendar birthCal = Calendar.getInstance(); + + birthCal.setTime((Date) getBirthDate()); + Long age = todayCal.getTimeInMillis() - birthCal.getTimeInMillis(); + Double ageDouble = SI.MILLI(SI.SECOND).getConverterTo(NonSI.YEAR).convert(Double.valueOf(age.toString())); + ageDouble = Math.floor(ageDouble); + age = Math.round(ageDouble); + + return (age); + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getApartment() { + return apartment; + } + + public void setApartment(String apartment) { + this.apartment = apartment; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Province getProvince() { + return province; + } + + public void setProvince(Province province) { + this.province = province; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Province.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Province.java index fc50a25b6..4edbd881c 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Province.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/participant/Province.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.core.domain.participant; - -public enum Province { - AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.participant; + +public enum Province { + AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/stage/StageExecutionMemento.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/stage/StageExecutionMemento.java index 4049cb5be..6ce48d969 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/stage/StageExecutionMemento.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/stage/StageExecutionMemento.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.core.domain.stage; import javax.persistence.Entity; diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Role.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Role.java index 78ee21b14..d80672dd8 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Role.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Role.java @@ -1,60 +1,69 @@ -package org.obiba.onyx.core.domain.user; - -import java.io.Serializable; - -import javax.persistence.Entity; - -import org.obiba.core.domain.AbstractEntity; - -@Entity -public class Role extends AbstractEntity implements Serializable, Comparable { - - private static final long serialVersionUID = -5985745491689725964L; - - public static final Role SYSTEM_ADMINISTRATOR = new Role("SYSTEM_ADMINISTRATOR"); - - public static final Role PARTICIPANT_MANAGER = new Role("PARTICIPANT_MANAGER"); - - public static final Role DATA_COLLECTION_OPERATOR = new Role("DATA_COLLECTION_OPERATOR"); - - private String name = null; - - public Role() { - } - - public Role(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String pName) { - name = pName; - } - - @Override - public String toString() { - return name; - } - - public int compareTo(Role o) { - return name.compareTo(o.name); - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Role) { - Role o = (Role) obj; - return name.equals(o.name); - } - return super.equals(obj); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.user; + +import java.io.Serializable; + +import javax.persistence.Entity; + +import org.obiba.core.domain.AbstractEntity; + +@Entity +public class Role extends AbstractEntity implements Serializable, Comparable { + + private static final long serialVersionUID = -5985745491689725964L; + + public static final Role SYSTEM_ADMINISTRATOR = new Role("SYSTEM_ADMINISTRATOR"); + + public static final Role PARTICIPANT_MANAGER = new Role("PARTICIPANT_MANAGER"); + + public static final Role DATA_COLLECTION_OPERATOR = new Role("DATA_COLLECTION_OPERATOR"); + + private String name = null; + + public Role() { + } + + public Role(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String pName) { + name = pName; + } + + @Override + public String toString() { + return name; + } + + public int compareTo(Role o) { + return name.compareTo(o.name); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Role) { + Role o = (Role) obj; + return name.equals(o.name); + } + return super.equals(obj); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Status.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Status.java index 02bbc84c1..48f043169 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Status.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/Status.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.core.domain.user; - -public enum Status { - ACTIVE, INACTIVE -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.user; + +public enum Status { + ACTIVE, INACTIVE +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/User.java b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/User.java index 37f7903a5..fa6da8648 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/User.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/domain/user/User.java @@ -1,175 +1,184 @@ -package org.obiba.onyx.core.domain.user; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.user.Role; - -@Entity -public class User extends AbstractEntity { - - private static final long serialVersionUID = -2200053643926715563L; - - private String lastName; - - private String firstName; - - private String login; - - private String password; - - private String email; - - private Locale language; - - private Boolean deleted; - - @Enumerated(EnumType.STRING) - private Status status; - - @ManyToMany - @JoinTable( - name="user_roles", - joinColumns = { @JoinColumn(name="user_id") }, - inverseJoinColumns = @JoinColumn(name="role_id") - ) - private Set roles; - - @OneToMany(mappedBy = "user") - private List interviews; - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getFullName() { - return getFirstName() + " " + getLastName(); - } - - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Set getRoles() { - return (roles != null) ? roles : (roles = new HashSet()); - } - - public void setRoles(Set roles) { this.roles = roles; } - - public void addRole(Role role) { - getRoles().add(role); - } - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - public List getInterviews() { - return interviews != null ? interviews : (interviews = new ArrayList()); - } - - public void addInterview(Interview interview) { - if(interview != null) { - getInterviews().add(interview); - interview.setUser(this); - } - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public boolean isDeleted() { - if(deleted == null) return false; - else - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - public Locale getLanguage() { - return language; - } - - public void setLanguage(Locale language) { - this.language = language; - } - - /** - * Digest the password into a predefined algorithm. - * @param password - * @return - */ - public static String digest(String password) { - try { - return convertToHex(MessageDigest.getInstance("SHA").digest(password.getBytes())); - } catch(NoSuchAlgorithmException e) { - e.printStackTrace(); - return password; - } - } - - private static String convertToHex(byte[] data) { - StringBuffer buf = new StringBuffer(); - for(int i = 0; i < data.length; i++) { - int halfbyte = (data[i] >>> 4) & 0x0F; - int two_halfs = 0; - do { - if((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); - else - buf.append((char) ('a' + (halfbyte - 10))); - halfbyte = data[i] & 0x0F; - } while(two_halfs++ < 1); - } - return buf.toString(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.domain.user; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.OneToMany; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.user.Role; + +@Entity +public class User extends AbstractEntity { + + private static final long serialVersionUID = -2200053643926715563L; + + private String lastName; + + private String firstName; + + private String login; + + private String password; + + private String email; + + private Locale language; + + private Boolean deleted; + + @Enumerated(EnumType.STRING) + private Status status; + + @ManyToMany + @JoinTable( + name="user_roles", + joinColumns = { @JoinColumn(name="user_id") }, + inverseJoinColumns = @JoinColumn(name="role_id") + ) + private Set roles; + + @OneToMany(mappedBy = "user") + private List interviews; + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getFullName() { + return getFirstName() + " " + getLastName(); + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return (roles != null) ? roles : (roles = new HashSet()); + } + + public void setRoles(Set roles) { this.roles = roles; } + + public void addRole(Role role) { + getRoles().add(role); + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public List getInterviews() { + return interviews != null ? interviews : (interviews = new ArrayList()); + } + + public void addInterview(Interview interview) { + if(interview != null) { + getInterviews().add(interview); + interview.setUser(this); + } + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public boolean isDeleted() { + if(deleted == null) return false; + else + return deleted; + } + + public void setDeleted(Boolean deleted) { + this.deleted = deleted; + } + + public Locale getLanguage() { + return language; + } + + public void setLanguage(Locale language) { + this.language = language; + } + + /** + * Digest the password into a predefined algorithm. + * @param password + * @return + */ + public static String digest(String password) { + try { + return convertToHex(MessageDigest.getInstance("SHA").digest(password.getBytes())); + } catch(NoSuchAlgorithmException e) { + e.printStackTrace(); + return password; + } + } + + private static String convertToHex(byte[] data) { + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < data.length; i++) { + int halfbyte = (data[i] >>> 4) & 0x0F; + int two_halfs = 0; + do { + if((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); + else + buf.append((char) ('a' + (halfbyte - 10))); + halfbyte = data[i] & 0x0F; + } while(two_halfs++ < 1); + } + return buf.toString(); + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/AbstractParticipantExcelReader.java b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/AbstractParticipantExcelReader.java index 2fadf26f5..48b8c75a9 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/AbstractParticipantExcelReader.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/AbstractParticipantExcelReader.java @@ -1,195 +1,204 @@ -package org.obiba.onyx.core.etl.participant; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.participant.Appointment; -import org.obiba.onyx.core.domain.participant.Participant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractParticipantExcelReader implements IParticipantReader { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(AbstractParticipantExcelReader.class); - - private int startAtLine = 2; - - private List listeners = new ArrayList(); - - public void addParticipantReadListener(IParticipantReadListener listener) { - listeners.add(listener); - } - - public void removeParticipantReadListener(IParticipantReadListener listener) { - listeners.remove(listener); - } - - public void setStartAtLine(int startAtLine) { - this.startAtLine = startAtLine; - } - - protected int getStartAtLine() { - return startAtLine; - } - - @SuppressWarnings("unchecked") - public void process(InputStream input) throws IOException, ValidationRuntimeException { - HSSFWorkbook wb = new HSSFWorkbook(input); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, wb); - - List cells = new ArrayList(); - int line = 0; - for(Iterator rit = (Iterator) sheet.rowIterator(); rit.hasNext();) { - HSSFRow row = rit.next(); - line = row.getRowNum() + 1; - cells.clear(); - - if(line >= getStartAtLine()) { - - Participant participant = processParticipant(row, evaluator); - participant.setAppointment(processAppointment(row, evaluator)); - for(IParticipantReadListener listener : listeners) { - listener.onParticipantRead(line, participant); - } - } - } - - for(IParticipantReadListener listener : listeners) { - listener.onParticipantReadEnd(line); - } - } - - protected abstract Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator); - - protected abstract Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator); - - protected Boolean getBooleanValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { - if(cell == null) return null; - - boolean rvalue = false; - - if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { - evaluator.setCurrentRow(row); - evaluator.evaluate(cell); - HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); - - switch(cellValue.getCellType()) { - case HSSFCell.CELL_TYPE_BOOLEAN: - rvalue = cellValue.getBooleanValue(); - break; - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = Boolean.parseBoolean(Long.valueOf((long) cellValue.getNumberValue()).toString()); - break; - case HSSFCell.CELL_TYPE_STRING: - rvalue = Boolean.parseBoolean(cellValue.getRichTextStringValue().getString()); - break; - } - } else { - switch(cell.getCellType()) { - case HSSFCell.CELL_TYPE_BOOLEAN: - rvalue = cell.getBooleanCellValue(); - break; - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = Boolean.parseBoolean(Long.valueOf((long) cell.getNumericCellValue()).toString()); - // cells.add(column + ":" + Double.toString(cell.getNumericCellValue()) + " || " + cell.getDateCellValue()); - break; - case HSSFCell.CELL_TYPE_STRING: - rvalue = Boolean.parseBoolean(cell.getRichStringCellValue().getString()); - break; - } - } - - return rvalue; - } - - protected Date getDateValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { - if(cell == null) return null; - - Date rvalue = null; - - if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { - evaluator.setCurrentRow(row); - evaluator.evaluate(cell); - HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); - - switch(cellValue.getCellType()) { - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = cell.getDateCellValue(); - break; - } - } else { - switch(cell.getCellType()) { - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = cell.getDateCellValue(); - break; - } - } - - return rvalue; - } - - protected Double getNumericValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { - if(cell == null) return null; - - Double rvalue = null; - - if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { - evaluator.setCurrentRow(row); - evaluator.evaluate(cell); - HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); - - switch(cellValue.getCellType()) { - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = cellValue.getNumberValue(); - break; - } - } else { - switch(cell.getCellType()) { - case HSSFCell.CELL_TYPE_NUMERIC: - rvalue = cell.getNumericCellValue(); - break; - } - } - - return rvalue; - } - - protected String getTextValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { - if(cell == null) return null; - - String rvalue = null; - - if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { - evaluator.setCurrentRow(row); - evaluator.evaluate(cell); - HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); - - switch(cellValue.getCellType()) { - case HSSFCell.CELL_TYPE_STRING: - rvalue = cellValue.getRichTextStringValue().getString(); - break; - } - } else { - switch(cell.getCellType()) { - case HSSFCell.CELL_TYPE_STRING: - rvalue = cell.getRichStringCellValue().getString(); - break; - } - } - - return rvalue; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.etl.participant; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.participant.Appointment; +import org.obiba.onyx.core.domain.participant.Participant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractParticipantExcelReader implements IParticipantReader { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(AbstractParticipantExcelReader.class); + + private int startAtLine = 2; + + private List listeners = new ArrayList(); + + public void addParticipantReadListener(IParticipantReadListener listener) { + listeners.add(listener); + } + + public void removeParticipantReadListener(IParticipantReadListener listener) { + listeners.remove(listener); + } + + public void setStartAtLine(int startAtLine) { + this.startAtLine = startAtLine; + } + + protected int getStartAtLine() { + return startAtLine; + } + + @SuppressWarnings("unchecked") + public void process(InputStream input) throws IOException, ValidationRuntimeException { + HSSFWorkbook wb = new HSSFWorkbook(input); + HSSFSheet sheet = wb.getSheetAt(0); + HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, wb); + + List cells = new ArrayList(); + int line = 0; + for(Iterator rit = (Iterator) sheet.rowIterator(); rit.hasNext();) { + HSSFRow row = rit.next(); + line = row.getRowNum() + 1; + cells.clear(); + + if(line >= getStartAtLine()) { + + Participant participant = processParticipant(row, evaluator); + participant.setAppointment(processAppointment(row, evaluator)); + for(IParticipantReadListener listener : listeners) { + listener.onParticipantRead(line, participant); + } + } + } + + for(IParticipantReadListener listener : listeners) { + listener.onParticipantReadEnd(line); + } + } + + protected abstract Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator); + + protected abstract Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator); + + protected Boolean getBooleanValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { + if(cell == null) return null; + + boolean rvalue = false; + + if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { + evaluator.setCurrentRow(row); + evaluator.evaluate(cell); + HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); + + switch(cellValue.getCellType()) { + case HSSFCell.CELL_TYPE_BOOLEAN: + rvalue = cellValue.getBooleanValue(); + break; + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = Boolean.parseBoolean(Long.valueOf((long) cellValue.getNumberValue()).toString()); + break; + case HSSFCell.CELL_TYPE_STRING: + rvalue = Boolean.parseBoolean(cellValue.getRichTextStringValue().getString()); + break; + } + } else { + switch(cell.getCellType()) { + case HSSFCell.CELL_TYPE_BOOLEAN: + rvalue = cell.getBooleanCellValue(); + break; + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = Boolean.parseBoolean(Long.valueOf((long) cell.getNumericCellValue()).toString()); + // cells.add(column + ":" + Double.toString(cell.getNumericCellValue()) + " || " + cell.getDateCellValue()); + break; + case HSSFCell.CELL_TYPE_STRING: + rvalue = Boolean.parseBoolean(cell.getRichStringCellValue().getString()); + break; + } + } + + return rvalue; + } + + protected Date getDateValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { + if(cell == null) return null; + + Date rvalue = null; + + if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { + evaluator.setCurrentRow(row); + evaluator.evaluate(cell); + HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); + + switch(cellValue.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = cell.getDateCellValue(); + break; + } + } else { + switch(cell.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = cell.getDateCellValue(); + break; + } + } + + return rvalue; + } + + protected Double getNumericValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { + if(cell == null) return null; + + Double rvalue = null; + + if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { + evaluator.setCurrentRow(row); + evaluator.evaluate(cell); + HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); + + switch(cellValue.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = cellValue.getNumberValue(); + break; + } + } else { + switch(cell.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC: + rvalue = cell.getNumericCellValue(); + break; + } + } + + return rvalue; + } + + protected String getTextValue(HSSFRow row, HSSFFormulaEvaluator evaluator, HSSFCell cell) { + if(cell == null) return null; + + String rvalue = null; + + if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { + evaluator.setCurrentRow(row); + evaluator.evaluate(cell); + HSSFFormulaEvaluator.CellValue cellValue = evaluator.evaluate(cell); + + switch(cellValue.getCellType()) { + case HSSFCell.CELL_TYPE_STRING: + rvalue = cellValue.getRichTextStringValue().getString(); + break; + } + } else { + switch(cell.getCellType()) { + case HSSFCell.CELL_TYPE_STRING: + rvalue = cell.getRichStringCellValue().getString(); + break; + } + } + + return rvalue; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReadListener.java b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReadListener.java index 664ecaffe..17f02ed21 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReadListener.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReadListener.java @@ -1,22 +1,31 @@ -package org.obiba.onyx.core.etl.participant; - -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.participant.Participant; - -public interface IParticipantReadListener { - - /** - * Called when a {@link Participant} is read at line. - * @param line - * @param participant - */ - public void onParticipantRead(int line, Participant participant) throws ValidationRuntimeException; - - /** - * Called after last participant was read, at the end of the stream, recalling the last line. - * @param line - * @throws ValidationRuntimeException - */ - public void onParticipantReadEnd(int line) throws ValidationRuntimeException; - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.etl.participant; + +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.participant.Participant; + +public interface IParticipantReadListener { + + /** + * Called when a {@link Participant} is read at line. + * @param line + * @param participant + */ + public void onParticipantRead(int line, Participant participant) throws ValidationRuntimeException; + + /** + * Called after last participant was read, at the end of the stream, recalling the last line. + * @param line + * @throws ValidationRuntimeException + */ + public void onParticipantReadEnd(int line) throws ValidationRuntimeException; + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReader.java b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReader.java index 704d51403..3178c9567 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReader.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/etl/participant/IParticipantReader.java @@ -1,16 +1,25 @@ -package org.obiba.onyx.core.etl.participant; - -import java.io.IOException; -import java.io.InputStream; - -import org.obiba.core.validation.exception.ValidationRuntimeException; - -public interface IParticipantReader { - - public void process(InputStream input) throws IOException, ValidationRuntimeException; - - public void addParticipantReadListener(IParticipantReadListener listener); - - public void removeParticipantReadListener(IParticipantReadListener listener); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.etl.participant; + +import java.io.IOException; +import java.io.InputStream; + +import org.obiba.core.validation.exception.ValidationRuntimeException; + +public interface IParticipantReader { + + public void process(InputStream input) throws IOException, ValidationRuntimeException; + + public void addParticipantReadListener(IParticipantReadListener listener); + + public void removeParticipantReadListener(IParticipantReadListener listener); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/ActiveInterviewService.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/ActiveInterviewService.java index 933394267..b1bfd25c8 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/ActiveInterviewService.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/ActiveInterviewService.java @@ -1,84 +1,93 @@ -package org.obiba.onyx.core.service; - -import java.util.List; - -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; - -/** - * Session active participant's interview service. - * @author Yannick Marcon - * - */ -public interface ActiveInterviewService { - - /** - * Set the current participant to deal with. - * @param participant - */ - public void setParticipant(Participant participant); - - /** - * Get the current participant. - * @return null if none set - */ - public Participant getParticipant(); - - /** - * Get current participant's interview. - * @return null if no participant set - */ - public Interview getInterview(); - - /** - * Set the operator for the current interview. - * @param operator - */ - public Interview setInterviewOperator(User operator); - - /** - * Get the stage execution object for given stage, in the interview of current participant. - * @param stage - * @return - */ - public IStageExecution getStageExecution(Stage stage); - - /** - * Get the stage execution object for given stage name, in the interview of current participant. - * @param stageName - * @return - */ - public IStageExecution getStageExecution(String stageName); - - /** - * Persist and perform action on the stage, in the interview of current participant. - * @param stage - * @param action - */ - public void doAction(Stage stage, Action action, User user); - - /** - * Set the status of the current interview. - * @param status - */ - public void setStatus(InterviewStatus status); - - /** - * Get a list of all the comments for the current interview. - * - * @return The list of comment - */ - public List getInterviewComments(); - - /** - * Get the {@link Action} associated to interview status. - * @return - */ - public Action getStatusAction(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.util.List; + +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; + +/** + * Session active participant's interview service. + * @author Yannick Marcon + * + */ +public interface ActiveInterviewService { + + /** + * Set the current participant to deal with. + * @param participant + */ + public void setParticipant(Participant participant); + + /** + * Get the current participant. + * @return null if none set + */ + public Participant getParticipant(); + + /** + * Get current participant's interview. + * @return null if no participant set + */ + public Interview getInterview(); + + /** + * Set the operator for the current interview. + * @param operator + */ + public Interview setInterviewOperator(User operator); + + /** + * Get the stage execution object for given stage, in the interview of current participant. + * @param stage + * @return + */ + public IStageExecution getStageExecution(Stage stage); + + /** + * Get the stage execution object for given stage name, in the interview of current participant. + * @param stageName + * @return + */ + public IStageExecution getStageExecution(String stageName); + + /** + * Persist and perform action on the stage, in the interview of current participant. + * @param stage + * @param action + */ + public void doAction(Stage stage, Action action, User user); + + /** + * Set the status of the current interview. + * @param status + */ + public void setStatus(InterviewStatus status); + + /** + * Get a list of all the comments for the current interview. + * + * @return The list of comment + */ + public List getInterviewComments(); + + /** + * Get the {@link Action} associated to interview status. + * @return + */ + public Action getStatusAction(); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/ApplicationConfigurationService.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/ApplicationConfigurationService.java index a16e271f8..80667fcdf 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/ApplicationConfigurationService.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/ApplicationConfigurationService.java @@ -1,9 +1,18 @@ -package org.obiba.onyx.core.service; - -import org.obiba.onyx.core.domain.application.ApplicationConfiguration; - -public interface ApplicationConfigurationService { - - public void createApplicationConfiguration(ApplicationConfiguration appConfiguration); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import org.obiba.onyx.core.domain.application.ApplicationConfiguration; + +public interface ApplicationConfigurationService { + + public void createApplicationConfiguration(ApplicationConfiguration appConfiguration); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/ParticipantService.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/ParticipantService.java index a45376add..35cec3999 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/ParticipantService.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/ParticipantService.java @@ -1,58 +1,67 @@ -package org.obiba.onyx.core.service; - -import java.io.InputStream; -import java.util.Date; -import java.util.List; - -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; - -public interface ParticipantService { - - /** - * - * @param code participant code or appointment code - * @param paging - * @param clauses - * @return - */ - public List getParticipantsByCode(String code, PagingClause paging, SortingClause... clauses); - - /** - * - * @param code participant code or appointment code - * @return - */ - public int countParticipantsByCode(String code); - - public List getParticipantsByName(String likeName, PagingClause paging, SortingClause... clauses); - - public int countParticipantsByName(String likeName); - - public List getParticipants(InterviewStatus status, PagingClause paging, SortingClause... clauses); - - public int countParticipants(InterviewStatus status); - - public List getParticipants(Date from, Date to, PagingClause paging, SortingClause... clauses); - - public int countParticipants(Date from, Date to); - - public void assignCodeToParticipant(Participant participant, String barcode, String receptionComment, User user); - - public void updateParticipant(Participant participant); - - /** - * Look in the special directory the participant list and add/update the participant/appointment list. - */ - public void updateParticipantList() throws ValidationRuntimeException; - - /** - * Update participants and their appointment from the given participants file. - * @param participantsList - */ - public void updateParticipants(InputStream participantsListStream) throws ValidationRuntimeException; -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.io.InputStream; +import java.util.Date; +import java.util.List; + +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; + +public interface ParticipantService { + + /** + * + * @param code participant code or appointment code + * @param paging + * @param clauses + * @return + */ + public List getParticipantsByCode(String code, PagingClause paging, SortingClause... clauses); + + /** + * + * @param code participant code or appointment code + * @return + */ + public int countParticipantsByCode(String code); + + public List getParticipantsByName(String likeName, PagingClause paging, SortingClause... clauses); + + public int countParticipantsByName(String likeName); + + public List getParticipants(InterviewStatus status, PagingClause paging, SortingClause... clauses); + + public int countParticipants(InterviewStatus status); + + public List getParticipants(Date from, Date to, PagingClause paging, SortingClause... clauses); + + public int countParticipants(Date from, Date to); + + public void assignCodeToParticipant(Participant participant, String barcode, String receptionComment, User user); + + public void updateParticipant(Participant participant); + + /** + * Look in the special directory the participant list and add/update the participant/appointment list. + */ + public void updateParticipantList() throws ValidationRuntimeException; + + /** + * Update participants and their appointment from the given participants file. + * @param participantsList + */ + public void updateParticipants(InputStream participantsListStream) throws ValidationRuntimeException; +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/UserService.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/UserService.java index 630407bc9..9d9c99089 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/UserService.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/UserService.java @@ -1,96 +1,105 @@ -package org.obiba.onyx.core.service; - -import java.io.Serializable; -import java.util.List; -import java.util.Locale; - -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; - -public interface UserService { - - /** - * Returns the list of users - * @param isDeleted - * @param paging - * @param clauses - * @return - */ - public List getUsers(User template, PagingClause paging, SortingClause... clauses); - - /** - * Returns the count of users - * @return - */ - public int getUserCount(User template); - - /** - * Gives the user with the specified login - * @param login - * @return - */ - public User getUserWithLogin(String login); - - /** - * Change the status of the specified user - * @param user - * @param status - */ - public void updateStatus(Serializable userId, Status status); - - /** - * User creation during the application configuration - */ - public void createUser(User user); - - /** - * Delete specified user by setting the "deleted" field to "true" - * @param user - */ - public void deleteUser(Serializable userId); - - /** - * Update the language of the specified user - * @param template - * @param language - */ - public void updateUserLanguage(Serializable userId, Locale language); - - /** - * Check if password was not previously given to the given user. - * @param user - * @param password - * @return - */ - public boolean isNewPassword(User user, String password); - - /** - * Update the password of the specified user - * @param template - * @param password - */ - public void updatePassword(Serializable userId, String password); - - /** - * Create a user when id is not provided, otherwise, updates the changed fields - * @param user - */ - public void createOrUpdateUser(User user); - - /** - * Create the given role. - * @param role - * @return - */ - public Role createRole(Role role); - - /** - * Returns the list of roles - * @param clauses - * @return - */ - public List getRoles(SortingClause... clauses); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.io.Serializable; +import java.util.List; +import java.util.Locale; + +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; + +public interface UserService { + + /** + * Returns the list of users + * @param isDeleted + * @param paging + * @param clauses + * @return + */ + public List getUsers(User template, PagingClause paging, SortingClause... clauses); + + /** + * Returns the count of users + * @return + */ + public int getUserCount(User template); + + /** + * Gives the user with the specified login + * @param login + * @return + */ + public User getUserWithLogin(String login); + + /** + * Change the status of the specified user + * @param user + * @param status + */ + public void updateStatus(Serializable userId, Status status); + + /** + * User creation during the application configuration + */ + public void createUser(User user); + + /** + * Delete specified user by setting the "deleted" field to "true" + * @param user + */ + public void deleteUser(Serializable userId); + + /** + * Update the language of the specified user + * @param template + * @param language + */ + public void updateUserLanguage(Serializable userId, Locale language); + + /** + * Check if password was not previously given to the given user. + * @param user + * @param password + * @return + */ + public boolean isNewPassword(User user, String password); + + /** + * Update the password of the specified user + * @param template + * @param password + */ + public void updatePassword(Serializable userId, String password); + + /** + * Create a user when id is not provided, otherwise, updates the changed fields + * @param user + */ + public void createOrUpdateUser(User user); + + /** + * Create the given role. + * @param role + * @return + */ + public Role createRole(Role role); + + /** + * Returns the list of roles + * @param clauses + * @return + */ + public List getRoles(SortingClause... clauses); +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/UserSessionService.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/UserSessionService.java index db190777c..4bc1b9238 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/UserSessionService.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/UserSessionService.java @@ -1,14 +1,23 @@ -package org.obiba.onyx.core.service; - -import java.util.Locale; - -import org.obiba.onyx.core.domain.user.User; - -public interface UserSessionService { - - public Locale getLocale(); - - public void setLocale(Locale locale); - - public User getUser(); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.util.Locale; + +import org.obiba.onyx.core.domain.user.User; + +public interface UserSessionService { + + public Locale getLocale(); + + public void setLocale(Locale locale); + + public User getUser(); +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultActiveInterviewServiceImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultActiveInterviewServiceImpl.java index eb4c3f5e4..affd6e24c 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultActiveInterviewServiceImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultActiveInterviewServiceImpl.java @@ -1,210 +1,219 @@ -package org.obiba.onyx.core.service.impl; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.obiba.core.service.SortingClause; -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.stage.StageExecutionMemento; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class DefaultActiveInterviewServiceImpl extends PersistenceManagerAwareService implements ActiveInterviewService { - - private static final Logger log = LoggerFactory.getLogger(DefaultActiveInterviewServiceImpl.class); - - private Serializable currentParticipantId = null; - - private ModuleRegistry moduleRegistry; - - // Map of Interview.id to Map of Stage.id to StageExecutionContext - private Map> interviewStageContexts = new HashMap>(); - - public void setModuleRegistry(ModuleRegistry moduleRegistry) { - this.moduleRegistry = moduleRegistry; - } - - public Participant getParticipant() { - if(currentParticipantId == null) return null; - return getPersistenceManager().get(Participant.class, currentParticipantId); - } - - public Interview getInterview() { - Participant currentParticipant = getParticipant(); - if(currentParticipantId == null) return null; - - Interview interview = currentParticipant.getInterview(); - - if(interview == null) { - interview = new Interview(); - interview.setParticipant(currentParticipant); - interview.setStartDate(new Date()); - interview.setStatus(InterviewStatus.IN_PROGRESS); - getPersistenceManager().save(interview); - currentParticipant = getPersistenceManager().get(Participant.class, currentParticipant.getId()); - interview = currentParticipant.getInterview(); - } - - return interview; - } - - public IStageExecution getStageExecution(Stage stage) { - Participant currentParticipant = getParticipant(); - if(currentParticipant == null) return null; - - // try to find it in memory - Interview interview = getInterview(); - Map contexts = interviewStageContexts.get(interview.getId()); - if(contexts == null) { - contexts = new HashMap(); - interviewStageContexts.put(interview.getId(), contexts); - } - StageExecutionContext exec = contexts.get(stage.getName()); - - if(exec == null) { - Module module = moduleRegistry.getModule(stage.getModule()); - exec = (StageExecutionContext) module.createStageExecution(getInterview(), stage); - - for(StageExecutionContext sec : contexts.values()) { - if(exec.getStage().getStageDependencyCondition() != null) { - if(exec.getStage().getStageDependencyCondition().isDependentOn(sec.getStage().getName())) { - sec.addTransitionListener(exec); - } - } - } - - contexts.put(stage.getName(), exec); - - // try to find it in memory - StageExecutionMemento template = new StageExecutionMemento(); - template.setStage(stage.getName()); - template.setInterview(getInterview()); - StageExecutionMemento memento = getPersistenceManager().matchOne(template); - if(memento != null) { - exec.restoreFromMemento(memento); - } - - } - - return exec; - } - - public IStageExecution getStageExecution(String stageName) { - Stage stage = moduleRegistry.getStage(stageName); - if(stage == null) { - throw new IllegalArgumentException("Invalid stage name " + stageName); - } - return getStageExecution(stage); - } - - public void doAction(Stage stage, Action action, User user) { - action.setInterview(getParticipant().getInterview()); - if(stage != null) { - action.setStage(stage.getName()); - } - action.setDateTime(new Date()); - action.setUser(user); - getPersistenceManager().save(action); - - if(stage != null) { - IStageExecution exec = getStageExecution(stage); - action.getActionType().act(exec, action); - } - } - - public void shutdown() { - log.info("shutdown"); - } - - public void setParticipant(Participant participant) { - this.currentParticipantId = participant.getId(); - } - - public Interview setInterviewOperator(User operator) { - Participant currentParticipant = getParticipant(); - if(currentParticipant == null) return null; - - Interview template = new Interview(); - template.setParticipant(currentParticipant); - Interview interview = getPersistenceManager().matchOne(template); - - if(interview != null) { - interview.setUser(operator); - getPersistenceManager().save(interview); - currentParticipant = getPersistenceManager().get(Participant.class, currentParticipant.getId()); - } - - return interview; - } - - public void setStatus(InterviewStatus status) { - Participant currentParticipant = getParticipant(); - if(currentParticipant == null) return; - - Interview template = new Interview(); - template.setParticipant(currentParticipant); - Interview interview = getPersistenceManager().matchOne(template); - - if(interview != null) { - interview.setStatus(status); - if(status.equals(InterviewStatus.CANCELLED) || status.equals(InterviewStatus.COMPLETED)) { - interview.setEndDate(new Date()); - } - getPersistenceManager().save(interview); - } - } - - public List getInterviewComments() { - Action template = new Action(); - template.setInterview(getInterview()); - List actions = getPersistenceManager().match(template, new SortingClause("dateTime", false)); - List comments = new ArrayList(); - - for(Action action : actions) { - if(action.getComment() != null) { - comments.add(action); - } - } - - return comments; - } - - public Action getStatusAction() { - Interview interview = getInterview(); - Action template = new Action(); - template.setInterview(interview); - switch(interview.getStatus()) { - case CANCELLED: - template.setActionType(ActionType.STOP); - break; - case COMPLETED: - template.setActionType(ActionType.COMPLETE); - break; - } - - List actions = getPersistenceManager().match(template, new SortingClause("dateTime", false)); - - if(actions.size() > 0) return actions.get(0); - else - return null; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.obiba.core.service.SortingClause; +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.stage.StageExecutionMemento; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class DefaultActiveInterviewServiceImpl extends PersistenceManagerAwareService implements ActiveInterviewService { + + private static final Logger log = LoggerFactory.getLogger(DefaultActiveInterviewServiceImpl.class); + + private Serializable currentParticipantId = null; + + private ModuleRegistry moduleRegistry; + + // Map of Interview.id to Map of Stage.id to StageExecutionContext + private Map> interviewStageContexts = new HashMap>(); + + public void setModuleRegistry(ModuleRegistry moduleRegistry) { + this.moduleRegistry = moduleRegistry; + } + + public Participant getParticipant() { + if(currentParticipantId == null) return null; + return getPersistenceManager().get(Participant.class, currentParticipantId); + } + + public Interview getInterview() { + Participant currentParticipant = getParticipant(); + if(currentParticipantId == null) return null; + + Interview interview = currentParticipant.getInterview(); + + if(interview == null) { + interview = new Interview(); + interview.setParticipant(currentParticipant); + interview.setStartDate(new Date()); + interview.setStatus(InterviewStatus.IN_PROGRESS); + getPersistenceManager().save(interview); + currentParticipant = getPersistenceManager().get(Participant.class, currentParticipant.getId()); + interview = currentParticipant.getInterview(); + } + + return interview; + } + + public IStageExecution getStageExecution(Stage stage) { + Participant currentParticipant = getParticipant(); + if(currentParticipant == null) return null; + + // try to find it in memory + Interview interview = getInterview(); + Map contexts = interviewStageContexts.get(interview.getId()); + if(contexts == null) { + contexts = new HashMap(); + interviewStageContexts.put(interview.getId(), contexts); + } + StageExecutionContext exec = contexts.get(stage.getName()); + + if(exec == null) { + Module module = moduleRegistry.getModule(stage.getModule()); + exec = (StageExecutionContext) module.createStageExecution(getInterview(), stage); + + for(StageExecutionContext sec : contexts.values()) { + if(exec.getStage().getStageDependencyCondition() != null) { + if(exec.getStage().getStageDependencyCondition().isDependentOn(sec.getStage().getName())) { + sec.addTransitionListener(exec); + } + } + } + + contexts.put(stage.getName(), exec); + + // try to find it in memory + StageExecutionMemento template = new StageExecutionMemento(); + template.setStage(stage.getName()); + template.setInterview(getInterview()); + StageExecutionMemento memento = getPersistenceManager().matchOne(template); + if(memento != null) { + exec.restoreFromMemento(memento); + } + + } + + return exec; + } + + public IStageExecution getStageExecution(String stageName) { + Stage stage = moduleRegistry.getStage(stageName); + if(stage == null) { + throw new IllegalArgumentException("Invalid stage name " + stageName); + } + return getStageExecution(stage); + } + + public void doAction(Stage stage, Action action, User user) { + action.setInterview(getParticipant().getInterview()); + if(stage != null) { + action.setStage(stage.getName()); + } + action.setDateTime(new Date()); + action.setUser(user); + getPersistenceManager().save(action); + + if(stage != null) { + IStageExecution exec = getStageExecution(stage); + action.getActionType().act(exec, action); + } + } + + public void shutdown() { + log.info("shutdown"); + } + + public void setParticipant(Participant participant) { + this.currentParticipantId = participant.getId(); + } + + public Interview setInterviewOperator(User operator) { + Participant currentParticipant = getParticipant(); + if(currentParticipant == null) return null; + + Interview template = new Interview(); + template.setParticipant(currentParticipant); + Interview interview = getPersistenceManager().matchOne(template); + + if(interview != null) { + interview.setUser(operator); + getPersistenceManager().save(interview); + currentParticipant = getPersistenceManager().get(Participant.class, currentParticipant.getId()); + } + + return interview; + } + + public void setStatus(InterviewStatus status) { + Participant currentParticipant = getParticipant(); + if(currentParticipant == null) return; + + Interview template = new Interview(); + template.setParticipant(currentParticipant); + Interview interview = getPersistenceManager().matchOne(template); + + if(interview != null) { + interview.setStatus(status); + if(status.equals(InterviewStatus.CANCELLED) || status.equals(InterviewStatus.COMPLETED)) { + interview.setEndDate(new Date()); + } + getPersistenceManager().save(interview); + } + } + + public List getInterviewComments() { + Action template = new Action(); + template.setInterview(getInterview()); + List actions = getPersistenceManager().match(template, new SortingClause("dateTime", false)); + List comments = new ArrayList(); + + for(Action action : actions) { + if(action.getComment() != null) { + comments.add(action); + } + } + + return comments; + } + + public Action getStatusAction() { + Interview interview = getInterview(); + Action template = new Action(); + template.setInterview(interview); + switch(interview.getStatus()) { + case CANCELLED: + template.setActionType(ActionType.STOP); + break; + case COMPLETED: + template.setActionType(ActionType.COMPLETE); + break; + } + + List actions = getPersistenceManager().match(template, new SortingClause("dateTime", false)); + + if(actions.size() > 0) return actions.get(0); + else + return null; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultApplicationConfigurationServiceImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultApplicationConfigurationServiceImpl.java index 27f238d0b..1aa1e0721 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultApplicationConfigurationServiceImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultApplicationConfigurationServiceImpl.java @@ -1,15 +1,24 @@ -package org.obiba.onyx.core.service.impl; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.application.ApplicationConfiguration; -import org.obiba.onyx.core.service.ApplicationConfigurationService; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class DefaultApplicationConfigurationServiceImpl extends PersistenceManagerAwareService implements ApplicationConfigurationService { - - public void createApplicationConfiguration(ApplicationConfiguration appConfiguration) { - persistenceManager.save(appConfiguration); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.application.ApplicationConfiguration; +import org.obiba.onyx.core.service.ApplicationConfigurationService; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class DefaultApplicationConfigurationServiceImpl extends PersistenceManagerAwareService implements ApplicationConfigurationService { + + public void createApplicationConfiguration(ApplicationConfiguration appConfiguration) { + persistenceManager.save(appConfiguration); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultParticipantServiceImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultParticipantServiceImpl.java index b79d61d7d..655ac4420 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultParticipantServiceImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultParticipantServiceImpl.java @@ -1,209 +1,218 @@ -package org.obiba.onyx.core.service.impl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; -import java.util.List; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.application.ApplicationConfiguration; -import org.obiba.onyx.core.domain.participant.Appointment; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.etl.participant.IParticipantReadListener; -import org.obiba.onyx.core.etl.participant.IParticipantReader; -import org.obiba.onyx.core.service.ParticipantService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.transaction.annotation.Transactional; - -/** - * Default implementation (non hibernate specific) of Participant Service - * @see#ParticipantServiceHibernateImpl. - * @author Yannick Marcon - * - */ -@Transactional -public abstract class DefaultParticipantServiceImpl extends PersistenceManagerAwareService implements ParticipantService { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(DefaultParticipantServiceImpl.class); - - private IParticipantReader participantReader; - - private boolean participantReaderCallbackInitialized = false; - - public void setParticipantReader(IParticipantReader participantReader) { - this.participantReader = participantReader; - } - - public void assignCodeToParticipant(Participant participant, String barcode, String receptionComment, User user) { - participant.setBarcode(barcode); - persistenceManager.save(participant); - - // - // Create an interview for the participant, in the IN_PROGRESS state. - // - // TODO: Revisit whether the interview should be in the IN_PROGRESS state - // or instead in the NOT_STARTED state a this point. - // - Interview interview = new Interview(); - interview.setParticipant(participant); - interview.setStartDate(new Date()); - interview.setStatus(InterviewStatus.IN_PROGRESS); - getPersistenceManager().save(interview); - - // Persist the reception comment, if there is one. - if(receptionComment != null && receptionComment.trim().length() != 0) { - Action receptionCommentAction = new Action(); - receptionCommentAction.setActionType(ActionType.COMMENT); - receptionCommentAction.setDateTime(new Date()); - receptionCommentAction.setComment(receptionComment); - receptionCommentAction.setUser(user); - receptionCommentAction.setInterview(interview); - persistenceManager.save(receptionCommentAction); - } - } - - public void updateParticipant(Participant participant) { - persistenceManager.save(participant); - } - - public void updateParticipantList() throws ValidationRuntimeException { - ApplicationConfiguration appConfig = new ApplicationConfiguration(); - appConfig = getPersistenceManager().matchOne(appConfig); - if(appConfig.getParticipantDirectoryPath() == null) { - ValidationRuntimeException vex = new ValidationRuntimeException(); - vex.reject("NoParticipantsListRepository", "No participants list repository."); - throw vex; - } - - File dir = new File(appConfig.getParticipantDirectoryPath()); - log.debug("participantDirectory={}", dir.getAbsolutePath()); - File lastModifiedFile = null; - if(dir.exists() && dir.isDirectory()) { - File[] dirContent = dir.listFiles(); - if(dirContent != null) { - for(File f : dirContent) { - if(f.isFile() && (lastModifiedFile == null || (f.lastModified() > lastModifiedFile.lastModified()))) { - lastModifiedFile = f; - } - } - } - } - else { - log.error("Participants update list repository does not exists or is not a directory: {}", dir.getAbsolutePath()); - } - - if(lastModifiedFile == null) { - ValidationRuntimeException vex = new ValidationRuntimeException(); - vex.reject("NoParticipantsListFileFound", new String[] { appConfig.getParticipantDirectoryPath() }, "No participants list file found in: " + appConfig.getParticipantDirectoryPath()); - throw vex; - } - - log.info("participantFile={}", lastModifiedFile.getAbsolutePath()); - try { - updateParticipants(new FileInputStream(lastModifiedFile)); - } catch(FileNotFoundException e) { - // should not happen cause we found it by exploring the directory - } - } - - public void updateParticipants(InputStream participantsListStream) throws ValidationRuntimeException { - - final ApplicationConfiguration appConfig = getPersistenceManager().matchOne(new ApplicationConfiguration()); - - final ValidationRuntimeException vex = new ValidationRuntimeException(); - - if(!participantReaderCallbackInitialized) { - participantReader.addParticipantReadListener(new IParticipantReadListener() { - - public void onParticipantRead(int line, Participant participant) throws ValidationRuntimeException { - log.debug("reading participant={} {}", participant.getEnrollmentId(), participant.getFullName()); - - if(!appConfig.getSiteNo().equals(participant.getSiteNo())) { - log.error("WrongParticipantSiteName"); - vex.reject(participant, "WrongParticipantSiteName", new String[] { Integer.toString(line), participant.getEnrollmentId(), participant.getSiteNo(), appConfig.getSiteNo() }, "Wrong Participant site name at line " + line + ": " + participant.getSiteNo() + ", expecting " + appConfig.getSiteName()); - if(vex.getAllObjectErrors().size() == 10) { - throw vex; - } - } else { - Participant persistedParticipant = new Participant(); - persistedParticipant.setEnrollmentId(participant.getEnrollmentId()); - persistedParticipant = getPersistenceManager().matchOne(persistedParticipant); - - if(persistedParticipant == null) { - log.debug("adding participant={}", participant.getEnrollmentId()); - getPersistenceManager().save(participant); - getPersistenceManager().save(participant.getAppointment()); - } else { - log.debug("persistedParticipant.interview={}", persistedParticipant.getInterview()); - if(persistedParticipant.getInterview() != null && persistedParticipant.getInterview().getStatus().equals(InterviewStatus.COMPLETED)) { - // error if new appointment date is in the future - Date newAppointmentDate = participant.getAppointment().getDate(); - if(newAppointmentDate != null && newAppointmentDate.compareTo(new Date()) > 0) { - log.error("ParticipantInterviewCompletedWithAppointmentInTheFuture"); - vex.reject(participant, "ParticipantInterviewCompletedWithAppointmentInTheFuture", new String[] { Integer.toString(line), participant.getEnrollmentId() }, "Participant's interview is completed, but new appointment date is in the future."); - if(vex.getAllObjectErrors().size() == 10) { - throw vex; - } - } - // else ignore - } else { - // update its appointment date - Appointment appointment = persistedParticipant.getAppointment(); - if(persistedParticipant.getAppointment() == null) { - log.debug("adding participant.appointment={}", participant.getEnrollmentId()); - appointment = participant.getAppointment(); - appointment.setParticipant(persistedParticipant); - getPersistenceManager().save(appointment); - } else { - log.debug("updating participant.appointment={}", participant.getEnrollmentId()); - persistedParticipant.getAppointment().setDate(participant.getAppointment().getDate()); - getPersistenceManager().save(persistedParticipant.getAppointment()); - } - } - } - } - } - - public void onParticipantReadEnd(int line) throws ValidationRuntimeException { - if(vex.getAllObjectErrors().size() > 0) throw vex; - } - - }); - participantReaderCallbackInitialized = true; - } - - // do some clean up before updating - for(Participant p : getNotReceivedParticipants()) { - if(p.getAppointment() != null) { - log.debug("removing appointment.appointmentCode={}", p.getAppointment().getAppointmentCode()); - getPersistenceManager().delete(p.getAppointment()); - } - log.debug("removing participant.enrollmentId={}", p.getEnrollmentId()); - getPersistenceManager().delete(p); - } - - try { - participantReader.process(participantsListStream); - } catch(IOException e) { - log.error("Update participants list read failed.", e); - throw new ValidationRuntimeException("UpdateParticipantsListReadFailed", "Update participants list read failed."); - } - } - - /** - * DB access layer specific implementation for getting {@link Participant} that have not been received. - * @return - */ - protected abstract List getNotReceivedParticipants(); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.List; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.application.ApplicationConfiguration; +import org.obiba.onyx.core.domain.participant.Appointment; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.etl.participant.IParticipantReadListener; +import org.obiba.onyx.core.etl.participant.IParticipantReader; +import org.obiba.onyx.core.service.ParticipantService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.annotation.Transactional; + +/** + * Default implementation (non hibernate specific) of Participant Service + * @see#ParticipantServiceHibernateImpl. + * @author Yannick Marcon + * + */ +@Transactional +public abstract class DefaultParticipantServiceImpl extends PersistenceManagerAwareService implements ParticipantService { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(DefaultParticipantServiceImpl.class); + + private IParticipantReader participantReader; + + private boolean participantReaderCallbackInitialized = false; + + public void setParticipantReader(IParticipantReader participantReader) { + this.participantReader = participantReader; + } + + public void assignCodeToParticipant(Participant participant, String barcode, String receptionComment, User user) { + participant.setBarcode(barcode); + persistenceManager.save(participant); + + // + // Create an interview for the participant, in the IN_PROGRESS state. + // + // TODO: Revisit whether the interview should be in the IN_PROGRESS state + // or instead in the NOT_STARTED state a this point. + // + Interview interview = new Interview(); + interview.setParticipant(participant); + interview.setStartDate(new Date()); + interview.setStatus(InterviewStatus.IN_PROGRESS); + getPersistenceManager().save(interview); + + // Persist the reception comment, if there is one. + if(receptionComment != null && receptionComment.trim().length() != 0) { + Action receptionCommentAction = new Action(); + receptionCommentAction.setActionType(ActionType.COMMENT); + receptionCommentAction.setDateTime(new Date()); + receptionCommentAction.setComment(receptionComment); + receptionCommentAction.setUser(user); + receptionCommentAction.setInterview(interview); + persistenceManager.save(receptionCommentAction); + } + } + + public void updateParticipant(Participant participant) { + persistenceManager.save(participant); + } + + public void updateParticipantList() throws ValidationRuntimeException { + ApplicationConfiguration appConfig = new ApplicationConfiguration(); + appConfig = getPersistenceManager().matchOne(appConfig); + if(appConfig.getParticipantDirectoryPath() == null) { + ValidationRuntimeException vex = new ValidationRuntimeException(); + vex.reject("NoParticipantsListRepository", "No participants list repository."); + throw vex; + } + + File dir = new File(appConfig.getParticipantDirectoryPath()); + log.debug("participantDirectory={}", dir.getAbsolutePath()); + File lastModifiedFile = null; + if(dir.exists() && dir.isDirectory()) { + File[] dirContent = dir.listFiles(); + if(dirContent != null) { + for(File f : dirContent) { + if(f.isFile() && (lastModifiedFile == null || (f.lastModified() > lastModifiedFile.lastModified()))) { + lastModifiedFile = f; + } + } + } + } + else { + log.error("Participants update list repository does not exists or is not a directory: {}", dir.getAbsolutePath()); + } + + if(lastModifiedFile == null) { + ValidationRuntimeException vex = new ValidationRuntimeException(); + vex.reject("NoParticipantsListFileFound", new String[] { appConfig.getParticipantDirectoryPath() }, "No participants list file found in: " + appConfig.getParticipantDirectoryPath()); + throw vex; + } + + log.info("participantFile={}", lastModifiedFile.getAbsolutePath()); + try { + updateParticipants(new FileInputStream(lastModifiedFile)); + } catch(FileNotFoundException e) { + // should not happen cause we found it by exploring the directory + } + } + + public void updateParticipants(InputStream participantsListStream) throws ValidationRuntimeException { + + final ApplicationConfiguration appConfig = getPersistenceManager().matchOne(new ApplicationConfiguration()); + + final ValidationRuntimeException vex = new ValidationRuntimeException(); + + if(!participantReaderCallbackInitialized) { + participantReader.addParticipantReadListener(new IParticipantReadListener() { + + public void onParticipantRead(int line, Participant participant) throws ValidationRuntimeException { + log.debug("reading participant={} {}", participant.getEnrollmentId(), participant.getFullName()); + + if(!appConfig.getSiteNo().equals(participant.getSiteNo())) { + log.error("WrongParticipantSiteName"); + vex.reject(participant, "WrongParticipantSiteName", new String[] { Integer.toString(line), participant.getEnrollmentId(), participant.getSiteNo(), appConfig.getSiteNo() }, "Wrong Participant site name at line " + line + ": " + participant.getSiteNo() + ", expecting " + appConfig.getSiteName()); + if(vex.getAllObjectErrors().size() == 10) { + throw vex; + } + } else { + Participant persistedParticipant = new Participant(); + persistedParticipant.setEnrollmentId(participant.getEnrollmentId()); + persistedParticipant = getPersistenceManager().matchOne(persistedParticipant); + + if(persistedParticipant == null) { + log.debug("adding participant={}", participant.getEnrollmentId()); + getPersistenceManager().save(participant); + getPersistenceManager().save(participant.getAppointment()); + } else { + log.debug("persistedParticipant.interview={}", persistedParticipant.getInterview()); + if(persistedParticipant.getInterview() != null && persistedParticipant.getInterview().getStatus().equals(InterviewStatus.COMPLETED)) { + // error if new appointment date is in the future + Date newAppointmentDate = participant.getAppointment().getDate(); + if(newAppointmentDate != null && newAppointmentDate.compareTo(new Date()) > 0) { + log.error("ParticipantInterviewCompletedWithAppointmentInTheFuture"); + vex.reject(participant, "ParticipantInterviewCompletedWithAppointmentInTheFuture", new String[] { Integer.toString(line), participant.getEnrollmentId() }, "Participant's interview is completed, but new appointment date is in the future."); + if(vex.getAllObjectErrors().size() == 10) { + throw vex; + } + } + // else ignore + } else { + // update its appointment date + Appointment appointment = persistedParticipant.getAppointment(); + if(persistedParticipant.getAppointment() == null) { + log.debug("adding participant.appointment={}", participant.getEnrollmentId()); + appointment = participant.getAppointment(); + appointment.setParticipant(persistedParticipant); + getPersistenceManager().save(appointment); + } else { + log.debug("updating participant.appointment={}", participant.getEnrollmentId()); + persistedParticipant.getAppointment().setDate(participant.getAppointment().getDate()); + getPersistenceManager().save(persistedParticipant.getAppointment()); + } + } + } + } + } + + public void onParticipantReadEnd(int line) throws ValidationRuntimeException { + if(vex.getAllObjectErrors().size() > 0) throw vex; + } + + }); + participantReaderCallbackInitialized = true; + } + + // do some clean up before updating + for(Participant p : getNotReceivedParticipants()) { + if(p.getAppointment() != null) { + log.debug("removing appointment.appointmentCode={}", p.getAppointment().getAppointmentCode()); + getPersistenceManager().delete(p.getAppointment()); + } + log.debug("removing participant.enrollmentId={}", p.getEnrollmentId()); + getPersistenceManager().delete(p); + } + + try { + participantReader.process(participantsListStream); + } catch(IOException e) { + log.error("Update participants list read failed.", e); + throw new ValidationRuntimeException("UpdateParticipantsListReadFailed", "Update participants list read failed."); + } + } + + /** + * DB access layer specific implementation for getting {@link Participant} that have not been received. + * @return + */ + protected abstract List getNotReceivedParticipants(); +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultUserServiceImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultUserServiceImpl.java index 8d7e6dffe..7c6c539ba 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultUserServiceImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/DefaultUserServiceImpl.java @@ -1,93 +1,102 @@ -package org.obiba.onyx.core.service.impl; - -import java.io.Serializable; -import java.util.Locale; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.springframework.transaction.annotation.Transactional; - -/** - * Default implementation (non hibernate specific) of User Service - * @see#UserServiceHibernateImpl. - * @author acarey - * - */ -@Transactional -public abstract class DefaultUserServiceImpl extends PersistenceManagerAwareService implements UserService { - - public User getUserWithLogin(String login) { - User template = new User(); - template.setLogin(login); - return getPersistenceManager().matchOne(template); - } - - public void updateStatus(Serializable userId, Status status) { - User user = loadUser(userId); - user.setStatus(status); - getPersistenceManager().save(user); - } - - public void createUser(User user) { - getPersistenceManager().save(user); - } - - public void deleteUser(Serializable userId) { - User user = loadUser(userId); - user.setDeleted(true); - getPersistenceManager().save(user); - } - - public void updateUserLanguage(Serializable userId, Locale language) { - User user = loadUser(userId); - user.setLanguage(language); - getPersistenceManager().save(user); - } - - public boolean isNewPassword(User user, String password) { - User template = new User(); - template.setLogin(user.getLogin()); - template.setPassword(password); - - return (getPersistenceManager().matchOne(template) == null); - } - - public void updatePassword(Serializable userId, String password) { - User user = loadUser(userId); - user.setPassword(password); - getPersistenceManager().save(user); - } - - public void createOrUpdateUser(User user) { - User template = new User(); - if(user.getId() != null) { - template = loadUser(user.getId()); - - if(!user.getLastName().equals(template.getLastName())) template.setLastName(user.getLastName()); - if(!user.getFirstName().equals(template.getFirstName())) template.setFirstName(user.getFirstName()); - if(!user.getPassword().equals(template.getPassword())) template.setPassword(user.getPassword()); - if(!user.getEmail().equals(template.getEmail())) template.setEmail(user.getEmail()); - if(template.getLanguage() == null || !user.getLanguage().equals(template.getLanguage())) template.setLanguage(user.getLanguage()); - - if(!user.getRoles().equals(template.getRoles())) { - template.setRoles(user.getRoles()); - } - } else { - template = user; - } - getPersistenceManager().save(template); - } - - public Role createRole(Role role) { - return getPersistenceManager().save(role); - } - - private User loadUser(Serializable userId) { - User user = getPersistenceManager().get(User.class, userId); - if(user == null) throw new IllegalArgumentException("Invalid user id"); - return user; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl; + +import java.io.Serializable; +import java.util.Locale; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.springframework.transaction.annotation.Transactional; + +/** + * Default implementation (non hibernate specific) of User Service + * @see#UserServiceHibernateImpl. + * @author acarey + * + */ +@Transactional +public abstract class DefaultUserServiceImpl extends PersistenceManagerAwareService implements UserService { + + public User getUserWithLogin(String login) { + User template = new User(); + template.setLogin(login); + return getPersistenceManager().matchOne(template); + } + + public void updateStatus(Serializable userId, Status status) { + User user = loadUser(userId); + user.setStatus(status); + getPersistenceManager().save(user); + } + + public void createUser(User user) { + getPersistenceManager().save(user); + } + + public void deleteUser(Serializable userId) { + User user = loadUser(userId); + user.setDeleted(true); + getPersistenceManager().save(user); + } + + public void updateUserLanguage(Serializable userId, Locale language) { + User user = loadUser(userId); + user.setLanguage(language); + getPersistenceManager().save(user); + } + + public boolean isNewPassword(User user, String password) { + User template = new User(); + template.setLogin(user.getLogin()); + template.setPassword(password); + + return (getPersistenceManager().matchOne(template) == null); + } + + public void updatePassword(Serializable userId, String password) { + User user = loadUser(userId); + user.setPassword(password); + getPersistenceManager().save(user); + } + + public void createOrUpdateUser(User user) { + User template = new User(); + if(user.getId() != null) { + template = loadUser(user.getId()); + + if(!user.getLastName().equals(template.getLastName())) template.setLastName(user.getLastName()); + if(!user.getFirstName().equals(template.getFirstName())) template.setFirstName(user.getFirstName()); + if(!user.getPassword().equals(template.getPassword())) template.setPassword(user.getPassword()); + if(!user.getEmail().equals(template.getEmail())) template.setEmail(user.getEmail()); + if(template.getLanguage() == null || !user.getLanguage().equals(template.getLanguage())) template.setLanguage(user.getLanguage()); + + if(!user.getRoles().equals(template.getRoles())) { + template.setRoles(user.getRoles()); + } + } else { + template = user; + } + getPersistenceManager().save(template); + } + + public Role createRole(Role role) { + return getPersistenceManager().save(role); + } + + private User loadUser(Serializable userId) { + User user = getPersistenceManager().get(User.class, userId); + if(user == null) throw new IllegalArgumentException("Invalid user id"); + return user; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/UserSessionServiceBeanImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/UserSessionServiceBeanImpl.java index dc3dcbfc4..5d6904729 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/UserSessionServiceBeanImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/UserSessionServiceBeanImpl.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.core.service.impl; import java.util.Locale; diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/ParticipantServiceHibernateImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/ParticipantServiceHibernateImpl.java index 088b03745..16742df40 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/ParticipantServiceHibernateImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/ParticipantServiceHibernateImpl.java @@ -1,149 +1,158 @@ -package org.obiba.onyx.core.service.impl.hibernate; - -import java.util.Date; -import java.util.List; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Restrictions; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.core.service.impl.hibernate.AssociationCriteria; -import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.impl.DefaultParticipantServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.transaction.annotation.Transactional; - -/** - * Implementation of hibernate specific methods of Participant Service - * @see#ParticipantService. - * @author Yannick Marcon - * - */ -@Transactional -public class ParticipantServiceHibernateImpl extends DefaultParticipantServiceImpl { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ParticipantServiceHibernateImpl.class); - - private SessionFactory factory; - - public void setSessionFactory(SessionFactory factory) { - this.factory = factory; - } - - private Session getSession() { - return factory.getCurrentSession(); - } - - public List getParticipants(InterviewStatus status, PagingClause paging, SortingClause... clauses) { - AssociationCriteria criteria = getCriteria(paging, clauses); - if(status != null) criteria.add("interview.status", Operation.eq, status); - return criteria.list(); - } - - public int countParticipants(InterviewStatus status) { - AssociationCriteria criteria = getCriteria(null, (SortingClause[]) null); - if(status != null) criteria.add("interview.status", Operation.eq, status); - return criteria.count(); - } - - public List getParticipants(Date from, Date to, PagingClause paging, SortingClause... clauses) { - AssociationCriteria criteria = getCriteria(paging, clauses); - - if(from != null) criteria.add("appointment.date", Operation.ge, from); - if(to != null) criteria.add("appointment.date", Operation.le, to); - - return criteria.list(); - } - - public int countParticipants(Date from, Date to) { - AssociationCriteria criteria = getCriteria(null, (SortingClause[]) null); - - if(from != null) criteria.add("appointment.date", Operation.ge, from); - if(to != null) criteria.add("appointment.date", Operation.le, to); - - return criteria.count(); - } - - private AssociationCriteria getCriteria(PagingClause paging, SortingClause... clauses) { - AssociationCriteria criteria = AssociationCriteria.create(Participant.class, getSession()); - - if(paging != null) criteria.addPagingClause(paging); - if(clauses != null) criteria.addSortingClauses(clauses); - - return criteria; - } - - public List getParticipantsByName(String likeName, PagingClause paging, SortingClause... clauses) { - return getCriteriaByName(likeName, null, (SortingClause[]) null).list(); - } - - public int countParticipantsByName(String likeName) { - return getCriteriaByName(likeName, null, (SortingClause[]) null).count(); - } - - private AssociationCriteria getCriteriaByName(String likeName, PagingClause paging, SortingClause... clauses) { - AssociationCriteria criteria = getCriteria(paging, clauses); - - if(likeName != null) { - int idx = likeName.indexOf(' '); - if(idx != -1) { - String likeFirstName = likeName.substring(0, idx); - String likeLastName = likeName.substring(idx + 1, likeName.length()); - criteria.add("firstName", Operation.ilike, "%" + likeFirstName + "%").add("lastName", Operation.ilike, "%" + likeLastName + "%"); - } else { - criteria.getCriteria().add(Restrictions.or(Restrictions.ilike("firstName", "%" + likeName + "%"), Restrictions.ilike("lastName", "%" + likeName + "%"))); - } - } - - return criteria; - } - - @SuppressWarnings("unchecked") - public List getParticipantsByCode(String code, PagingClause paging, SortingClause... clauses) { - Query participantQuery = createParticipantsByCodeQuery(code); - - participantQuery.setMaxResults(paging.getLimit()); - participantQuery.setFirstResult(paging.getOffset()); - - return participantQuery.list(); - } - - @SuppressWarnings("unchecked") - public int countParticipantsByCode(String code) { - Query participantQuery = createParticipantsByCodeQuery(code); - - List results = participantQuery.list(); - - int count = 0; - - if(results != null) { - count = results.size(); - } - - return count; - } - - private Query createParticipantsByCodeQuery(String code) { - Query participantQuery = null; - - if(code != null) { - participantQuery = getSession().createQuery("from Participant p where p.barcode = :barcode or p.enrollmentId = :appointmentCode"); - participantQuery.setString("barcode", code); - participantQuery.setString("appointmentCode", code); - } else { - participantQuery = getSession().createQuery("from Participant"); - } - - return participantQuery; - } - - protected List getNotReceivedParticipants() { - return getSession().createCriteria(Participant.class).add(Restrictions.isNull("barcode")).list(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl.hibernate; + +import java.util.Date; +import java.util.List; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Restrictions; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.core.service.impl.hibernate.AssociationCriteria; +import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.impl.DefaultParticipantServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.annotation.Transactional; + +/** + * Implementation of hibernate specific methods of Participant Service + * @see#ParticipantService. + * @author Yannick Marcon + * + */ +@Transactional +public class ParticipantServiceHibernateImpl extends DefaultParticipantServiceImpl { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ParticipantServiceHibernateImpl.class); + + private SessionFactory factory; + + public void setSessionFactory(SessionFactory factory) { + this.factory = factory; + } + + private Session getSession() { + return factory.getCurrentSession(); + } + + public List getParticipants(InterviewStatus status, PagingClause paging, SortingClause... clauses) { + AssociationCriteria criteria = getCriteria(paging, clauses); + if(status != null) criteria.add("interview.status", Operation.eq, status); + return criteria.list(); + } + + public int countParticipants(InterviewStatus status) { + AssociationCriteria criteria = getCriteria(null, (SortingClause[]) null); + if(status != null) criteria.add("interview.status", Operation.eq, status); + return criteria.count(); + } + + public List getParticipants(Date from, Date to, PagingClause paging, SortingClause... clauses) { + AssociationCriteria criteria = getCriteria(paging, clauses); + + if(from != null) criteria.add("appointment.date", Operation.ge, from); + if(to != null) criteria.add("appointment.date", Operation.le, to); + + return criteria.list(); + } + + public int countParticipants(Date from, Date to) { + AssociationCriteria criteria = getCriteria(null, (SortingClause[]) null); + + if(from != null) criteria.add("appointment.date", Operation.ge, from); + if(to != null) criteria.add("appointment.date", Operation.le, to); + + return criteria.count(); + } + + private AssociationCriteria getCriteria(PagingClause paging, SortingClause... clauses) { + AssociationCriteria criteria = AssociationCriteria.create(Participant.class, getSession()); + + if(paging != null) criteria.addPagingClause(paging); + if(clauses != null) criteria.addSortingClauses(clauses); + + return criteria; + } + + public List getParticipantsByName(String likeName, PagingClause paging, SortingClause... clauses) { + return getCriteriaByName(likeName, null, (SortingClause[]) null).list(); + } + + public int countParticipantsByName(String likeName) { + return getCriteriaByName(likeName, null, (SortingClause[]) null).count(); + } + + private AssociationCriteria getCriteriaByName(String likeName, PagingClause paging, SortingClause... clauses) { + AssociationCriteria criteria = getCriteria(paging, clauses); + + if(likeName != null) { + int idx = likeName.indexOf(' '); + if(idx != -1) { + String likeFirstName = likeName.substring(0, idx); + String likeLastName = likeName.substring(idx + 1, likeName.length()); + criteria.add("firstName", Operation.ilike, "%" + likeFirstName + "%").add("lastName", Operation.ilike, "%" + likeLastName + "%"); + } else { + criteria.getCriteria().add(Restrictions.or(Restrictions.ilike("firstName", "%" + likeName + "%"), Restrictions.ilike("lastName", "%" + likeName + "%"))); + } + } + + return criteria; + } + + @SuppressWarnings("unchecked") + public List getParticipantsByCode(String code, PagingClause paging, SortingClause... clauses) { + Query participantQuery = createParticipantsByCodeQuery(code); + + participantQuery.setMaxResults(paging.getLimit()); + participantQuery.setFirstResult(paging.getOffset()); + + return participantQuery.list(); + } + + @SuppressWarnings("unchecked") + public int countParticipantsByCode(String code) { + Query participantQuery = createParticipantsByCodeQuery(code); + + List results = participantQuery.list(); + + int count = 0; + + if(results != null) { + count = results.size(); + } + + return count; + } + + private Query createParticipantsByCodeQuery(String code) { + Query participantQuery = null; + + if(code != null) { + participantQuery = getSession().createQuery("from Participant p where p.barcode = :barcode or p.enrollmentId = :appointmentCode"); + participantQuery.setString("barcode", code); + participantQuery.setString("appointmentCode", code); + } else { + participantQuery = getSession().createQuery("from Participant"); + } + + return participantQuery; + } + + protected List getNotReceivedParticipants() { + return getSession().createCriteria(Participant.class).add(Restrictions.isNull("barcode")).list(); + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/UserServiceHibernateImpl.java b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/UserServiceHibernateImpl.java index 33ddb4f28..07ce04d39 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/UserServiceHibernateImpl.java +++ b/onyx-core/src/main/java/org/obiba/onyx/core/service/impl/hibernate/UserServiceHibernateImpl.java @@ -1,65 +1,74 @@ -package org.obiba.onyx.core.service.impl.hibernate; - -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.core.service.impl.hibernate.AssociationCriteria; -import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.impl.DefaultUserServiceImpl; -import org.springframework.transaction.annotation.Transactional; - -/** - * Implementation of hibernate specific methods of User Service - * @see#UserService. - * @author acarey - * - */ -@Transactional -public class UserServiceHibernateImpl extends DefaultUserServiceImpl { - - private SessionFactory factory; - - public void setSessionFactory(SessionFactory factory) { - this.factory = factory; - } - - private Session getSession() { - return factory.getCurrentSession(); - } - - public List getUsers(User template, PagingClause paging, SortingClause... clauses) { - return getUserCriteria(template, paging, clauses).list(); - } - - public int getUserCount(User template) { - return getUserCriteria(template, null, (SortingClause) null).count(); - } - - private AssociationCriteria getUserCriteria(User template, PagingClause paging, SortingClause... clauses) { - AssociationCriteria criteria = AssociationCriteria.create(User.class, getSession()); - - if (template.isDeleted() == false) criteria.add("deleted", Operation.eq, template.isDeleted()); - if(paging != null) criteria.addPagingClause(paging); - if(clauses != null) criteria.addSortingClauses(clauses); - - return criteria; - } - - public List getRoles(SortingClause... clauses) { - return getRoleCriteria(clauses).list(); - } - - private AssociationCriteria getRoleCriteria(SortingClause... clauses) { - AssociationCriteria criteria = AssociationCriteria.create(Role.class, getSession()); - - if(clauses != null) criteria.addSortingClauses(clauses); - - return criteria; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service.impl.hibernate; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.core.service.impl.hibernate.AssociationCriteria; +import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.impl.DefaultUserServiceImpl; +import org.springframework.transaction.annotation.Transactional; + +/** + * Implementation of hibernate specific methods of User Service + * @see#UserService. + * @author acarey + * + */ +@Transactional +public class UserServiceHibernateImpl extends DefaultUserServiceImpl { + + private SessionFactory factory; + + public void setSessionFactory(SessionFactory factory) { + this.factory = factory; + } + + private Session getSession() { + return factory.getCurrentSession(); + } + + public List getUsers(User template, PagingClause paging, SortingClause... clauses) { + return getUserCriteria(template, paging, clauses).list(); + } + + public int getUserCount(User template) { + return getUserCriteria(template, null, (SortingClause) null).count(); + } + + private AssociationCriteria getUserCriteria(User template, PagingClause paging, SortingClause... clauses) { + AssociationCriteria criteria = AssociationCriteria.create(User.class, getSession()); + + if (template.isDeleted() == false) criteria.add("deleted", Operation.eq, template.isDeleted()); + if(paging != null) criteria.addPagingClause(paging); + if(clauses != null) criteria.addSortingClauses(clauses); + + return criteria; + } + + public List getRoles(SortingClause... clauses) { + return getRoleCriteria(clauses).list(); + } + + private AssociationCriteria getRoleCriteria(SortingClause... clauses) { + AssociationCriteria criteria = AssociationCriteria.create(Role.class, getSession()); + + if(clauses != null) criteria.addSortingClauses(clauses); + + return criteria; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/Action.java b/onyx-core/src/main/java/org/obiba/onyx/engine/Action.java index c52c44f06..e760f3edf 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/Action.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/Action.java @@ -1,118 +1,127 @@ -package org.obiba.onyx.engine; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.user.User; - -/** - * Action is the track of who did what, when on who and why in the Onyx system. - * - * @see ActionType - * @author Yannick Marcon - * - */ -@Entity -public class Action extends AbstractEntity { - - private static final long serialVersionUID = -943609521870150739L; - - @ManyToOne - @JoinColumn(name="user_id") - private User user; - - @ManyToOne - @JoinColumn(name="interview_id") - private Interview interview; - - @Enumerated(EnumType.STRING) - private ActionType type; - - private String stage; - - @Temporal(TemporalType.TIMESTAMP) - private Date dateTime; - - private String comment; - - private String eventReason; - - public Action() { - } - - public Action(ActionDefinition definition) { - this.type = definition.getType(); - dateTime = new Date(); - } - - public final User getUser() { - return user; - } - - public final void setUser(User user) { - this.user = user; - } - - public final Interview getInterview() { - return interview; - } - - public final void setInterview(Interview interview) { - this.interview = interview; - } - - public final ActionType getActionType() { - return type; - } - - public final void setActionType(ActionType actionType) { - this.type = actionType; - } - - public final String getStage() { - return stage; - } - - public final void setStage(String stage) { - this.stage = stage; - } - - public final Date getDateTime() { - return dateTime; - } - - public final void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public final String getComment() { - return comment; - } - - public final void setComment(String comment) { - this.comment = comment; - } - - public final String getEventReason() { - return eventReason; - } - - public final void setEventReason(String eventReason) { - this.eventReason = eventReason; - } - - @Override - public String toString() { - return "[" + type + " " + dateTime + "]"; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.user.User; + +/** + * Action is the track of who did what, when on who and why in the Onyx system. + * + * @see ActionType + * @author Yannick Marcon + * + */ +@Entity +public class Action extends AbstractEntity { + + private static final long serialVersionUID = -943609521870150739L; + + @ManyToOne + @JoinColumn(name="user_id") + private User user; + + @ManyToOne + @JoinColumn(name="interview_id") + private Interview interview; + + @Enumerated(EnumType.STRING) + private ActionType type; + + private String stage; + + @Temporal(TemporalType.TIMESTAMP) + private Date dateTime; + + private String comment; + + private String eventReason; + + public Action() { + } + + public Action(ActionDefinition definition) { + this.type = definition.getType(); + dateTime = new Date(); + } + + public final User getUser() { + return user; + } + + public final void setUser(User user) { + this.user = user; + } + + public final Interview getInterview() { + return interview; + } + + public final void setInterview(Interview interview) { + this.interview = interview; + } + + public final ActionType getActionType() { + return type; + } + + public final void setActionType(ActionType actionType) { + this.type = actionType; + } + + public final String getStage() { + return stage; + } + + public final void setStage(String stage) { + this.stage = stage; + } + + public final Date getDateTime() { + return dateTime; + } + + public final void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public final String getComment() { + return comment; + } + + public final void setComment(String comment) { + this.comment = comment; + } + + public final String getEventReason() { + return eventReason; + } + + public final void setEventReason(String eventReason) { + this.eventReason = eventReason; + } + + @Override + public String toString() { + return "[" + type + " " + dateTime + "]"; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinition.java index 9707414b7..f68b3be13 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinition.java @@ -1,148 +1,157 @@ -package org.obiba.onyx.engine; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * An action definition, defines how getting information from the user to produce an {@link Action}. - * - * @see ActionType - * @author Yannick Marcon - * - */ -public class ActionDefinition implements Serializable { - - private static final long serialVersionUID = 5052458659458743800L; - - private ActionType type; - - /** - * Label to be displayed to user for action identification. - */ - private String label; - - /** - * Description of the information needed to produce an action. - */ - private String description; - - /** - * Says if it requires operator authentication (using its password). - */ - private boolean askPassword = false; - - /** - * Says if a comment is mandatory. - */ - private boolean commentMandatory = true; - - /** - * Says if a reason is mandatory. - */ - private boolean reasonMandatory = false; - - /** - * Specify the default reason. - */ - private String defaultReason; - - /** - * List of reasons to be picked-up. - */ - private List reasons; - - /** - * Path to icon for displaying action in a friendly way. - */ - private String iconPath; - - public ActionDefinition(ActionType type, String label) { - this.type = type; - this.label = label; - } - - public ActionType getType() { - return type; - } - - public void setType(ActionType type) { - this.type = type; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public boolean isAskPassword() { - return askPassword; - } - - public void setAskPassword(boolean askPassword) { - this.askPassword = askPassword; - } - - public boolean isCommentMandatory() { - return commentMandatory; - } - - public void setCommentMandatory(boolean commentMandatory) { - this.commentMandatory = commentMandatory; - } - - public boolean isReasonMandatory() { - return reasonMandatory; - } - - public void setReasonMandatory(boolean reasonMandatory) { - this.reasonMandatory = reasonMandatory; - } - - public String getDefaultReason() { - return defaultReason; - } - - public void setDefaultReason(String defaultReason) { - this.defaultReason = defaultReason; - } - - public List getReasons() { - return reasons != null ? reasons : (reasons = new ArrayList()); - } - - public void addReason(String reason) { - getReasons().add(reason); - } - - public void addReasons(String[] reasons) { - for(String reason : reasons) { - getReasons().add(reason); - } - } - - public String getIconPath() { - return iconPath; - } - - public void setIconPath(String iconPath) { - this.iconPath = iconPath; - } - - @Override - public String toString() { - return type.toString(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * An action definition, defines how getting information from the user to produce an {@link Action}. + * + * @see ActionType + * @author Yannick Marcon + * + */ +public class ActionDefinition implements Serializable { + + private static final long serialVersionUID = 5052458659458743800L; + + private ActionType type; + + /** + * Label to be displayed to user for action identification. + */ + private String label; + + /** + * Description of the information needed to produce an action. + */ + private String description; + + /** + * Says if it requires operator authentication (using its password). + */ + private boolean askPassword = false; + + /** + * Says if a comment is mandatory. + */ + private boolean commentMandatory = true; + + /** + * Says if a reason is mandatory. + */ + private boolean reasonMandatory = false; + + /** + * Specify the default reason. + */ + private String defaultReason; + + /** + * List of reasons to be picked-up. + */ + private List reasons; + + /** + * Path to icon for displaying action in a friendly way. + */ + private String iconPath; + + public ActionDefinition(ActionType type, String label) { + this.type = type; + this.label = label; + } + + public ActionType getType() { + return type; + } + + public void setType(ActionType type) { + this.type = type; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isAskPassword() { + return askPassword; + } + + public void setAskPassword(boolean askPassword) { + this.askPassword = askPassword; + } + + public boolean isCommentMandatory() { + return commentMandatory; + } + + public void setCommentMandatory(boolean commentMandatory) { + this.commentMandatory = commentMandatory; + } + + public boolean isReasonMandatory() { + return reasonMandatory; + } + + public void setReasonMandatory(boolean reasonMandatory) { + this.reasonMandatory = reasonMandatory; + } + + public String getDefaultReason() { + return defaultReason; + } + + public void setDefaultReason(String defaultReason) { + this.defaultReason = defaultReason; + } + + public List getReasons() { + return reasons != null ? reasons : (reasons = new ArrayList()); + } + + public void addReason(String reason) { + getReasons().add(reason); + } + + public void addReasons(String[] reasons) { + for(String reason : reasons) { + getReasons().add(reason); + } + } + + public String getIconPath() { + return iconPath; + } + + public void setIconPath(String iconPath) { + this.iconPath = iconPath; + } + + @Override + public String toString() { + return type.toString(); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinitionBuilder.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinitionBuilder.java index 48d2af6ce..855b31a50 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinitionBuilder.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionDefinitionBuilder.java @@ -1,96 +1,105 @@ -package org.obiba.onyx.engine; - -import java.io.Serializable; - -/** - * An {@link ActionDefinition} builder, to allow friendly action definition creation. - * - * @see ActionType, ActionDefinition - * @author Yannick Marcon - * - */ -public class ActionDefinitionBuilder implements Serializable { - - private static final long serialVersionUID = 5052458659458743800L; - - /** - * Default start action. - */ - public static final ActionDefinition START_ACTION = ActionDefinitionBuilder.create(ActionType.EXECUTE, "Start").setDescription("You may enter a comment before starting this stage.").setAskPassword(true).getActionDefinition(); - - /** - * Default cancel action. - */ - public static final ActionDefinition CANCEL_ACTION = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may enter a comment before cancelling this stage.").getActionDefinition(); - - /** - * Cancel action for a skipped stage (requires a different description). - */ - public static final ActionDefinition CANCEL_SKIPPED_ACTION = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("Please explain why you are reinstating this stage.").getActionDefinition(); - - /** - * Default comment action. - */ - public static final ActionDefinition COMMENT_ACTION = ActionDefinitionBuilder.create(ActionType.COMMENT, "Comment").setDescription("You may enter a free comment.").getActionDefinition(); - - /** - * Default complete action. - */ - public static final ActionDefinition COMPLETE_ACTION = ActionDefinitionBuilder.create(ActionType.COMPLETE, "Complete").getActionDefinition(); - - private ActionDefinition actionDefinition; - - private ActionDefinitionBuilder() { - } - - public ActionDefinition getActionDefinition() { - return actionDefinition; - } - - public static ActionDefinitionBuilder create(ActionType type, String label) { - ActionDefinitionBuilder builder = new ActionDefinitionBuilder(); - builder.actionDefinition = new ActionDefinition(type, label); - return builder; - } - - public ActionDefinitionBuilder setDescription(String description) { - actionDefinition.setDescription(description); - return this; - } - - public ActionDefinitionBuilder setAskPassword(boolean askPassword) { - actionDefinition.setAskPassword(askPassword); - return this; - } - - public ActionDefinitionBuilder setCommentMandatory(boolean commentMandatory) { - actionDefinition.setCommentMandatory(commentMandatory); - return this; - } - - public ActionDefinitionBuilder setReasonMandatory(boolean reasonMandatory) { - actionDefinition.setReasonMandatory(reasonMandatory); - return this; - } - - public ActionDefinitionBuilder setDefaultReason(String defaultReason) { - actionDefinition.setDefaultReason(defaultReason); - return this; - } - - public ActionDefinitionBuilder addReason(String reason) { - actionDefinition.addReason(reason); - return this; - } - - public ActionDefinitionBuilder addReasons(String[] reasons) { - actionDefinition.addReasons(reasons); - return this; - } - - public ActionDefinitionBuilder setIconPath(String iconPath) { - actionDefinition.setIconPath(iconPath); - return this; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import java.io.Serializable; + +/** + * An {@link ActionDefinition} builder, to allow friendly action definition creation. + * + * @see ActionType, ActionDefinition + * @author Yannick Marcon + * + */ +public class ActionDefinitionBuilder implements Serializable { + + private static final long serialVersionUID = 5052458659458743800L; + + /** + * Default start action. + */ + public static final ActionDefinition START_ACTION = ActionDefinitionBuilder.create(ActionType.EXECUTE, "Start").setDescription("You may enter a comment before starting this stage.").setAskPassword(true).getActionDefinition(); + + /** + * Default cancel action. + */ + public static final ActionDefinition CANCEL_ACTION = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may enter a comment before cancelling this stage.").getActionDefinition(); + + /** + * Cancel action for a skipped stage (requires a different description). + */ + public static final ActionDefinition CANCEL_SKIPPED_ACTION = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("Please explain why you are reinstating this stage.").getActionDefinition(); + + /** + * Default comment action. + */ + public static final ActionDefinition COMMENT_ACTION = ActionDefinitionBuilder.create(ActionType.COMMENT, "Comment").setDescription("You may enter a free comment.").getActionDefinition(); + + /** + * Default complete action. + */ + public static final ActionDefinition COMPLETE_ACTION = ActionDefinitionBuilder.create(ActionType.COMPLETE, "Complete").getActionDefinition(); + + private ActionDefinition actionDefinition; + + private ActionDefinitionBuilder() { + } + + public ActionDefinition getActionDefinition() { + return actionDefinition; + } + + public static ActionDefinitionBuilder create(ActionType type, String label) { + ActionDefinitionBuilder builder = new ActionDefinitionBuilder(); + builder.actionDefinition = new ActionDefinition(type, label); + return builder; + } + + public ActionDefinitionBuilder setDescription(String description) { + actionDefinition.setDescription(description); + return this; + } + + public ActionDefinitionBuilder setAskPassword(boolean askPassword) { + actionDefinition.setAskPassword(askPassword); + return this; + } + + public ActionDefinitionBuilder setCommentMandatory(boolean commentMandatory) { + actionDefinition.setCommentMandatory(commentMandatory); + return this; + } + + public ActionDefinitionBuilder setReasonMandatory(boolean reasonMandatory) { + actionDefinition.setReasonMandatory(reasonMandatory); + return this; + } + + public ActionDefinitionBuilder setDefaultReason(String defaultReason) { + actionDefinition.setDefaultReason(defaultReason); + return this; + } + + public ActionDefinitionBuilder addReason(String reason) { + actionDefinition.addReason(reason); + return this; + } + + public ActionDefinitionBuilder addReasons(String[] reasons) { + actionDefinition.addReasons(reasons); + return this; + } + + public ActionDefinitionBuilder setIconPath(String iconPath) { + actionDefinition.setIconPath(iconPath); + return this; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionType.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionType.java index 0dda5c019..577f92a76 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ActionType.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ActionType.java @@ -1,75 +1,84 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.TransitionEvent; - -/** - * Onyx has a fixed set of actions, that can be freely associated to different {@link TransitionEvent} through - * {@link IStageExecution}. - * @author Yannick Marcon - * - */ -public enum ActionType { - /** - * Does not not modify {@link IStageExecution} state. - */ - COMMENT { - @Override - public void act(IStageExecution execution, Action action) { - } - }, - /** - * {@link IStageExecution#complete(Action)} - */ - COMPLETE { - @Override - public void act(IStageExecution execution, Action action) { - execution.complete(action); - } - }, - /** - * {@link IStageExecution#execute(Action)} - */ - EXECUTE { - @Override - public void act(IStageExecution execution, Action action) { - execution.execute(action); - } - }, - /** - * {@link IStageExecution#interrupt(Action)} - */ - INTERRUPT { - @Override - public void act(IStageExecution execution, Action action) { - execution.interrupt(action); - execution.setReason(action); - } - }, - /** - * {@link IStageExecution#stop(Action)} - */ - STOP { - @Override - public void act(IStageExecution execution, Action action) { - execution.stop(action); - } - }, - /** - * {@link IStageExecution#skip(Action)} - */ - SKIP { - @Override - public void act(IStageExecution execution, Action action) { - execution.skip(action); - execution.setReason(action); - } - }; - - /** - * Ask the {@link IStageExecution} to perform {@link Action} according to its {@link ActionType}. - * @param execution - * @param action - */ - public abstract void act(IStageExecution execution, Action action); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.TransitionEvent; + +/** + * Onyx has a fixed set of actions, that can be freely associated to different {@link TransitionEvent} through + * {@link IStageExecution}. + * @author Yannick Marcon + * + */ +public enum ActionType { + /** + * Does not not modify {@link IStageExecution} state. + */ + COMMENT { + @Override + public void act(IStageExecution execution, Action action) { + } + }, + /** + * {@link IStageExecution#complete(Action)} + */ + COMPLETE { + @Override + public void act(IStageExecution execution, Action action) { + execution.complete(action); + } + }, + /** + * {@link IStageExecution#execute(Action)} + */ + EXECUTE { + @Override + public void act(IStageExecution execution, Action action) { + execution.execute(action); + } + }, + /** + * {@link IStageExecution#interrupt(Action)} + */ + INTERRUPT { + @Override + public void act(IStageExecution execution, Action action) { + execution.interrupt(action); + execution.setReason(action); + } + }, + /** + * {@link IStageExecution#stop(Action)} + */ + STOP { + @Override + public void act(IStageExecution execution, Action action) { + execution.stop(action); + } + }, + /** + * {@link IStageExecution#skip(Action)} + */ + SKIP { + @Override + public void act(IStageExecution execution, Action action) { + execution.skip(action); + execution.setReason(action); + } + }; + + /** + * Ask the {@link IStageExecution} to perform {@link Action} according to its {@link ActionType}. + * @param execution + * @param action + */ + public abstract void act(IStageExecution execution, Action action); +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ConsentStageDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ConsentStageDependencyCondition.java index b78a2080d..c24bf8bae 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ConsentStageDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ConsentStageDependencyCondition.java @@ -1,59 +1,68 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.util.data.Data; - -/** - * Specific Stage Dependency condition for Consent step - * @author acarey - */ -public class ConsentStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private String stageName; - - public ConsentStageDependencyCondition() { - } - - public ConsentStageDependencyCondition(String name) { - this.stageName = name; - } - - /** - * Returns a Boolean depending on the fact that the step is completed and also on its result - * Null if not completed - * True if completed and consented - * False if completed and not consented - */ - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - IStageExecution consent = activeInterviewService.getStageExecution(stageName); - if(consent != null) { - if(!consent.isCompleted()) return null; - else { - Data consentData = consent.getData("Consent"); - if(consentData != null) { - return (Boolean) consentData.getValue(); - } else - return false; - } - } - return null; - } - - @Override - public boolean isDependentOn(String stageName) { - return this.stageName.equals(stageName); - } - - public String getStageName() { - return stageName; - } - - public void setStageName(String stageName) { - this.stageName = stageName; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.util.data.Data; + +/** + * Specific Stage Dependency condition for Consent step + * @author acarey + */ +public class ConsentStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private String stageName; + + public ConsentStageDependencyCondition() { + } + + public ConsentStageDependencyCondition(String name) { + this.stageName = name; + } + + /** + * Returns a Boolean depending on the fact that the step is completed and also on its result + * Null if not completed + * True if completed and consented + * False if completed and not consented + */ + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + IStageExecution consent = activeInterviewService.getStageExecution(stageName); + if(consent != null) { + if(!consent.isCompleted()) return null; + else { + Data consentData = consent.getData("Consent"); + if(consentData != null) { + return (Boolean) consentData.getValue(); + } else + return false; + } + } + return null; + } + + @Override + public boolean isDependentOn(String stageName) { + return this.stageName.equals(stageName); + } + + public String getStageName() { + return stageName; + } + + public void setStageName(String stageName) { + this.stageName = stageName; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/IInterviewListener.java b/onyx-core/src/main/java/org/obiba/onyx/engine/IInterviewListener.java index aa888c89d..578acf0c0 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/IInterviewListener.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/IInterviewListener.java @@ -1,20 +1,29 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; - -/** - * Stages execution context may want to be informed when the englobing interview changes its status. - * @author Yannick Marcon - * - */ -public interface IInterviewListener { - - /** - * Called when given interview goes to status completed. - * @see InterviewStatus - * @param interview - */ - public void onInterviewCompleted(Interview interview); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; + +/** + * Stages execution context may want to be informed when the englobing interview changes its status. + * @author Yannick Marcon + * + */ +public interface IInterviewListener { + + /** + * Called when given interview goes to status completed. + * @see InterviewStatus + * @param interview + */ + public void onInterviewCompleted(Interview interview); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/InverseStageDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/InverseStageDependencyCondition.java index 0085fa2b7..a0750916a 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/InverseStageDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/InverseStageDependencyCondition.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.service.ActiveInterviewService; - -/** - * Case of Inverse Stage Dependency Condition - * @author acarey - */ -public class InverseStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private StageDependencyCondition stageDependencyCondition; - - /** - * Returns the inverse of the specified condition - */ - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - if (stageDependencyCondition.isDependencySatisfied(activeInterviewService) == null) - return false; - return (!(stageDependencyCondition.isDependencySatisfied(activeInterviewService))); - } - - @Override - public boolean isDependentOn(String stageName) { - return stageDependencyCondition.isDependentOn(stageName); - } - - public void setStageDependencyCondition(StageDependencyCondition stageDependencyCondition) { - this.stageDependencyCondition = stageDependencyCondition; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.service.ActiveInterviewService; + +/** + * Case of Inverse Stage Dependency Condition + * @author acarey + */ +public class InverseStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private StageDependencyCondition stageDependencyCondition; + + /** + * Returns the inverse of the specified condition + */ + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + if (stageDependencyCondition.isDependencySatisfied(activeInterviewService) == null) + return false; + return (!(stageDependencyCondition.isDependencySatisfied(activeInterviewService))); + } + + @Override + public boolean isDependentOn(String stageName) { + return stageDependencyCondition.isDependentOn(stageName); + } + + public void setStageDependencyCondition(StageDependencyCondition stageDependencyCondition) { + this.stageDependencyCondition = stageDependencyCondition; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/Module.java b/onyx-core/src/main/java/org/obiba/onyx/engine/Module.java index 4ea1c4c87..5fa4f8a0a 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/Module.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/Module.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.engine; import java.util.List; diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleDependencyCondition.java index 8c7820ec1..eab01ebf1 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleDependencyCondition.java @@ -1,84 +1,93 @@ -package org.obiba.onyx.engine; - -import java.util.List; - -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.onyx.engine.state.IStageExecution; - -/** - * Mica specific dependency condition depending on the presence of runValues for the stage - * @author acarey - */ -public class ModuleDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private ModuleRegistry moduleRegistry; - - private String moduleName; - - public ModuleDependencyCondition() { - } - - /** - * Returns true if dependency is satisfied, false if it is not, - * null if it's impossible to know whether it's right or wrong (step not done yet) - * @param activeInterviewService - * @return - */ - @SuppressWarnings("static-access") - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - - Module module = moduleRegistry.getModule(moduleName); - - List moduleStage = module.getStages(); - - for(Stage oneStage : moduleStage) { - IStageExecution stageExecution = activeInterviewService.getStageExecution(oneStage.getName()); - - if(!stageExecution.isCompleted()) { - return null; - } - } - - return true; - } - - @Override - public boolean isDependentOn(String stageName) { - - Module module = moduleRegistry.getModule(moduleName); - - List moduleStage = module.getStages(); - - for(Stage oneStage : moduleStage) { - - if(oneStage.getName().equals(stageName)) { - return true; - } - } - - return false; - } - - public ModuleRegistry getModuleRegistry() { - return moduleRegistry; - } - - public void setModuleRegistry(ModuleRegistry moduleRegistry) { - this.moduleRegistry = moduleRegistry; - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import java.util.List; + +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.onyx.engine.state.IStageExecution; + +/** + * Mica specific dependency condition depending on the presence of runValues for the stage + * @author acarey + */ +public class ModuleDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private ModuleRegistry moduleRegistry; + + private String moduleName; + + public ModuleDependencyCondition() { + } + + /** + * Returns true if dependency is satisfied, false if it is not, + * null if it's impossible to know whether it's right or wrong (step not done yet) + * @param activeInterviewService + * @return + */ + @SuppressWarnings("static-access") + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + + Module module = moduleRegistry.getModule(moduleName); + + List moduleStage = module.getStages(); + + for(Stage oneStage : moduleStage) { + IStageExecution stageExecution = activeInterviewService.getStageExecution(oneStage.getName()); + + if(!stageExecution.isCompleted()) { + return null; + } + } + + return true; + } + + @Override + public boolean isDependentOn(String stageName) { + + Module module = moduleRegistry.getModule(moduleName); + + List moduleStage = module.getStages(); + + for(Stage oneStage : moduleStage) { + + if(oneStage.getName().equals(stageName)) { + return true; + } + } + + return false; + } + + public ModuleRegistry getModuleRegistry() { + return moduleRegistry; + } + + public void setModuleRegistry(ModuleRegistry moduleRegistry) { + this.moduleRegistry = moduleRegistry; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistrationListener.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistrationListener.java index 4ae882aaa..488f50c35 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistrationListener.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistrationListener.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.engine; import java.util.Map; diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistry.java b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistry.java index 26411a80a..3153998f8 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistry.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/ModuleRegistry.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.engine; import java.util.ArrayList; diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/MultipleStageDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/MultipleStageDependencyCondition.java index 1c2060557..966e78455 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/MultipleStageDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/MultipleStageDependencyCondition.java @@ -1,64 +1,73 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.service.ActiveInterviewService; - -/** - * Case of Multiple Stage Dependency Condition - * Compares two dependency conditions with AND or OR relation - * @author acarey - */ -public class MultipleStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private Operator operator; - - private StageDependencyCondition leftStageDependencyCondition; - - private StageDependencyCondition rightStageDependencyCondition; - - /** - * Returns a Boolean depending on the AND/OR relation between the conditions - * If one condition is null and the relation is AND => returns null - * if one condition is null and the relation is OR => returns null if the not null condition is false - * (otherwise returns true) - */ - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - Boolean leftResult = leftStageDependencyCondition.isDependencySatisfied(activeInterviewService); - Boolean rightResult = rightStageDependencyCondition.isDependencySatisfied(activeInterviewService); - - if(leftResult != null && rightResult != null) { - if(operator.equals(Operator.AND)) return (leftResult && rightResult); - else - return (leftResult || rightResult); - } else { - if(operator.equals(Operator.AND)) { - if(leftResult != null && leftResult == false) return false; - if(rightResult != null && rightResult == false) return false; - return null; - } else { - if(leftResult != null) return (leftResult == true) ? leftResult : null; - if(rightResult != null) return (rightResult == true) ? rightResult : null; - return null; - } - } - } - - @Override - public boolean isDependentOn(String stageName) { - return (leftStageDependencyCondition.isDependentOn(stageName) || rightStageDependencyCondition.isDependentOn(stageName)); - } - - public void setLeftStageDependencyCondition(StageDependencyCondition leftStageDependencyCondition) { - this.leftStageDependencyCondition = leftStageDependencyCondition; - } - - public void setRightStageDependencyCondition(StageDependencyCondition rightStageDependencyCondition) { - this.rightStageDependencyCondition = rightStageDependencyCondition; - } - - public void setOperator(Operator operator) { - this.operator = operator; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.service.ActiveInterviewService; + +/** + * Case of Multiple Stage Dependency Condition + * Compares two dependency conditions with AND or OR relation + * @author acarey + */ +public class MultipleStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private Operator operator; + + private StageDependencyCondition leftStageDependencyCondition; + + private StageDependencyCondition rightStageDependencyCondition; + + /** + * Returns a Boolean depending on the AND/OR relation between the conditions + * If one condition is null and the relation is AND => returns null + * if one condition is null and the relation is OR => returns null if the not null condition is false + * (otherwise returns true) + */ + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + Boolean leftResult = leftStageDependencyCondition.isDependencySatisfied(activeInterviewService); + Boolean rightResult = rightStageDependencyCondition.isDependencySatisfied(activeInterviewService); + + if(leftResult != null && rightResult != null) { + if(operator.equals(Operator.AND)) return (leftResult && rightResult); + else + return (leftResult || rightResult); + } else { + if(operator.equals(Operator.AND)) { + if(leftResult != null && leftResult == false) return false; + if(rightResult != null && rightResult == false) return false; + return null; + } else { + if(leftResult != null) return (leftResult == true) ? leftResult : null; + if(rightResult != null) return (rightResult == true) ? rightResult : null; + return null; + } + } + } + + @Override + public boolean isDependentOn(String stageName) { + return (leftStageDependencyCondition.isDependentOn(stageName) || rightStageDependencyCondition.isDependentOn(stageName)); + } + + public void setLeftStageDependencyCondition(StageDependencyCondition leftStageDependencyCondition) { + this.leftStageDependencyCondition = leftStageDependencyCondition; + } + + public void setRightStageDependencyCondition(StageDependencyCondition rightStageDependencyCondition) { + this.rightStageDependencyCondition = rightStageDependencyCondition; + } + + public void setOperator(Operator operator) { + this.operator = operator; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/Operator.java b/onyx-core/src/main/java/org/obiba/onyx/engine/Operator.java index c8400708c..bc5715ea9 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/Operator.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/Operator.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.engine; - -public enum Operator { - AND, OR -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +public enum Operator { + AND, OR +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/PreviousStageDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/PreviousStageDependencyCondition.java index 4bbc93bef..e640e1b3f 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/PreviousStageDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/PreviousStageDependencyCondition.java @@ -1,46 +1,55 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.service.ActiveInterviewService; - -/** - * Most simple case of Previous Stage Dependency Condition - * @author acarey - */ -public class PreviousStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private String stageName; - - public PreviousStageDependencyCondition() { - } - - public PreviousStageDependencyCondition(String name) { - this.stageName = name; - } - - /** - * returns true if stage execution is completed - * returns null if it's not completed - */ - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - if (!activeInterviewService.getStageExecution(stageName).isCompleted()) - return null; - else - return true; - } - - @Override - public boolean isDependentOn(String stageName) { - return this.stageName.equals(stageName); - } - - public String getStageName() { - return stageName; - } - - public void setStageName(String stageName) { - this.stageName = stageName; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.service.ActiveInterviewService; + +/** + * Most simple case of Previous Stage Dependency Condition + * @author acarey + */ +public class PreviousStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private String stageName; + + public PreviousStageDependencyCondition() { + } + + public PreviousStageDependencyCondition(String name) { + this.stageName = name; + } + + /** + * returns true if stage execution is completed + * returns null if it's not completed + */ + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + if (!activeInterviewService.getStageExecution(stageName).isCompleted()) + return null; + else + return true; + } + + @Override + public boolean isDependentOn(String stageName) { + return this.stageName.equals(stageName); + } + + public String getStageName() { + return stageName; + } + + public void setStageName(String stageName) { + this.stageName = stageName; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/Stage.java b/onyx-core/src/main/java/org/obiba/onyx/engine/Stage.java index 3ee2a77ae..e165e2e47 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/Stage.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/Stage.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.engine; import org.obiba.onyx.core.service.UserSessionService; diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/StageDependencyCondition.java b/onyx-core/src/main/java/org/obiba/onyx/engine/StageDependencyCondition.java index fdf6740a0..e448a4d72 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/StageDependencyCondition.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/StageDependencyCondition.java @@ -1,28 +1,37 @@ -package org.obiba.onyx.engine; - -import org.obiba.onyx.core.service.ActiveInterviewService; - -/** - * Base class for Stage Dependency Conditions. - * @author acarey - * - */ - -public abstract class StageDependencyCondition { - - /** - * Returns true if dependency is satisfied, false if it is not, - * null if it's impossible to know whether it's right or wrong (step not done yet) - * @param activeInterviewService - * @return - */ - public abstract Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService); - - /** - * returns true if this stageDependencyCondition depends on the specified stage - * @param stageName - * @return - */ - public abstract boolean isDependentOn(String stageName); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import org.obiba.onyx.core.service.ActiveInterviewService; + +/** + * Base class for Stage Dependency Conditions. + * @author acarey + * + */ + +public abstract class StageDependencyCondition { + + /** + * Returns true if dependency is satisfied, false if it is not, + * null if it's impossible to know whether it's right or wrong (step not done yet) + * @param activeInterviewService + * @return + */ + public abstract Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService); + + /** + * returns true if this stageDependencyCondition depends on the specified stage + * @param stageName + * @return + */ + public abstract boolean isDependentOn(String stageName); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/AbstractStageState.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/AbstractStageState.java index da9ced2d0..f8f6b6195 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/AbstractStageState.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/AbstractStageState.java @@ -1,180 +1,189 @@ -package org.obiba.onyx.engine.state; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.wicket.Component; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.util.data.Data; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -/** - * Base class for Stage states. - * @author Yannick Marcon - * - */ -public abstract class AbstractStageState implements IStageExecution, ITransitionListener, ApplicationContextAware { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(AbstractStageState.class); - - private ITransitionEventSink eventSink; - - private Stage stage; - - protected List actionDefinitions = new ArrayList(); - - protected List systemActionDefinitions = new ArrayList(); - - protected ApplicationContext context; - - protected ActiveInterviewService activeInterviewService; - - protected UserSessionService userSessionService; - - /** - * The reason the stage is in its current state (i.e., the action that caused the stage to transition to this state). - */ - private Action reason; - - public void setUserSessionService(UserSessionService userSessionService) { - this.userSessionService = userSessionService; - } - - public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { - this.activeInterviewService = activeInterviewService; - } - - public void setApplicationContext(ApplicationContext context) { - this.context = context; - } - - public void setStage(Stage stage) { - this.stage = stage; - } - - public Stage getStage() { - return stage; - } - - public void onTransition(IStageExecution execution, TransitionEvent event) { - Boolean var = areDependenciesCompleted(); - - if(var == null) { - if(wantTransitionEvent(TransitionEvent.INVALID)) castEvent(TransitionEvent.INVALID); - } else if(var == true && wantTransitionEvent(TransitionEvent.VALID)) castEvent(TransitionEvent.VALID); - else if(var == false && wantTransitionEvent(TransitionEvent.NOTAPPLICABLE)) castEvent(TransitionEvent.NOTAPPLICABLE); - } - - protected Boolean areDependenciesCompleted() { - if(stage.getStageDependencyCondition() != null) return stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService); - return true; - } - - public boolean removeAfterTransition() { - return false; - } - - protected void castEvent(TransitionEvent event) { - eventSink.castEvent(event); - } - - public void setEventSink(ITransitionEventSink eventSink) { - this.eventSink = eventSink; - } - - protected void addAction(ActionDefinition action) { - actionDefinitions.add(action); - } - - public List getActionDefinitions() { - return actionDefinitions; - } - - public ActionDefinition getActionDefinition(ActionType type) { - for(ActionDefinition def : actionDefinitions) { - if(def.getType().equals(type)) return def; - } - return null; - } - - public ActionDefinition getSystemActionDefinition(ActionType type) { - for(ActionDefinition def : systemActionDefinitions) { - if(def.getType().equals(type)) return def; - } - return null; - } - - protected void addSystemAction(ActionDefinition action) { - systemActionDefinitions.add(action); - } - - public List getSystemActionDefinitions() { - return systemActionDefinitions; - } - - public void execute(Action action) { - } - - public void interrupt(Action action) { - } - - public void skip(Action action) { - } - - public void stop(Action action) { - } - - public void complete(Action action) { - } - - public Component getWidget(String id) { - return null; - } - - public boolean isCompleted() { - return false; - } - - public boolean isFinal() { - return false; - } - - public boolean isInteractive() { - return false; - } - - public String getMessage() { - Locale locale = userSessionService.getLocale(); - return context.getMessage(getName(), null, locale); - } - - public Data getData(String key) { - return null; - } - - public void setReason(Action reason) { - this.reason = reason; - } - - public Action getReason() { - return reason; - } - - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - return true; - } - - public ActionType getStartingActionType() { - return null; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.apache.wicket.Component; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.util.data.Data; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +/** + * Base class for Stage states. + * @author Yannick Marcon + * + */ +public abstract class AbstractStageState implements IStageExecution, ITransitionListener, ApplicationContextAware { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(AbstractStageState.class); + + private ITransitionEventSink eventSink; + + private Stage stage; + + protected List actionDefinitions = new ArrayList(); + + protected List systemActionDefinitions = new ArrayList(); + + protected ApplicationContext context; + + protected ActiveInterviewService activeInterviewService; + + protected UserSessionService userSessionService; + + /** + * The reason the stage is in its current state (i.e., the action that caused the stage to transition to this state). + */ + private Action reason; + + public void setUserSessionService(UserSessionService userSessionService) { + this.userSessionService = userSessionService; + } + + public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { + this.activeInterviewService = activeInterviewService; + } + + public void setApplicationContext(ApplicationContext context) { + this.context = context; + } + + public void setStage(Stage stage) { + this.stage = stage; + } + + public Stage getStage() { + return stage; + } + + public void onTransition(IStageExecution execution, TransitionEvent event) { + Boolean var = areDependenciesCompleted(); + + if(var == null) { + if(wantTransitionEvent(TransitionEvent.INVALID)) castEvent(TransitionEvent.INVALID); + } else if(var == true && wantTransitionEvent(TransitionEvent.VALID)) castEvent(TransitionEvent.VALID); + else if(var == false && wantTransitionEvent(TransitionEvent.NOTAPPLICABLE)) castEvent(TransitionEvent.NOTAPPLICABLE); + } + + protected Boolean areDependenciesCompleted() { + if(stage.getStageDependencyCondition() != null) return stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService); + return true; + } + + public boolean removeAfterTransition() { + return false; + } + + protected void castEvent(TransitionEvent event) { + eventSink.castEvent(event); + } + + public void setEventSink(ITransitionEventSink eventSink) { + this.eventSink = eventSink; + } + + protected void addAction(ActionDefinition action) { + actionDefinitions.add(action); + } + + public List getActionDefinitions() { + return actionDefinitions; + } + + public ActionDefinition getActionDefinition(ActionType type) { + for(ActionDefinition def : actionDefinitions) { + if(def.getType().equals(type)) return def; + } + return null; + } + + public ActionDefinition getSystemActionDefinition(ActionType type) { + for(ActionDefinition def : systemActionDefinitions) { + if(def.getType().equals(type)) return def; + } + return null; + } + + protected void addSystemAction(ActionDefinition action) { + systemActionDefinitions.add(action); + } + + public List getSystemActionDefinitions() { + return systemActionDefinitions; + } + + public void execute(Action action) { + } + + public void interrupt(Action action) { + } + + public void skip(Action action) { + } + + public void stop(Action action) { + } + + public void complete(Action action) { + } + + public Component getWidget(String id) { + return null; + } + + public boolean isCompleted() { + return false; + } + + public boolean isFinal() { + return false; + } + + public boolean isInteractive() { + return false; + } + + public String getMessage() { + Locale locale = userSessionService.getLocale(); + return context.getMessage(getName(), null, locale); + } + + public Data getData(String key) { + return null; + } + + public void setReason(Action reason) { + this.reason = reason; + } + + public Action getReason() { + return reason; + } + + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + return true; + } + + public ActionType getStartingActionType() { + return null; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/IStageExecution.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/IStageExecution.java index 63a18161a..7d4cb0ac2 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/IStageExecution.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/IStageExecution.java @@ -1,148 +1,157 @@ -package org.obiba.onyx.engine.state; - -import java.util.List; - -import org.apache.wicket.Component; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.util.data.Data; - -/** - * State Machine interface, exposed by {@link StageExecutionContext}. - * - * @see State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf - * @author Yannick Marcon - * - */ -public interface IStageExecution { - - /** - * Get the name identifying this stage execution. - * @return - */ - public String getName(); - - /** - * Get the action definitions, exposed to user by Onyx. - * @return - */ - public List getActionDefinitions(); - - /** - * Get the action definition for the given type or null if not found. - * @param type - * @return - */ - public ActionDefinition getActionDefinition(ActionType type); - - /** - * Get the action definitions, not exposed to normal user interface. It may be used by module UI. - * @return - */ - public List getSystemActionDefinitions(); - - /** - * Get the system action definition for the given type or null if not found. - * @param type - * @return - */ - public ActionDefinition getSystemActionDefinition(ActionType type); - - /** - * Do execute. - * @see ActionType - * @param action - */ - public void execute(Action action); - - /** - * Do skip. - * @see ActionType - * @param action - */ - public void skip(Action action); - - /** - * Do stop. - * @see ActionType - * @param action - */ - public void stop(Action action); - - /** - * Do interrupt. - * @see ActionType - * @param action - */ - public void interrupt(Action action); - - /** - * Do complete. - * @see ActionType - * @param action - */ - public void complete(Action action); - - /** - * Get the {@link Component} to be displayed. - * @see #isInteractive() - * @param id - * @return - */ - public Component getWidget(String id); - - /** - * Says if {@link #getWidget(String)} will return a non null value. This decides if current state should be displayed - * in the stage page or the interview page. - * @return - */ - public boolean isInteractive(); - - /** - * Says if its a completed state, allowing stage dependencies resolution. - * @return - */ - public boolean isCompleted(); - - /** - * Says if it is a final state, ready for data export. - * @return - */ - public boolean isFinal(); - - /** - * Get a message indicating the current state information (may include reasons why the current state was reached). - * @return - */ - public String getMessage(); - - /** - * Get the {@link Data} corresponding to the given for stage execution dependency resolution. - * @param key - * @return the Data or null if not applicable - */ - public Data getData(String key); - - /** - * Sets the reason for the state (i.e., the action that caused the transition to the current state). - * - * @param reason the reason for the state - */ - public void setReason(Action reason); - - /** - * Returns the reason for the state (i.e., the action that caused the transition to the current state). - * - * @return the reason for the state - */ - public Action getReason(); - - /** - * Returns the starting action type for the state (i.e., the first action that caused the transition to the current - * state). - * - * @return the actionType for the state - */ - public ActionType getStartingActionType(); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +import java.util.List; + +import org.apache.wicket.Component; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.util.data.Data; + +/** + * State Machine interface, exposed by {@link StageExecutionContext}. + * + * @see State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf + * @author Yannick Marcon + * + */ +public interface IStageExecution { + + /** + * Get the name identifying this stage execution. + * @return + */ + public String getName(); + + /** + * Get the action definitions, exposed to user by Onyx. + * @return + */ + public List getActionDefinitions(); + + /** + * Get the action definition for the given type or null if not found. + * @param type + * @return + */ + public ActionDefinition getActionDefinition(ActionType type); + + /** + * Get the action definitions, not exposed to normal user interface. It may be used by module UI. + * @return + */ + public List getSystemActionDefinitions(); + + /** + * Get the system action definition for the given type or null if not found. + * @param type + * @return + */ + public ActionDefinition getSystemActionDefinition(ActionType type); + + /** + * Do execute. + * @see ActionType + * @param action + */ + public void execute(Action action); + + /** + * Do skip. + * @see ActionType + * @param action + */ + public void skip(Action action); + + /** + * Do stop. + * @see ActionType + * @param action + */ + public void stop(Action action); + + /** + * Do interrupt. + * @see ActionType + * @param action + */ + public void interrupt(Action action); + + /** + * Do complete. + * @see ActionType + * @param action + */ + public void complete(Action action); + + /** + * Get the {@link Component} to be displayed. + * @see #isInteractive() + * @param id + * @return + */ + public Component getWidget(String id); + + /** + * Says if {@link #getWidget(String)} will return a non null value. This decides if current state should be displayed + * in the stage page or the interview page. + * @return + */ + public boolean isInteractive(); + + /** + * Says if its a completed state, allowing stage dependencies resolution. + * @return + */ + public boolean isCompleted(); + + /** + * Says if it is a final state, ready for data export. + * @return + */ + public boolean isFinal(); + + /** + * Get a message indicating the current state information (may include reasons why the current state was reached). + * @return + */ + public String getMessage(); + + /** + * Get the {@link Data} corresponding to the given for stage execution dependency resolution. + * @param key + * @return the Data or null if not applicable + */ + public Data getData(String key); + + /** + * Sets the reason for the state (i.e., the action that caused the transition to the current state). + * + * @param reason the reason for the state + */ + public void setReason(Action reason); + + /** + * Returns the reason for the state (i.e., the action that caused the transition to the current state). + * + * @return the reason for the state + */ + public Action getReason(); + + /** + * Returns the starting action type for the state (i.e., the first action that caused the transition to the current + * state). + * + * @return the actionType for the state + */ + public ActionType getStartingActionType(); +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionEventSink.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionEventSink.java index e05325f36..b2297f918 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionEventSink.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionEventSink.java @@ -1,18 +1,27 @@ -package org.obiba.onyx.engine.state; - -/** - * Defines the operation of performing the state transition given the {@link TransitionEvent}. - * - * @see State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf - * @author Yannick Marcon - * - */ -public interface ITransitionEventSink { - - /** - * Perform the state transition. - * @param event - */ - public void castEvent(TransitionEvent event); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +/** + * Defines the operation of performing the state transition given the {@link TransitionEvent}. + * + * @see State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf + * @author Yannick Marcon + * + */ +public interface ITransitionEventSink { + + /** + * Perform the state transition. + * @param event + */ + public void castEvent(TransitionEvent event); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionListener.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionListener.java index 2d6a4bbeb..443c0838f 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionListener.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionListener.java @@ -1,23 +1,32 @@ -package org.obiba.onyx.engine.state; - -/** - * A {@link TransitionEvent} listener, would want to be informed about a state transition that has occured in - * {@link ITransitionSource}. - * @author Yannick Marcon - * - */ -public interface ITransitionListener { - - /** - * Called after a transition event has occured. - * @param execution - */ - public void onTransition(IStageExecution execution, TransitionEvent event); - - /** - * Listen to transitions until it asks the contrary. Checked after transition has occured. If false, listener is - * removed from listener list. - */ - public boolean removeAfterTransition(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +/** + * A {@link TransitionEvent} listener, would want to be informed about a state transition that has occured in + * {@link ITransitionSource}. + * @author Yannick Marcon + * + */ +public interface ITransitionListener { + + /** + * Called after a transition event has occured. + * @param execution + */ + public void onTransition(IStageExecution execution, TransitionEvent event); + + /** + * Listen to transitions until it asks the contrary. Checked after transition has occured. If false, listener is + * removed from listener list. + */ + public boolean removeAfterTransition(); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionSource.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionSource.java index f15cb45f7..94121f0ac 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionSource.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/ITransitionSource.java @@ -1,24 +1,33 @@ -package org.obiba.onyx.engine.state; - -/** - * A source of {@link TransitionEvent} can hold a list of {@link ITransitionListener} whishing to be informed about a - * state transition event. - * - * @author Yannick Marcon - * - */ -public interface ITransitionSource { - - /** - * Add a {@link ITransitionListener}. - * @param listener - */ - public void addTransitionListener(ITransitionListener listener); - - /** - * Remove the given {@link ITransitionListener}, if known (otherwise ignore it). - * @param listener - */ - public void removeTransitionListener(ITransitionListener listener); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +/** + * A source of {@link TransitionEvent} can hold a list of {@link ITransitionListener} whishing to be informed about a + * state transition event. + * + * @author Yannick Marcon + * + */ +public interface ITransitionSource { + + /** + * Add a {@link ITransitionListener}. + * @param listener + */ + public void addTransitionListener(ITransitionListener listener); + + /** + * Remove the given {@link ITransitionListener}, if known (otherwise ignore it). + * @param listener + */ + public void removeTransitionListener(ITransitionListener listener); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/StageExecutionContext.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/StageExecutionContext.java index 4057f8a9e..459209b0e 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/StageExecutionContext.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/StageExecutionContext.java @@ -1,267 +1,276 @@ -package org.obiba.onyx.engine.state; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.wicket.Component; -import org.obiba.core.domain.IEntity; -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.IMemento; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.stage.StageExecutionMemento; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.util.data.Data; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The stage execution context is the entry point of stage state machines. It holds the current state, and performs the - * {@link TransitionEvent} based state transitions. As a {@link ITransitionSource} it will inform the - * {@link ITransitionListener} about the transition event. All the method calls defined by {@link IStageExecution} will - * be forwarded to the {@link IStageExecution} holding the current state. - *

- * State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf - * @author Yannick Marcon - * - */ -public class StageExecutionContext extends PersistenceManagerAwareService implements IStageExecution, ITransitionEventSink, IMemento, ITransitionSource, ITransitionListener { - - private static final Logger log = LoggerFactory.getLogger(StageExecutionContext.class); - - private ModuleRegistry moduleRegistry; - - private Stage stage; - - private Interview interview; - - private IStageExecution currentState; - - private Map> edges = new HashMap>(); - - private List transitionListeners = new ArrayList(); - - public StageExecutionContext() { - } - - public StageExecutionContext(Interview interview, Stage stage) { - this.interview = interview; - this.stage = stage; - } - - public void setModuleRegistry(ModuleRegistry moduleRegistry) { - this.moduleRegistry = moduleRegistry; - } - - public void addTransitionListener(ITransitionListener listener) { - transitionListeners.add(listener); - } - - public void removeTransitionListener(ITransitionListener listener) { - transitionListeners.remove(listener); - } - - public void removeAllTransitionListener() { - transitionListeners.clear(); - } - - public void addEdge(AbstractStageState source, TransitionEvent event, AbstractStageState target) { - Map stateEdges = edges.get(source); - if(stateEdges == null) { - stateEdges = new HashMap(); - edges.put(source, stateEdges); - } - stateEdges.put(event, target); - source.setEventSink(this); - source.setStage(stage); - target.setEventSink(this); - target.setStage(stage); - } - - public void castEvent(TransitionEvent event) { - log.info("castEvent({}) from stage {} in state {}", new Object[] { event, stage.getName(), currentState.getClass().getSimpleName() }); - Map stateEdges = edges.get(currentState); - if(stateEdges != null) { - IStageExecution newState = stateEdges.get(event); - if(newState == null) { - log.error("Stage {} in state {} received event {} that has no edge to any other state. Either the state machine is missing edges (to determine what the new state should be) or the event should have never been received by the current state.", new Object[] { stage.getName(), currentState.getClass().getSimpleName(), event }); - throw new IllegalStateException("No destination state"); - } - currentState = newState; - // reinit the reason why transition event occured (there may be no action at all). - currentState.setReason(null); - List transitionListenersToRemove = new ArrayList(); - log.debug("transitionListeners.size=" + transitionListeners.size()); - for(ITransitionListener listener : transitionListeners) { - listener.onTransition(this, event); - if(listener.removeAfterTransition()) { - transitionListenersToRemove.add(listener); - } - } - for(ITransitionListener listener : transitionListenersToRemove) { - transitionListeners.remove(listener); - } - } - log.info("castEvent({}) from stage {} now in state {}", new Object[] { event, stage.getName(), currentState.getClass().getSimpleName() }); - - saveState(); - } - - private void saveState() { - StageExecutionMemento template = new StageExecutionMemento(); - template.setStage(stage.getName()); - template.setInterview(interview); - StageExecutionMemento memento = (StageExecutionMemento) saveToMemento(getPersistenceManager().matchOne(template)); - getPersistenceManager().save(memento); - } - - public List getActionDefinitions() { - return currentState.getActionDefinitions(); - } - - public List getSystemActionDefinitions() { - return currentState.getSystemActionDefinitions(); - } - - public ActionDefinition getActionDefinition(ActionType type) { - return currentState.getActionDefinition(type); - } - - public ActionDefinition getSystemActionDefinition(ActionType type) { - return currentState.getSystemActionDefinition(type); - } - - public void execute(Action action) { - currentState.execute(action); - } - - public void interrupt(Action action) { - currentState.interrupt(action); - } - - public void skip(Action action) { - currentState.skip(action); - } - - public void stop(Action action) { - currentState.stop(action); - } - - public void complete(Action action) { - currentState.complete(action); - } - - public Component getWidget(String id) { - return currentState.getWidget(id); - } - - public boolean isInteractive() { - return currentState.isInteractive(); - } - - public boolean isFinal() { - return currentState.isFinal(); - } - - public boolean isCompleted() { - return currentState.isCompleted(); - } - - public String getMessage() { - return currentState.getMessage(); - } - - public Data getData(String key) { - Data data = currentState.getData(key); - log.info(getName() + ":" + currentState.getName() + ".data." + key + "=" + data); - return data; - } - - public Stage getStage() { - return stage; - } - - public void setStage(Stage stage) { - this.stage = stage; - } - - public Interview getInterview() { - return interview; - } - - public void setInterview(Interview interview) { - this.interview = interview; - } - - public void setInitialState(IStageExecution stageState) { - this.currentState = stageState; - } - - public void onTransition(IStageExecution execution, TransitionEvent event) { - log.info("Stage {} in state {} receiving onTransition({}, {})", new Object[] { stage.getName(), currentState.getClass().getSimpleName(), execution.getName(), event }); - if(currentState instanceof ITransitionListener) { - ((ITransitionListener) currentState).onTransition(execution, event); - } - } - - public boolean removeAfterTransition() { - if(currentState instanceof ITransitionListener) { - return ((ITransitionListener) currentState).removeAfterTransition(); - } - return false; - } - - public String getName() { - // do not expose current state name - return stage.getModule() + ":" + stage.getName(); - } - - public void setReason(Action reason) { - currentState.setReason(reason); - // persist the action - saveState(); - } - - public Action getReason() { - return currentState.getReason(); - } - - public void restoreFromMemento(IEntity memento) { - if(memento instanceof StageExecutionMemento) { - StageExecutionMemento stageMemento = (StageExecutionMemento) memento; - this.interview = stageMemento.getInterview(); - this.stage = this.moduleRegistry.getStage(stageMemento.getStage()); - for(IStageExecution exec : edges.keySet()) { - if(exec.getClass().getSimpleName().equals(stageMemento.getState())) { - this.currentState = exec; - } - } - this.currentState.setReason(stageMemento.getAction()); - } - } - - public IEntity saveToMemento(IEntity memento) { - StageExecutionMemento myMemento = null; - if(memento == null) { - myMemento = new StageExecutionMemento(); - myMemento.setInterview(interview); - myMemento.setStage(stage.getName()); - } else if(memento instanceof StageExecutionMemento) myMemento = (StageExecutionMemento) memento; - else - throw new IllegalArgumentException("StageExecutionMemento is expected."); - - myMemento.setState(currentState.getClass().getSimpleName()); - myMemento.setAction(currentState.getReason()); - - return myMemento; - } - - public ActionType getStartingActionType() { - return currentState.getStartingActionType(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.wicket.Component; +import org.obiba.core.domain.IEntity; +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.IMemento; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.stage.StageExecutionMemento; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.util.data.Data; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The stage execution context is the entry point of stage state machines. It holds the current state, and performs the + * {@link TransitionEvent} based state transitions. As a {@link ITransitionSource} it will inform the + * {@link ITransitionListener} about the transition event. All the method calls defined by {@link IStageExecution} will + * be forwarded to the {@link IStageExecution} holding the current state. + *

+ * State Machine Design Pattern http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf + * @author Yannick Marcon + * + */ +public class StageExecutionContext extends PersistenceManagerAwareService implements IStageExecution, ITransitionEventSink, IMemento, ITransitionSource, ITransitionListener { + + private static final Logger log = LoggerFactory.getLogger(StageExecutionContext.class); + + private ModuleRegistry moduleRegistry; + + private Stage stage; + + private Interview interview; + + private IStageExecution currentState; + + private Map> edges = new HashMap>(); + + private List transitionListeners = new ArrayList(); + + public StageExecutionContext() { + } + + public StageExecutionContext(Interview interview, Stage stage) { + this.interview = interview; + this.stage = stage; + } + + public void setModuleRegistry(ModuleRegistry moduleRegistry) { + this.moduleRegistry = moduleRegistry; + } + + public void addTransitionListener(ITransitionListener listener) { + transitionListeners.add(listener); + } + + public void removeTransitionListener(ITransitionListener listener) { + transitionListeners.remove(listener); + } + + public void removeAllTransitionListener() { + transitionListeners.clear(); + } + + public void addEdge(AbstractStageState source, TransitionEvent event, AbstractStageState target) { + Map stateEdges = edges.get(source); + if(stateEdges == null) { + stateEdges = new HashMap(); + edges.put(source, stateEdges); + } + stateEdges.put(event, target); + source.setEventSink(this); + source.setStage(stage); + target.setEventSink(this); + target.setStage(stage); + } + + public void castEvent(TransitionEvent event) { + log.info("castEvent({}) from stage {} in state {}", new Object[] { event, stage.getName(), currentState.getClass().getSimpleName() }); + Map stateEdges = edges.get(currentState); + if(stateEdges != null) { + IStageExecution newState = stateEdges.get(event); + if(newState == null) { + log.error("Stage {} in state {} received event {} that has no edge to any other state. Either the state machine is missing edges (to determine what the new state should be) or the event should have never been received by the current state.", new Object[] { stage.getName(), currentState.getClass().getSimpleName(), event }); + throw new IllegalStateException("No destination state"); + } + currentState = newState; + // reinit the reason why transition event occured (there may be no action at all). + currentState.setReason(null); + List transitionListenersToRemove = new ArrayList(); + log.debug("transitionListeners.size=" + transitionListeners.size()); + for(ITransitionListener listener : transitionListeners) { + listener.onTransition(this, event); + if(listener.removeAfterTransition()) { + transitionListenersToRemove.add(listener); + } + } + for(ITransitionListener listener : transitionListenersToRemove) { + transitionListeners.remove(listener); + } + } + log.info("castEvent({}) from stage {} now in state {}", new Object[] { event, stage.getName(), currentState.getClass().getSimpleName() }); + + saveState(); + } + + private void saveState() { + StageExecutionMemento template = new StageExecutionMemento(); + template.setStage(stage.getName()); + template.setInterview(interview); + StageExecutionMemento memento = (StageExecutionMemento) saveToMemento(getPersistenceManager().matchOne(template)); + getPersistenceManager().save(memento); + } + + public List getActionDefinitions() { + return currentState.getActionDefinitions(); + } + + public List getSystemActionDefinitions() { + return currentState.getSystemActionDefinitions(); + } + + public ActionDefinition getActionDefinition(ActionType type) { + return currentState.getActionDefinition(type); + } + + public ActionDefinition getSystemActionDefinition(ActionType type) { + return currentState.getSystemActionDefinition(type); + } + + public void execute(Action action) { + currentState.execute(action); + } + + public void interrupt(Action action) { + currentState.interrupt(action); + } + + public void skip(Action action) { + currentState.skip(action); + } + + public void stop(Action action) { + currentState.stop(action); + } + + public void complete(Action action) { + currentState.complete(action); + } + + public Component getWidget(String id) { + return currentState.getWidget(id); + } + + public boolean isInteractive() { + return currentState.isInteractive(); + } + + public boolean isFinal() { + return currentState.isFinal(); + } + + public boolean isCompleted() { + return currentState.isCompleted(); + } + + public String getMessage() { + return currentState.getMessage(); + } + + public Data getData(String key) { + Data data = currentState.getData(key); + log.info(getName() + ":" + currentState.getName() + ".data." + key + "=" + data); + return data; + } + + public Stage getStage() { + return stage; + } + + public void setStage(Stage stage) { + this.stage = stage; + } + + public Interview getInterview() { + return interview; + } + + public void setInterview(Interview interview) { + this.interview = interview; + } + + public void setInitialState(IStageExecution stageState) { + this.currentState = stageState; + } + + public void onTransition(IStageExecution execution, TransitionEvent event) { + log.info("Stage {} in state {} receiving onTransition({}, {})", new Object[] { stage.getName(), currentState.getClass().getSimpleName(), execution.getName(), event }); + if(currentState instanceof ITransitionListener) { + ((ITransitionListener) currentState).onTransition(execution, event); + } + } + + public boolean removeAfterTransition() { + if(currentState instanceof ITransitionListener) { + return ((ITransitionListener) currentState).removeAfterTransition(); + } + return false; + } + + public String getName() { + // do not expose current state name + return stage.getModule() + ":" + stage.getName(); + } + + public void setReason(Action reason) { + currentState.setReason(reason); + // persist the action + saveState(); + } + + public Action getReason() { + return currentState.getReason(); + } + + public void restoreFromMemento(IEntity memento) { + if(memento instanceof StageExecutionMemento) { + StageExecutionMemento stageMemento = (StageExecutionMemento) memento; + this.interview = stageMemento.getInterview(); + this.stage = this.moduleRegistry.getStage(stageMemento.getStage()); + for(IStageExecution exec : edges.keySet()) { + if(exec.getClass().getSimpleName().equals(stageMemento.getState())) { + this.currentState = exec; + } + } + this.currentState.setReason(stageMemento.getAction()); + } + } + + public IEntity saveToMemento(IEntity memento) { + StageExecutionMemento myMemento = null; + if(memento == null) { + myMemento = new StageExecutionMemento(); + myMemento.setInterview(interview); + myMemento.setStage(stage.getName()); + } else if(memento instanceof StageExecutionMemento) myMemento = (StageExecutionMemento) memento; + else + throw new IllegalArgumentException("StageExecutionMemento is expected."); + + myMemento.setState(currentState.getClass().getSimpleName()); + myMemento.setAction(currentState.getReason()); + + return myMemento; + } + + public ActionType getStartingActionType() { + return currentState.getStartingActionType(); + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/engine/state/TransitionEvent.java b/onyx-core/src/main/java/org/obiba/onyx/engine/state/TransitionEvent.java index c009f64e1..b9c1688f7 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/engine/state/TransitionEvent.java +++ b/onyx-core/src/main/java/org/obiba/onyx/engine/state/TransitionEvent.java @@ -1,95 +1,104 @@ -package org.obiba.onyx.engine.state; - -/** - * Transition event is the way performing the transition from on state to another of the stage state machine. - * @author Yannick Marcon - * - */ -public class TransitionEvent implements Comparable { - - /** - * Successful validation event. - */ - public static final TransitionEvent VALID = new TransitionEvent("valid"); - - /** - * Failed validation event. - */ - public static final TransitionEvent INVALID = new TransitionEvent("invalid"); - - /** - * Default not applicable event. - */ - public static final TransitionEvent NOTAPPLICABLE = new TransitionEvent("notApplicable"); - - /** - * Default contra indicated event. - */ - public static final TransitionEvent CONTRAINDICATED = new TransitionEvent("contraIndicated"); - - /** - * Default start event (usually from the beginning to the in progress state). - */ - public static final TransitionEvent START = new TransitionEvent("start"); - - /** - * Default cancel event (usually goes to beginning state) - */ - public static final TransitionEvent CANCEL = new TransitionEvent("cancel"); - - /** - * Default complete event (usually from the in progress to the completed state). - */ - public static final TransitionEvent COMPLETE = new TransitionEvent("complete"); - - /** - * Default skip event (usually from the beginning to the skipped state). - */ - public static final TransitionEvent SKIP = new TransitionEvent("skip"); - - /** - * Default interrupt event (usually from the in progress to the interrupted state). - */ - public static final TransitionEvent INTERRUPT = new TransitionEvent("interrupt"); - - /** - * Default resume event (usually from the interrupted to the in progress state). - */ - public static final TransitionEvent RESUME = new TransitionEvent("resume"); - - /** - * The name of the event that will identify it. - */ - private String name; - - public TransitionEvent(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return name; - } - - public int compareTo(TransitionEvent o) { - return name.compareTo(o.name); - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof TransitionEvent) { - return name.equals(((TransitionEvent) obj).name); - } - return super.equals(obj); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine.state; + +/** + * Transition event is the way performing the transition from on state to another of the stage state machine. + * @author Yannick Marcon + * + */ +public class TransitionEvent implements Comparable { + + /** + * Successful validation event. + */ + public static final TransitionEvent VALID = new TransitionEvent("valid"); + + /** + * Failed validation event. + */ + public static final TransitionEvent INVALID = new TransitionEvent("invalid"); + + /** + * Default not applicable event. + */ + public static final TransitionEvent NOTAPPLICABLE = new TransitionEvent("notApplicable"); + + /** + * Default contra indicated event. + */ + public static final TransitionEvent CONTRAINDICATED = new TransitionEvent("contraIndicated"); + + /** + * Default start event (usually from the beginning to the in progress state). + */ + public static final TransitionEvent START = new TransitionEvent("start"); + + /** + * Default cancel event (usually goes to beginning state) + */ + public static final TransitionEvent CANCEL = new TransitionEvent("cancel"); + + /** + * Default complete event (usually from the in progress to the completed state). + */ + public static final TransitionEvent COMPLETE = new TransitionEvent("complete"); + + /** + * Default skip event (usually from the beginning to the skipped state). + */ + public static final TransitionEvent SKIP = new TransitionEvent("skip"); + + /** + * Default interrupt event (usually from the in progress to the interrupted state). + */ + public static final TransitionEvent INTERRUPT = new TransitionEvent("interrupt"); + + /** + * Default resume event (usually from the interrupted to the in progress state). + */ + public static final TransitionEvent RESUME = new TransitionEvent("resume"); + + /** + * The name of the event that will identify it. + */ + private String name; + + public TransitionEvent(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } + + public int compareTo(TransitionEvent o) { + return name.compareTo(o.name); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof TransitionEvent) { + return name.equals(((TransitionEvent) obj).name); + } + return super.equals(obj); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/spring/AnnotatedBeanFinderFactoryBean.java b/onyx-core/src/main/java/org/obiba/onyx/spring/AnnotatedBeanFinderFactoryBean.java index bb75cdd36..e432eba82 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/spring/AnnotatedBeanFinderFactoryBean.java +++ b/onyx-core/src/main/java/org/obiba/onyx/spring/AnnotatedBeanFinderFactoryBean.java @@ -1,406 +1,415 @@ -package org.obiba.onyx.spring; - -import java.lang.annotation.Annotation; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.FatalBeanException; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.context.ResourceLoaderAware; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.util.StringUtils; - -/** - *

This class is for automatic searching annotated classes (i.e. Hibernate entity classes with Entity - * annotation). It is mostly for use with Hibernate's SessionFactory in the Spring application context, - * but can be used to find classes that match any annotations. This code is based on William Mo's - * EntityBeanFinderFactoryBean. - *

- * - *

Example bean definition: - *

- * <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- *   <property name="dataSource">
- *     <ref bean="dataSource"/>
- *   </property>
- *   <property name="annotatedClasses">
- *     <bean class="org.obiba.onyx.spring.AnnotatedBeanFinderFactoryBean">
- *     <!-- Use Apache Ant Pattern -->
- *     <property name="searchPatterns">
- *       <set>
- *         <value>classpath*:org/obiba/**/*/*.class</value>
- *         <value>**/foo-core-*.jar</value>
- *       </set>
- *     </property>
- *
- *     <!-- Use Java regular expression to find all domain classes, default is .* -->
- *     <property name="qualifiedClassNamePatterns">
- *       <set>
- *         <value>^org\.obiba\..*\.domain\..*</value>
- *       </set>
- *     </property>
- *
- *     <!-- Specify annotations to look for in classes -->
- *     <property name="annotationClasses">
- *       <set>
- *         <value>javax.persistence.Entity</value>
- *         <value>javax.persistence.Embeddable</value>
- *         <value>javax.persistence.MappedSuperclass</value>
- *       </set>
- *     </property>
- *
- *       <value>test.package.Foo</value>
- *     </bean>
- *   </property>
- *   <property name="annotatedPackages">
- *     <list>
- *       <value>test.package</value>
- *     </list>
- *   </property>
- * </bean>
- * 
- *

- * - *

This class is for automatic searching annotated entity classes (i.e. classes with Entity annotation) - * for Hibernate's SessionFacotry in the Spring application context.

- * - * @author William Mo - * @version Original version downloaded, Jan 29, 2008 - * @see http://forum.springframework.org/showthread.php?t=46630 - * - * @author Oren E. Livne - * @version added supported for other Hibernate annotations, Jan 29, 2008 - */ -public class AnnotatedBeanFinderFactoryBean implements ResourceLoaderAware, FactoryBean { - - /** - * A logger that helps identify this class' printouts. - */ - private final Logger log = LoggerFactory.getLogger(getClass()); - - /** - * Resource resolver. - */ - private ResourcePatternResolver resolver; - - /** - * A collection of resource search patterns. - */ - private final Set searchPatterns = new HashSet(); - - /** - * A collection of qualified class name patterns to find in the selected resources. - */ - private final Set qualifiedClassNamePatterns = new HashSet(); - - /** - * List of annotation types to match in classes. - */ - private final Set> annotationClasses = new HashSet>(); - - /** - * The output set of annotated classes. - */ - private final Set> annotatedClasses = new HashSet>(); - - public AnnotatedBeanFinderFactoryBean() { - // default accepted class name pattern is all - qualifiedClassNamePatterns.add(".*"); - } - - /** - * Inject the resource loader. - * - * @param resourceLoader - * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader) - */ - public void setResourceLoader(ResourceLoader resourceLoader) { - resolver = (ResourcePatternResolver) resourceLoader; - } - - /** - * Return an instance (possibly shared or independent) of the object managed by this factory. - *

- * As with a BeanFactory, this allows support for both the Singleton and Prototype design pattern. - * - * @return instance of the object managed by this factory - * @throws Exception in case of creation errors - * @see org.springframework.beans.factory.FactoryBean#getObject() - */ - public Object getObject() throws Exception { - if(annotatedClasses.isEmpty()) { - searchAnnotatedEntityClasses(); - } - - return annotatedClasses; - } - - /** - * Return the type of product made by this factory. In this cases, a class. - * - * @return he type of object that this FactoryBean creates, in this case, a class - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ - public Class getObjectType() { - return annotatedClasses.getClass(); - } - - /** - * Indicates that this bean is a singleton. - * - * @return true - * @see org.springframework.beans.factory.FactoryBean#isSingleton() - */ - public boolean isSingleton() { - return true; - } - - /** - * The main method that searches for annotated classes in classpath resources. - */ - private void searchAnnotatedEntityClasses() { - // Search resources by every search pattern. - log.info("searchAnnotatedEntityClasses in " + searchPatterns); - for(String searchPattern : searchPatterns) { - try { - Resource[] resources = resolver.getResources(searchPattern); - - if(resources != null) { - // Parse every resource. - for(Resource res : resources) { - String path = res.getURL().getPath(); - // Path name string should not be empty. - if(!path.equals("")) { - if(path.endsWith(".class")) { - dealWithClasses(path); - } else if(path.endsWith(".jar")) { - dealWithJars(res); - } - } - } - } - } catch(Exception ignore) { - log.warn("Resource resolving failed", ignore); - } - } - if(log.isInfoEnabled()) { - log.info("Annotations to look for: " + annotationClasses); - log.info("Annotated classes found: " + annotatedClasses); - } - } - - /** - * @param path - */ - private void dealWithClasses(String path) { - Set qClassNames = listAllPossibleQualifiedClassNames(path); - - for(String qName : qClassNames) { - // Apply the qualified class name pattern to improve the searching - // performance. - if(matchQualifiedClassNamePatterns(qName)) { - addPossibleClasses(qName); - } - } - } - - /** - * @param qName - */ - private void addPossibleClasses(String qName) { - Class clazz; - try { - clazz = Class.forName(qName); - - // Add the class to the annotatedEntityClasses property. - if(checkEntityAnnotation(clazz)) { - annotatedClasses.add(clazz); - } - } catch(Exception ignore) { - } catch(NoClassDefFoundError ignore) { - } - } - - /** - * @param res - * @throws Exception - */ - private void dealWithJars(Resource res) throws Exception { - // Enumerate all entries in this JAR file. - Enumeration jarEntries = new JarFile(res.getFile()).entries(); - while(jarEntries.hasMoreElements()) { - String name = jarEntries.nextElement().getName(); - - // If the entry is a class, deal with it. - if(name.endsWith(".class") && !name.equals("")) { - // Format the path first. - name = pathToQualifiedClassName(name); - - // Apply the qualified class name pattern to improve the - // searching performance. - if(matchQualifiedClassNamePatterns(name)) - // This is the qualified class name, so add it. - addPossibleClasses(name); - } - } - } - - /** - * @param classPath - * @return - */ - private Set listAllPossibleQualifiedClassNames(String classPath) { - Set qualifiedClassNames = new HashSet(); - - // Format the path first. - String path = pathToQualifiedClassName(classPath); - - // Split the QName by the dot (i.e. '.') character. - String[] pathParts = path.split("\\."); - - // Add the path parts one by one from the end of the array to the - // beginning. - StringBuffer qName = new StringBuffer(); - for(int i = pathParts.length - 1; i >= 0; i--) { - qName.insert(0, pathParts[i]); - qualifiedClassNames.add(qName.toString()); - qName.insert(0, "."); - } - - return qualifiedClassNames; - } - - /** - * @param path - * @return - */ - private String pathToQualifiedClassName(String path) { - return path.replaceAll("/", ".").replaceAll("\\\\", ".").substring(0, path.length() - ".class".length()); - } - - /** - * Match a path against a set of qualified class name patterns. - * - * @param path path to match - * @return result of matching - */ - private boolean matchQualifiedClassNamePatterns(String path) { - for(String pattern : qualifiedClassNamePatterns) { - if(path.matches(pattern)) { - return true; - } - } - return false; - } - - /** - * Check whether the class implements at least one of the specified annotation types. - * - * @param clazz class to check - * @return true if and only if the class implements at least one of the specified annotation types - */ - private boolean checkEntityAnnotation(Class clazz) { - for(Class annotationClass : annotationClasses) { - if(clazz.getAnnotation(annotationClass) != null) { - if(log.isDebugEnabled()) { - log.debug("Found class " + clazz.getSimpleName() + " annotation @" + annotationClass.getSimpleName()); - } - return true; - } - } - return false; - } - - /** - * Clean and trim a string read from the context file. - * - * @param string string to clean - * @return cleaned string - */ - private String cleanString(String string) { - return StringUtils.trimAllWhitespace(string.replaceAll("[\t\n]", "")); - } - - /** - * Returns the set of resource search patterns. - * - * @return the set of resource search patterns - */ - public Set getSearchPatterns() { - return searchPatterns; - } - - /** - * Returns the the set of qualified class name patterns. - * - * @return the the set of qualified class name patterns - */ - public Set getQualifiedClassNamePatterns() { - return qualifiedClassNamePatterns; - } - - /** - * Returns the the set of annotation types. - * - * @return the the set of annotation types - */ - public Set> getAnnotationClasses() { - return annotationClasses; - } - - /** - * Inject the set of resource search patterns. - * - * @param searchPatterns the set of resource search patterns to set - */ - public void setSearchPatterns(Set searchPatterns) { - // Regular expression are sensitive with special characters. - for(String pattern : searchPatterns) { - this.searchPatterns.add(cleanString(pattern)); - } - } - - /** - * Inject the set of qualified class name patterns. - * - * @param qualifiedClassNamePatterns the set of qualified class name patterns to set - */ - public void setQualifiedClassNamePatterns(Set qualifiedClassNamePatterns) { - // Regular expression are sensitive with special characters. - // Clear default value - if(qualifiedClassNamePatterns.size() > 0) this.qualifiedClassNamePatterns.clear(); - for(String pattern : qualifiedClassNamePatterns) { - this.qualifiedClassNamePatterns.add(cleanString(pattern)); - } - } - - /** - * Injects the set of annotation types. - * - * @param annotationClasses the set of qualified annotation class names to set. - */ - @SuppressWarnings("unchecked") - public void setAnnotationClasses(Set annotationClasses) { - // Filter tabs and new lines - for(String annotationClass : annotationClasses) { - Class clazz; - try { - clazz = (Class) Class.forName(cleanString(annotationClass)); - this.annotationClasses.add(clazz); - } catch(NoClassDefFoundError ignore) { - throw new FatalBeanException("The class " + annotationClass + " in the annotatedClasses property of the sessionFactory declaration is not an annotation type."); - } catch(ClassCastException e) { - throw new FatalBeanException("Could not find annotation class " + annotationClass + " in the annotatedClasses property of the sessionFactory declaration."); - } catch(Throwable throwable) { - throw new FatalBeanException("Could not add annotation class " + annotationClass + " to the list of annotations in the annotatedClasses property of the sessionFactory declaration: " + throwable); - } - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.spring; + +import java.lang.annotation.Annotation; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.util.StringUtils; + +/** + *

This class is for automatic searching annotated classes (i.e. Hibernate entity classes with Entity + * annotation). It is mostly for use with Hibernate's SessionFactory in the Spring application context, + * but can be used to find classes that match any annotations. This code is based on William Mo's + * EntityBeanFinderFactoryBean. + *

+ * + *

Example bean definition: + *

+ * <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
+ *   <property name="dataSource">
+ *     <ref bean="dataSource"/>
+ *   </property>
+ *   <property name="annotatedClasses">
+ *     <bean class="org.obiba.onyx.spring.AnnotatedBeanFinderFactoryBean">
+ *     <!-- Use Apache Ant Pattern -->
+ *     <property name="searchPatterns">
+ *       <set>
+ *         <value>classpath*:org/obiba/**/*/*.class</value>
+ *         <value>**/foo-core-*.jar</value>
+ *       </set>
+ *     </property>
+ *
+ *     <!-- Use Java regular expression to find all domain classes, default is .* -->
+ *     <property name="qualifiedClassNamePatterns">
+ *       <set>
+ *         <value>^org\.obiba\..*\.domain\..*</value>
+ *       </set>
+ *     </property>
+ *
+ *     <!-- Specify annotations to look for in classes -->
+ *     <property name="annotationClasses">
+ *       <set>
+ *         <value>javax.persistence.Entity</value>
+ *         <value>javax.persistence.Embeddable</value>
+ *         <value>javax.persistence.MappedSuperclass</value>
+ *       </set>
+ *     </property>
+ *
+ *       <value>test.package.Foo</value>
+ *     </bean>
+ *   </property>
+ *   <property name="annotatedPackages">
+ *     <list>
+ *       <value>test.package</value>
+ *     </list>
+ *   </property>
+ * </bean>
+ * 
+ *

+ * + *

This class is for automatic searching annotated entity classes (i.e. classes with Entity annotation) + * for Hibernate's SessionFacotry in the Spring application context.

+ * + * @author William Mo + * @version Original version downloaded, Jan 29, 2008 + * @see http://forum.springframework.org/showthread.php?t=46630 + * + * @author Oren E. Livne + * @version added supported for other Hibernate annotations, Jan 29, 2008 + */ +public class AnnotatedBeanFinderFactoryBean implements ResourceLoaderAware, FactoryBean { + + /** + * A logger that helps identify this class' printouts. + */ + private final Logger log = LoggerFactory.getLogger(getClass()); + + /** + * Resource resolver. + */ + private ResourcePatternResolver resolver; + + /** + * A collection of resource search patterns. + */ + private final Set searchPatterns = new HashSet(); + + /** + * A collection of qualified class name patterns to find in the selected resources. + */ + private final Set qualifiedClassNamePatterns = new HashSet(); + + /** + * List of annotation types to match in classes. + */ + private final Set> annotationClasses = new HashSet>(); + + /** + * The output set of annotated classes. + */ + private final Set> annotatedClasses = new HashSet>(); + + public AnnotatedBeanFinderFactoryBean() { + // default accepted class name pattern is all + qualifiedClassNamePatterns.add(".*"); + } + + /** + * Inject the resource loader. + * + * @param resourceLoader + * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader) + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + resolver = (ResourcePatternResolver) resourceLoader; + } + + /** + * Return an instance (possibly shared or independent) of the object managed by this factory. + *

+ * As with a BeanFactory, this allows support for both the Singleton and Prototype design pattern. + * + * @return instance of the object managed by this factory + * @throws Exception in case of creation errors + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + public Object getObject() throws Exception { + if(annotatedClasses.isEmpty()) { + searchAnnotatedEntityClasses(); + } + + return annotatedClasses; + } + + /** + * Return the type of product made by this factory. In this cases, a class. + * + * @return he type of object that this FactoryBean creates, in this case, a class + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public Class getObjectType() { + return annotatedClasses.getClass(); + } + + /** + * Indicates that this bean is a singleton. + * + * @return true + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ + public boolean isSingleton() { + return true; + } + + /** + * The main method that searches for annotated classes in classpath resources. + */ + private void searchAnnotatedEntityClasses() { + // Search resources by every search pattern. + log.info("searchAnnotatedEntityClasses in " + searchPatterns); + for(String searchPattern : searchPatterns) { + try { + Resource[] resources = resolver.getResources(searchPattern); + + if(resources != null) { + // Parse every resource. + for(Resource res : resources) { + String path = res.getURL().getPath(); + // Path name string should not be empty. + if(!path.equals("")) { + if(path.endsWith(".class")) { + dealWithClasses(path); + } else if(path.endsWith(".jar")) { + dealWithJars(res); + } + } + } + } + } catch(Exception ignore) { + log.warn("Resource resolving failed", ignore); + } + } + if(log.isInfoEnabled()) { + log.info("Annotations to look for: " + annotationClasses); + log.info("Annotated classes found: " + annotatedClasses); + } + } + + /** + * @param path + */ + private void dealWithClasses(String path) { + Set qClassNames = listAllPossibleQualifiedClassNames(path); + + for(String qName : qClassNames) { + // Apply the qualified class name pattern to improve the searching + // performance. + if(matchQualifiedClassNamePatterns(qName)) { + addPossibleClasses(qName); + } + } + } + + /** + * @param qName + */ + private void addPossibleClasses(String qName) { + Class clazz; + try { + clazz = Class.forName(qName); + + // Add the class to the annotatedEntityClasses property. + if(checkEntityAnnotation(clazz)) { + annotatedClasses.add(clazz); + } + } catch(Exception ignore) { + } catch(NoClassDefFoundError ignore) { + } + } + + /** + * @param res + * @throws Exception + */ + private void dealWithJars(Resource res) throws Exception { + // Enumerate all entries in this JAR file. + Enumeration jarEntries = new JarFile(res.getFile()).entries(); + while(jarEntries.hasMoreElements()) { + String name = jarEntries.nextElement().getName(); + + // If the entry is a class, deal with it. + if(name.endsWith(".class") && !name.equals("")) { + // Format the path first. + name = pathToQualifiedClassName(name); + + // Apply the qualified class name pattern to improve the + // searching performance. + if(matchQualifiedClassNamePatterns(name)) + // This is the qualified class name, so add it. + addPossibleClasses(name); + } + } + } + + /** + * @param classPath + * @return + */ + private Set listAllPossibleQualifiedClassNames(String classPath) { + Set qualifiedClassNames = new HashSet(); + + // Format the path first. + String path = pathToQualifiedClassName(classPath); + + // Split the QName by the dot (i.e. '.') character. + String[] pathParts = path.split("\\."); + + // Add the path parts one by one from the end of the array to the + // beginning. + StringBuffer qName = new StringBuffer(); + for(int i = pathParts.length - 1; i >= 0; i--) { + qName.insert(0, pathParts[i]); + qualifiedClassNames.add(qName.toString()); + qName.insert(0, "."); + } + + return qualifiedClassNames; + } + + /** + * @param path + * @return + */ + private String pathToQualifiedClassName(String path) { + return path.replaceAll("/", ".").replaceAll("\\\\", ".").substring(0, path.length() - ".class".length()); + } + + /** + * Match a path against a set of qualified class name patterns. + * + * @param path path to match + * @return result of matching + */ + private boolean matchQualifiedClassNamePatterns(String path) { + for(String pattern : qualifiedClassNamePatterns) { + if(path.matches(pattern)) { + return true; + } + } + return false; + } + + /** + * Check whether the class implements at least one of the specified annotation types. + * + * @param clazz class to check + * @return true if and only if the class implements at least one of the specified annotation types + */ + private boolean checkEntityAnnotation(Class clazz) { + for(Class annotationClass : annotationClasses) { + if(clazz.getAnnotation(annotationClass) != null) { + if(log.isDebugEnabled()) { + log.debug("Found class " + clazz.getSimpleName() + " annotation @" + annotationClass.getSimpleName()); + } + return true; + } + } + return false; + } + + /** + * Clean and trim a string read from the context file. + * + * @param string string to clean + * @return cleaned string + */ + private String cleanString(String string) { + return StringUtils.trimAllWhitespace(string.replaceAll("[\t\n]", "")); + } + + /** + * Returns the set of resource search patterns. + * + * @return the set of resource search patterns + */ + public Set getSearchPatterns() { + return searchPatterns; + } + + /** + * Returns the the set of qualified class name patterns. + * + * @return the the set of qualified class name patterns + */ + public Set getQualifiedClassNamePatterns() { + return qualifiedClassNamePatterns; + } + + /** + * Returns the the set of annotation types. + * + * @return the the set of annotation types + */ + public Set> getAnnotationClasses() { + return annotationClasses; + } + + /** + * Inject the set of resource search patterns. + * + * @param searchPatterns the set of resource search patterns to set + */ + public void setSearchPatterns(Set searchPatterns) { + // Regular expression are sensitive with special characters. + for(String pattern : searchPatterns) { + this.searchPatterns.add(cleanString(pattern)); + } + } + + /** + * Inject the set of qualified class name patterns. + * + * @param qualifiedClassNamePatterns the set of qualified class name patterns to set + */ + public void setQualifiedClassNamePatterns(Set qualifiedClassNamePatterns) { + // Regular expression are sensitive with special characters. + // Clear default value + if(qualifiedClassNamePatterns.size() > 0) this.qualifiedClassNamePatterns.clear(); + for(String pattern : qualifiedClassNamePatterns) { + this.qualifiedClassNamePatterns.add(cleanString(pattern)); + } + } + + /** + * Injects the set of annotation types. + * + * @param annotationClasses the set of qualified annotation class names to set. + */ + @SuppressWarnings("unchecked") + public void setAnnotationClasses(Set annotationClasses) { + // Filter tabs and new lines + for(String annotationClass : annotationClasses) { + Class clazz; + try { + clazz = (Class) Class.forName(cleanString(annotationClass)); + this.annotationClasses.add(clazz); + } catch(NoClassDefFoundError ignore) { + throw new FatalBeanException("The class " + annotationClass + " in the annotatedClasses property of the sessionFactory declaration is not an annotation type."); + } catch(ClassCastException e) { + throw new FatalBeanException("Could not find annotation class " + annotationClass + " in the annotatedClasses property of the sessionFactory declaration."); + } catch(Throwable throwable) { + throw new FatalBeanException("Could not add annotation class " + annotationClass + " to the list of annotations in the annotatedClasses property of the sessionFactory declaration: " + throwable); + } + } + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/spring/remoting/CookieRequestExecutor.java b/onyx-core/src/main/java/org/obiba/onyx/spring/remoting/CookieRequestExecutor.java index a5c721c4f..b5bd64e4d 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/spring/remoting/CookieRequestExecutor.java +++ b/onyx-core/src/main/java/org/obiba/onyx/spring/remoting/CookieRequestExecutor.java @@ -1,35 +1,44 @@ -package org.obiba.onyx.spring.remoting; - -import java.io.IOException; - -import org.apache.commons.httpclient.methods.PostMethod; -import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; -import org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration; - -/** - * Request executer that adds credentials as cookies in the http request. - * @author Yannick Marcon - * - */ -public class CookieRequestExecutor extends CommonsHttpInvokerRequestExecutor { - - private String name; - - private String value; - - public void setName(String name) { - this.name = name; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - protected PostMethod createPostMethod(HttpInvokerClientConfiguration config) throws IOException { - PostMethod method = super.createPostMethod(config); - method.setRequestHeader("Cookie", name + "=" + value); - return method; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.spring.remoting; + +import java.io.IOException; + +import org.apache.commons.httpclient.methods.PostMethod; +import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; +import org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration; + +/** + * Request executer that adds credentials as cookies in the http request. + * @author Yannick Marcon + * + */ +public class CookieRequestExecutor extends CommonsHttpInvokerRequestExecutor { + + private String name; + + private String value; + + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + protected PostMethod createPostMethod(HttpInvokerClientConfiguration config) throws IOException { + PostMethod method = super.createPostMethod(config); + method.setRequestHeader("Cookie", name + "=" + value); + return method; + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/IEngineComponentAware.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/IEngineComponentAware.java index 58917f011..6687a8c8d 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/IEngineComponentAware.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/IEngineComponentAware.java @@ -1,25 +1,34 @@ -package org.obiba.onyx.wicket; - -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.obiba.onyx.wicket.action.ActionWindow; - -/** - * An interface to inject to stage module component some usefull tools. - * @author Yannick Marcon - * - */ -public interface IEngineComponentAware { - - /** - * Set the action window that can be used by the stage component to perform interactive actions. - * @param window - */ - public void setActionWindwon(ActionWindow window); - - /** - * The place to display feedback messages. - * @param feedback - */ - public void setFeedbackPanel(FeedbackPanel feedbackPanel); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket; + +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.obiba.onyx.wicket.action.ActionWindow; + +/** + * An interface to inject to stage module component some usefull tools. + * @author Yannick Marcon + * + */ +public interface IEngineComponentAware { + + /** + * Set the action window that can be used by the stage component to perform interactive actions. + * @param window + */ + public void setActionWindwon(ActionWindow window); + + /** + * The place to display feedback messages. + * @param feedback + */ + public void setFeedbackPanel(FeedbackPanel feedbackPanel); + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/StageModel.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/StageModel.java index 1e3d0df29..4f2c95e8f 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/StageModel.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/StageModel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -31,4 +40,4 @@ public StageModel(ModuleRegistry registry, String stageName) { protected Object load() { return this.moduleRegistry.getStage(stageName); } -} \ No newline at end of file +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionDefinitionPanel.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionDefinitionPanel.java index d75c222b2..2f46f62eb 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionDefinitionPanel.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionDefinitionPanel.java @@ -1,206 +1,215 @@ -package org.obiba.onyx.wicket.action; - -import java.io.Serializable; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxButton; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.PasswordTextField; -import org.apache.wicket.markup.html.form.TextArea; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.validation.IErrorMessageSource; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidationError; -import org.apache.wicket.validation.IValidator; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -public abstract class ActionDefinitionPanel extends Panel { - - private static final long serialVersionUID = -5173222062528691764L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ActionDefinitionPanel.class); - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean(name = "userSessionService") - private UserSessionService userSessionService; - - private boolean cancelled = true; - - private FeedbackPanel feedback; - - @SuppressWarnings("serial") - public ActionDefinitionPanel(String id, ActionDefinition definition) { - super(id); - - Action action = new Action(definition); - setModel(new Model(action)); - - add(new Label("description", definition.getDescription())); - - Form form = new Form("form"); - add(form); - - form.add(feedback = new FeedbackPanel("feedback")); - feedback.setOutputMarkupId(true); - - form.add(new Label("operator", activeInterviewService.getInterview().getUser().getFullName())); - - Participant participant = activeInterviewService.getParticipant(); - form.add(new Label("participantName", participant.getFullName())); - form.add(new Label("participantGender", new StringResourceModel("Gender." + participant.getGender(), this, null))); - form.add(new Label("participantBirthDate", DateModelUtils.getDateModel(new Model(participant.getBirthDate())))); - - if(definition.isAskPassword()) { - form.add(new PasswordFragment("password")); - } else { - form.add(new Fragment("password", "trFragment", this)); - } - - Participant participantTemplate = new Participant(); - TextField participantBarcode = new TextField("confirmBarcode", new PropertyModel(participantTemplate, "barcode")); - participantBarcode.setLabel(new StringResourceModel("ConfirmParticipantCode", this, null)); - participantBarcode.add(new IValidator() { - - public void validate(IValidatable validatable) { - if(!activeInterviewService.getParticipant().getBarcode().equals(validatable.getValue())) { - validatable.error(new ParticipantValidationError()); - } - } - - }); - form.add(participantBarcode.add(new RequiredFormFieldBehavior())); - - form.add(new TextArea("comment", new PropertyModel(this, "action.comment"))); - - action.setEventReason(definition.getDefaultReason()); - if(definition.getReasons().size() > 0) { - form.add(new ReasonsFragment("reasons", definition.getReasons())); - } else { - form.add(new Fragment("reasons", "trFragment", this)); - } - - form.add(new AjaxButton("submit", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - cancelled = false; - target.addComponent(feedback); - ActionDefinitionPanel.this.onClick(target); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - cancelled = false; - target.addComponent(feedback); - } - - }); - - form.add(new AjaxLink("cancel") { - - @Override - public void onClick(AjaxRequestTarget target) { - cancelled = true; - target.addComponent(feedback); - ActionDefinitionPanel.this.onClick(target); - } - - }); - } - - public Action getAction() { - return (Action) getModelObject(); - } - - public boolean isCancelled() { - return cancelled; - } - - /** - * Called after submit or cancel button are clicked. - * @param target - */ - public abstract void onClick(AjaxRequestTarget target); - - @SuppressWarnings("serial") - private class ParticipantValidationError implements IValidationError, Serializable { - - public String getErrorMessage(IErrorMessageSource messageSource) { - return ActionDefinitionPanel.this.getString("NotTheInterviewParticipant"); - } - - } - - @SuppressWarnings("serial") - private class UserValidationError implements IValidationError, Serializable { - - public String getErrorMessage(IErrorMessageSource messageSource) { - return ActionDefinitionPanel.this.getString("WrongOperatorPassword", null, "Wrong Operator Password"); - } - - } - - @SuppressWarnings("serial") - private class ReasonsFragment extends Fragment { - - public ReasonsFragment(String id, List reasons) { - super(id, "reasonsFragment", ActionDefinitionPanel.this); - add(new DropDownChoice("reasonsSelect", new PropertyModel(ActionDefinitionPanel.this, "action.eventReason"), reasons, new IChoiceRenderer() { - public Object getDisplayValue(Object object) { - ApplicationContext context = ((SpringWebApplication)(ActionDefinitionPanel.this.getApplication())).getSpringContextLocator().getSpringContext(); - return context.getMessage(object.toString(), null, userSessionService.getLocale()); - } - - public String getIdValue(Object object, int index) { - return object.toString(); - } - })); - } - - } - - @SuppressWarnings("serial") - private class PasswordFragment extends Fragment { - - public PasswordFragment(String id) { - super(id, "passwordFragment", ActionDefinitionPanel.this); - final User operatorTemplate = new User(); - PasswordTextField pwdTextField = new PasswordTextField("password", new PropertyModel(operatorTemplate, "password")); - add(pwdTextField.add(new RequiredFormFieldBehavior())); - pwdTextField.add(new IValidator() { - - public void validate(IValidatable validatable) { - if (!User.digest((String)validatable.getValue()).equals(activeInterviewService.getInterview().getUser().getPassword())) { - validatable.error(new UserValidationError()); - } - } - }); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.action; + +import java.io.Serializable; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.PasswordTextField; +import org.apache.wicket.markup.html.form.TextArea; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.IErrorMessageSource; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidationError; +import org.apache.wicket.validation.IValidator; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; + +public abstract class ActionDefinitionPanel extends Panel { + + private static final long serialVersionUID = -5173222062528691764L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ActionDefinitionPanel.class); + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean(name = "userSessionService") + private UserSessionService userSessionService; + + private boolean cancelled = true; + + private FeedbackPanel feedback; + + @SuppressWarnings("serial") + public ActionDefinitionPanel(String id, ActionDefinition definition) { + super(id); + + Action action = new Action(definition); + setModel(new Model(action)); + + add(new Label("description", definition.getDescription())); + + Form form = new Form("form"); + add(form); + + form.add(feedback = new FeedbackPanel("feedback")); + feedback.setOutputMarkupId(true); + + form.add(new Label("operator", activeInterviewService.getInterview().getUser().getFullName())); + + Participant participant = activeInterviewService.getParticipant(); + form.add(new Label("participantName", participant.getFullName())); + form.add(new Label("participantGender", new StringResourceModel("Gender." + participant.getGender(), this, null))); + form.add(new Label("participantBirthDate", DateModelUtils.getDateModel(new Model(participant.getBirthDate())))); + + if(definition.isAskPassword()) { + form.add(new PasswordFragment("password")); + } else { + form.add(new Fragment("password", "trFragment", this)); + } + + Participant participantTemplate = new Participant(); + TextField participantBarcode = new TextField("confirmBarcode", new PropertyModel(participantTemplate, "barcode")); + participantBarcode.setLabel(new StringResourceModel("ConfirmParticipantCode", this, null)); + participantBarcode.add(new IValidator() { + + public void validate(IValidatable validatable) { + if(!activeInterviewService.getParticipant().getBarcode().equals(validatable.getValue())) { + validatable.error(new ParticipantValidationError()); + } + } + + }); + form.add(participantBarcode.add(new RequiredFormFieldBehavior())); + + form.add(new TextArea("comment", new PropertyModel(this, "action.comment"))); + + action.setEventReason(definition.getDefaultReason()); + if(definition.getReasons().size() > 0) { + form.add(new ReasonsFragment("reasons", definition.getReasons())); + } else { + form.add(new Fragment("reasons", "trFragment", this)); + } + + form.add(new AjaxButton("submit", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + cancelled = false; + target.addComponent(feedback); + ActionDefinitionPanel.this.onClick(target); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + cancelled = false; + target.addComponent(feedback); + } + + }); + + form.add(new AjaxLink("cancel") { + + @Override + public void onClick(AjaxRequestTarget target) { + cancelled = true; + target.addComponent(feedback); + ActionDefinitionPanel.this.onClick(target); + } + + }); + } + + public Action getAction() { + return (Action) getModelObject(); + } + + public boolean isCancelled() { + return cancelled; + } + + /** + * Called after submit or cancel button are clicked. + * @param target + */ + public abstract void onClick(AjaxRequestTarget target); + + @SuppressWarnings("serial") + private class ParticipantValidationError implements IValidationError, Serializable { + + public String getErrorMessage(IErrorMessageSource messageSource) { + return ActionDefinitionPanel.this.getString("NotTheInterviewParticipant"); + } + + } + + @SuppressWarnings("serial") + private class UserValidationError implements IValidationError, Serializable { + + public String getErrorMessage(IErrorMessageSource messageSource) { + return ActionDefinitionPanel.this.getString("WrongOperatorPassword", null, "Wrong Operator Password"); + } + + } + + @SuppressWarnings("serial") + private class ReasonsFragment extends Fragment { + + public ReasonsFragment(String id, List reasons) { + super(id, "reasonsFragment", ActionDefinitionPanel.this); + add(new DropDownChoice("reasonsSelect", new PropertyModel(ActionDefinitionPanel.this, "action.eventReason"), reasons, new IChoiceRenderer() { + public Object getDisplayValue(Object object) { + ApplicationContext context = ((SpringWebApplication)(ActionDefinitionPanel.this.getApplication())).getSpringContextLocator().getSpringContext(); + return context.getMessage(object.toString(), null, userSessionService.getLocale()); + } + + public String getIdValue(Object object, int index) { + return object.toString(); + } + })); + } + + } + + @SuppressWarnings("serial") + private class PasswordFragment extends Fragment { + + public PasswordFragment(String id) { + super(id, "passwordFragment", ActionDefinitionPanel.this); + final User operatorTemplate = new User(); + PasswordTextField pwdTextField = new PasswordTextField("password", new PropertyModel(operatorTemplate, "password")); + add(pwdTextField.add(new RequiredFormFieldBehavior())); + pwdTextField.add(new IValidator() { + + public void validate(IValidatable validatable) { + if (!User.digest((String)validatable.getValue()).equals(activeInterviewService.getInterview().getUser().getPassword())) { + validatable.error(new UserValidationError()); + } + } + }); + } + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionWindow.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionWindow.java index 2a25378a6..da3c3ca8f 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionWindow.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/action/ActionWindow.java @@ -1,106 +1,115 @@ -package org.obiba.onyx.wicket.action; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.Stage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class ActionWindow extends Panel { - - private static final long serialVersionUID = -3711214735708110972L; - - private static final Logger log = LoggerFactory.getLogger(ActionWindow.class); - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean(name="userSessionService") - private UserSessionService userSessionService; - - private ModalWindow modal; - - private IModel stageModel; - - @SuppressWarnings("serial") - public ActionWindow(String id) { - super(id); - - add(modal = new ModalWindow("modal")); - modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { - public boolean onCloseButtonClicked(AjaxRequestTarget target) { - // same as cancel - return true; - } - }); - - modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - public void onClose(AjaxRequestTarget target) { - ActionDefinitionPanel pane = (ActionDefinitionPanel) modal.get(modal.getContentId()); - if(!pane.isCancelled()) { - Action action = pane.getAction(); - log.info("action=" + action); - Stage stage = null; - if(stageModel != null) { - stage = (Stage) stageModel.getObject(); - } - activeInterviewService.doAction(stage, action, activeInterviewService.getInterview().getUser()); - onActionPerformed(target, stage, action); - } - } - }); - - } - - /** - * On action performed. - * @param target - */ - public abstract void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action); - - public void close(AjaxRequestTarget target) { - modal.close(target); - } - - public void setTitle(String title) { - modal.setTitle(title); - } - - public void setTitle(IModel title) { - modal.setTitle(title); - } - - @SuppressWarnings("serial") - public void show(AjaxRequestTarget target, IModel stageModel, ActionDefinition actionDefinition) { - this.stageModel = stageModel; - modal.setContent(new ActionDefinitionPanel(modal.getContentId(), actionDefinition) { - - @Override - public void onClick(AjaxRequestTarget target) { - modal.close(target); - } - - }); - if(stageModel != null && stageModel.getObject() != null) { - // Inject the Spring application context and the user session service - // into the stage. NOTE: These are dependencies of Stage.getDescription(). - Stage stage = (Stage)stageModel.getObject(); - stage.setApplicationContext(((SpringWebApplication)getApplication()).getSpringContextLocator().getSpringContext()); - stage.setUserSessionService(userSessionService); - - modal.setTitle(((Stage) stageModel.getObject()).getDescription() + ": " + getString(actionDefinition.getLabel(), null, actionDefinition.getLabel())); - } - else - modal.setTitle(getString(actionDefinition.getLabel(), null, actionDefinition.getLabel())); - modal.show(target); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.action; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.Stage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class ActionWindow extends Panel { + + private static final long serialVersionUID = -3711214735708110972L; + + private static final Logger log = LoggerFactory.getLogger(ActionWindow.class); + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean(name="userSessionService") + private UserSessionService userSessionService; + + private ModalWindow modal; + + private IModel stageModel; + + @SuppressWarnings("serial") + public ActionWindow(String id) { + super(id); + + add(modal = new ModalWindow("modal")); + modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { + public boolean onCloseButtonClicked(AjaxRequestTarget target) { + // same as cancel + return true; + } + }); + + modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { + public void onClose(AjaxRequestTarget target) { + ActionDefinitionPanel pane = (ActionDefinitionPanel) modal.get(modal.getContentId()); + if(!pane.isCancelled()) { + Action action = pane.getAction(); + log.info("action=" + action); + Stage stage = null; + if(stageModel != null) { + stage = (Stage) stageModel.getObject(); + } + activeInterviewService.doAction(stage, action, activeInterviewService.getInterview().getUser()); + onActionPerformed(target, stage, action); + } + } + }); + + } + + /** + * On action performed. + * @param target + */ + public abstract void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action); + + public void close(AjaxRequestTarget target) { + modal.close(target); + } + + public void setTitle(String title) { + modal.setTitle(title); + } + + public void setTitle(IModel title) { + modal.setTitle(title); + } + + @SuppressWarnings("serial") + public void show(AjaxRequestTarget target, IModel stageModel, ActionDefinition actionDefinition) { + this.stageModel = stageModel; + modal.setContent(new ActionDefinitionPanel(modal.getContentId(), actionDefinition) { + + @Override + public void onClick(AjaxRequestTarget target) { + modal.close(target); + } + + }); + if(stageModel != null && stageModel.getObject() != null) { + // Inject the Spring application context and the user session service + // into the stage. NOTE: These are dependencies of Stage.getDescription(). + Stage stage = (Stage)stageModel.getObject(); + stage.setApplicationContext(((SpringWebApplication)getApplication()).getSpringContextLocator().getSpringContext()); + stage.setUserSessionService(userSessionService); + + modal.setTitle(((Stage) stageModel.getObject()).getDescription() + ": " + getString(actionDefinition.getLabel(), null, actionDefinition.getLabel())); + } + else + modal.setTitle(getString(actionDefinition.getLabel(), null, actionDefinition.getLabel())); + modal.show(target); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/behavior/RequiredFormFieldBehavior.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/behavior/RequiredFormFieldBehavior.java index 2cd171802..6acaf0b01 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/behavior/RequiredFormFieldBehavior.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/behavior/RequiredFormFieldBehavior.java @@ -1,23 +1,32 @@ -package org.obiba.onyx.wicket.behavior; - -import org.apache.wicket.Component; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.markup.html.form.FormComponent; -import org.apache.wicket.model.Model; - -public class RequiredFormFieldBehavior extends AttributeAppender { - - private static final long serialVersionUID = -547194106510259211L; - - public RequiredFormFieldBehavior() { - super("class", new Model("required"), " "); - } - - @Override - public void bind(Component component) { - FormComponent formComp = (FormComponent) component; - formComp.setRequired(true); - super.bind(component); - } - -}; +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.behavior; + +import org.apache.wicket.Component; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.model.Model; + +public class RequiredFormFieldBehavior extends AttributeAppender { + + private static final long serialVersionUID = -547194106510259211L; + + public RequiredFormFieldBehavior() { + super("class", new Model("required"), " "); + } + + @Override + public void bind(Component component) { + FormComponent formComp = (FormComponent) component; + formComp.setRequired(true); + super.bind(component); + } + +}; diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataConverter.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataConverter.java index 1b8a26e45..825fb4701 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataConverter.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataConverter.java @@ -1,74 +1,83 @@ -package org.obiba.onyx.wicket.data; - -import java.io.Serializable; -import java.util.Locale; - -import org.apache.wicket.util.convert.ConversionException; -import org.apache.wicket.util.convert.IConverter; -import org.apache.wicket.util.convert.converters.DateConverter; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DataConverter implements IConverter { - - private static final long serialVersionUID = 3639500916194340039L; - - private static final Logger log = LoggerFactory.getLogger(DataConverter.class); - - private DataType type; - - public DataConverter(DataType type) { - this.type = type; - } - - public Object convertToObject(String value, Locale locale) { - - Data data = null; - - try { - switch(type) { - case BOOLEAN: - data = new Data(type, Boolean.valueOf(value)); - break; - - case DATE: - DateConverter dateConverter = new DateConverter(); - data = new Data(type, (Serializable)dateConverter.convertToObject(value, locale)); - break; - - case DECIMAL: - data = new Data(type, Double.valueOf(value)); - break; - - case INTEGER: - data = new Data(type, Long.valueOf(value)); - break; - - case TEXT: - data = new Data(type, value); - break; - - case DATA: - // TODO - break; - - default: - break; - } - } catch (Exception ex) { - log.warn(ex.getMessage()); - ConversionException cex = new ConversionException(ex.getMessage()); - throw cex; - } - return data; - } - - public String convertToString(Object value, Locale locale) { - Data data = (Data) value; - if(data == null || data.getValue() == null) return null; - return data.getValueAsString(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.data; + +import java.io.Serializable; +import java.util.Locale; + +import org.apache.wicket.util.convert.ConversionException; +import org.apache.wicket.util.convert.IConverter; +import org.apache.wicket.util.convert.converters.DateConverter; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DataConverter implements IConverter { + + private static final long serialVersionUID = 3639500916194340039L; + + private static final Logger log = LoggerFactory.getLogger(DataConverter.class); + + private DataType type; + + public DataConverter(DataType type) { + this.type = type; + } + + public Object convertToObject(String value, Locale locale) { + + Data data = null; + + try { + switch(type) { + case BOOLEAN: + data = new Data(type, Boolean.valueOf(value)); + break; + + case DATE: + DateConverter dateConverter = new DateConverter(); + data = new Data(type, (Serializable)dateConverter.convertToObject(value, locale)); + break; + + case DECIMAL: + data = new Data(type, Double.valueOf(value)); + break; + + case INTEGER: + data = new Data(type, Long.valueOf(value)); + break; + + case TEXT: + data = new Data(type, value); + break; + + case DATA: + // TODO + break; + + default: + break; + } + } catch (Exception ex) { + log.warn(ex.getMessage()); + ConversionException cex = new ConversionException(ex.getMessage()); + throw cex; + } + return data; + } + + public String convertToString(Object value, Locale locale) { + Data data = (Data) value; + if(data == null || data.getValue() == null) return null; + return data.getValueAsString(); + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataField.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataField.java index 94c9863a9..27d367b87 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataField.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/data/DataField.java @@ -1,279 +1,288 @@ -package org.obiba.onyx.wicket.data; - -import java.util.List; - -import org.apache.wicket.AttributeModifier; -import org.apache.wicket.Component; -import org.apache.wicket.MarkupContainer; -import org.apache.wicket.behavior.IBehavior; -import org.apache.wicket.extensions.markup.html.form.DateTextField; -import org.apache.wicket.extensions.yui.calendar.DatePicker; -import org.apache.wicket.feedback.FeedbackMessage; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.CheckBox; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.FormComponent; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.util.convert.IConverter; -import org.apache.wicket.validation.IValidator; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; - -/** - * Data field is the component representation of {@link Data}. - * @see DataConverter - * @author Yannick Marcon - * - */ -public class DataField extends Panel { - - private static final long serialVersionUID = 4522983933046975818L; - - private FieldFragment input; - - public DataField(String id, IModel model, final DataType dataType) { - this(id, model, dataType, ""); - } - - /** - * Constructor. - * @param id - * @param model value set is of type {@link Data} - * @param dataType - * @param unit the representation of the unit for the value - */ - public DataField(String id, IModel model, final DataType dataType, String unit) { - super(id, model); - - input = new InputFragment("input", model, dataType); - add(input); - - addUnitLabel(unit); - } - - /** - * Select field from given choices. - * @param id - * @param model - * @param dataType - * @param choices - * @param unit - */ - public DataField(String id, IModel model, final DataType dataType, IModel choices, String unit) { - this(id, model, dataType, choices, null, unit); - } - - /** - * Select field from given choices. - * @param id - * @param model - * @param dataType - * @param choices - * @param renderer - * @param unit - */ - public DataField(String id, IModel model, final DataType dataType, IModel choices, IChoiceRenderer renderer, String unit) { - super(id); - - input = new SelectFragment("input", model, dataType, choices, renderer); - add(input); - - addUnitLabel(unit); - } - - /** - * Select field from given choices. - * @param id - * @param model - * @param dataType - * @param choices - * @param unit - */ - @SuppressWarnings("unchecked") - public DataField(String id, IModel model, final DataType dataType, List choices, String unit) { - this(id, model, dataType, choices, null, unit); - } - - /** - * Select field from given choices. - * @param id - * @param model - * @param dataType - * @param choices - * @param renderer - * @param unit - */ - @SuppressWarnings("unchecked") - public DataField(String id, IModel model, final DataType dataType, List choices, IChoiceRenderer renderer, String unit) { - super(id); - - input = new SelectFragment("input", model, dataType, choices, renderer); - add(input); - - addUnitLabel(unit); - } - - private void addUnitLabel(String unit) { - add(new Label("unit", (unit == null ? "" : unit))); - } - - /** - * Set the model that identifies the underlying field in error messages. - * @param labelModel - */ - public void setLabel(IModel labelModel) { - input.getField().setLabel(labelModel); - } - - public void setFieldEnabled(boolean enabled) { - input.getField().setEnabled(enabled); - } - - - /** - * Add a behavior to underlying field. - * @return this for chaining - */ - @Override - public Component add(IBehavior behavior) { - input.getField().add(behavior); - return this; - } - - /** - * Add a validator to the underlying field. - * - * @param validator the validator - * @return this for chaining - */ - public Component add(IValidator validator) { - input.getField().add(validator); - return this; - } - - /** - * Set the underlying input field as required. - * @param required - * @return this for chaining - */ - public Component setRequired(boolean required) { - input.getField().setRequired(required); - return this; - } - - /** - * Get the underlying field feeback message. - * @return - */ - public FeedbackMessage getFieldFeedbackMessage() { - return input.getField().getFeedbackMessage(); - } - - private abstract class FieldFragment extends Fragment { - - protected FormComponent field = null; - - public FieldFragment(String id, String markupId, MarkupContainer markupProvider) { - super(id, markupId, markupProvider); - - } - - public FormComponent getField() { - return field; - } - } - - private class InputFragment extends FieldFragment { - - private static final long serialVersionUID = 7003783791888047073L; - - @SuppressWarnings("serial") - public InputFragment(String id, IModel model, final DataType dataType) { - super(id, "inputFragment", DataField.this); - - switch(dataType) { - case TEXT: - case DATA: - field = new TextField("field", model, String.class) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new DataConverter(dataType); - } - }; - break; - case BOOLEAN: - field = new CheckBox("field", model) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new DataConverter(dataType); - } - }; - field.add(new AttributeModifier("type", new Model("checkbox"))); - break; - case DATE: - field = new DateTextField("field", model) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new DataConverter(dataType); - } - }; - field.add(new DatePicker()); - break; - case INTEGER: - field = new TextField("field", model, Long.class) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new DataConverter(dataType); - } - }; - break; - case DECIMAL: - field = new TextField("field", model, Double.class) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new DataConverter(dataType); - } - }; - break; - } - add(field); - } - } - - private class SelectFragment extends FieldFragment { - - private static final long serialVersionUID = -6926320986227794949L; - - @SuppressWarnings("unchecked") - public SelectFragment(String id, IModel model, final DataType dataType, List choices, IChoiceRenderer renderer) { - super(id, "selectFragment", DataField.this); - - if (renderer == null) - field = new DropDownChoice("select", model, choices); - else - field = new DropDownChoice("select", model, choices, renderer); - - add(field); - } - - public SelectFragment(String id, IModel model, final DataType dataType, IModel choices, IChoiceRenderer renderer) { - super(id, "selectFragment", DataField.this); - - if (renderer == null) - field = new DropDownChoice("select", model, choices); - else - field = new DropDownChoice("select", model, choices, renderer); - add(field); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.data; + +import java.util.List; + +import org.apache.wicket.AttributeModifier; +import org.apache.wicket.Component; +import org.apache.wicket.MarkupContainer; +import org.apache.wicket.behavior.IBehavior; +import org.apache.wicket.extensions.markup.html.form.DateTextField; +import org.apache.wicket.extensions.yui.calendar.DatePicker; +import org.apache.wicket.feedback.FeedbackMessage; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.CheckBox; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.util.convert.IConverter; +import org.apache.wicket.validation.IValidator; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; + +/** + * Data field is the component representation of {@link Data}. + * @see DataConverter + * @author Yannick Marcon + * + */ +public class DataField extends Panel { + + private static final long serialVersionUID = 4522983933046975818L; + + private FieldFragment input; + + public DataField(String id, IModel model, final DataType dataType) { + this(id, model, dataType, ""); + } + + /** + * Constructor. + * @param id + * @param model value set is of type {@link Data} + * @param dataType + * @param unit the representation of the unit for the value + */ + public DataField(String id, IModel model, final DataType dataType, String unit) { + super(id, model); + + input = new InputFragment("input", model, dataType); + add(input); + + addUnitLabel(unit); + } + + /** + * Select field from given choices. + * @param id + * @param model + * @param dataType + * @param choices + * @param unit + */ + public DataField(String id, IModel model, final DataType dataType, IModel choices, String unit) { + this(id, model, dataType, choices, null, unit); + } + + /** + * Select field from given choices. + * @param id + * @param model + * @param dataType + * @param choices + * @param renderer + * @param unit + */ + public DataField(String id, IModel model, final DataType dataType, IModel choices, IChoiceRenderer renderer, String unit) { + super(id); + + input = new SelectFragment("input", model, dataType, choices, renderer); + add(input); + + addUnitLabel(unit); + } + + /** + * Select field from given choices. + * @param id + * @param model + * @param dataType + * @param choices + * @param unit + */ + @SuppressWarnings("unchecked") + public DataField(String id, IModel model, final DataType dataType, List choices, String unit) { + this(id, model, dataType, choices, null, unit); + } + + /** + * Select field from given choices. + * @param id + * @param model + * @param dataType + * @param choices + * @param renderer + * @param unit + */ + @SuppressWarnings("unchecked") + public DataField(String id, IModel model, final DataType dataType, List choices, IChoiceRenderer renderer, String unit) { + super(id); + + input = new SelectFragment("input", model, dataType, choices, renderer); + add(input); + + addUnitLabel(unit); + } + + private void addUnitLabel(String unit) { + add(new Label("unit", (unit == null ? "" : unit))); + } + + /** + * Set the model that identifies the underlying field in error messages. + * @param labelModel + */ + public void setLabel(IModel labelModel) { + input.getField().setLabel(labelModel); + } + + public void setFieldEnabled(boolean enabled) { + input.getField().setEnabled(enabled); + } + + + /** + * Add a behavior to underlying field. + * @return this for chaining + */ + @Override + public Component add(IBehavior behavior) { + input.getField().add(behavior); + return this; + } + + /** + * Add a validator to the underlying field. + * + * @param validator the validator + * @return this for chaining + */ + public Component add(IValidator validator) { + input.getField().add(validator); + return this; + } + + /** + * Set the underlying input field as required. + * @param required + * @return this for chaining + */ + public Component setRequired(boolean required) { + input.getField().setRequired(required); + return this; + } + + /** + * Get the underlying field feeback message. + * @return + */ + public FeedbackMessage getFieldFeedbackMessage() { + return input.getField().getFeedbackMessage(); + } + + private abstract class FieldFragment extends Fragment { + + protected FormComponent field = null; + + public FieldFragment(String id, String markupId, MarkupContainer markupProvider) { + super(id, markupId, markupProvider); + + } + + public FormComponent getField() { + return field; + } + } + + private class InputFragment extends FieldFragment { + + private static final long serialVersionUID = 7003783791888047073L; + + @SuppressWarnings("serial") + public InputFragment(String id, IModel model, final DataType dataType) { + super(id, "inputFragment", DataField.this); + + switch(dataType) { + case TEXT: + case DATA: + field = new TextField("field", model, String.class) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new DataConverter(dataType); + } + }; + break; + case BOOLEAN: + field = new CheckBox("field", model) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new DataConverter(dataType); + } + }; + field.add(new AttributeModifier("type", new Model("checkbox"))); + break; + case DATE: + field = new DateTextField("field", model) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new DataConverter(dataType); + } + }; + field.add(new DatePicker()); + break; + case INTEGER: + field = new TextField("field", model, Long.class) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new DataConverter(dataType); + } + }; + break; + case DECIMAL: + field = new TextField("field", model, Double.class) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new DataConverter(dataType); + } + }; + break; + } + add(field); + } + } + + private class SelectFragment extends FieldFragment { + + private static final long serialVersionUID = -6926320986227794949L; + + @SuppressWarnings("unchecked") + public SelectFragment(String id, IModel model, final DataType dataType, List choices, IChoiceRenderer renderer) { + super(id, "selectFragment", DataField.this); + + if (renderer == null) + field = new DropDownChoice("select", model, choices); + else + field = new DropDownChoice("select", model, choices, renderer); + + add(field); + } + + public SelectFragment(String id, IModel model, final DataType dataType, IModel choices, IChoiceRenderer renderer) { + super(id, "selectFragment", DataField.this); + + if (renderer == null) + field = new DropDownChoice("select", model, choices); + else + field = new DropDownChoice("select", model, choices, renderer); + add(field); + } + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/model/SpringStringResourceModel.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/model/SpringStringResourceModel.java index a88e5cd13..676e49c05 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/model/SpringStringResourceModel.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/model/SpringStringResourceModel.java @@ -1,244 +1,253 @@ -package org.obiba.onyx.wicket.model; - -import java.util.Locale; - -import org.apache.wicket.Application; -import org.apache.wicket.Session; -import org.apache.wicket.WicketRuntimeException; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.LoadableDetachableModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.util.string.interpolator.PropertyVariableInterpolator; -import org.springframework.context.ApplicationContext; -import org.springframework.context.MessageSource; - -/** - * Localization using Spring messages, with the {@link Session} current locale. - * @author Yannick Marcon - * - */ -public class SpringStringResourceModel extends LoadableDetachableModel { - - private static final long serialVersionUID = -1944585777700210245L; - - private ApplicationContext context; - - /** The locale to use. */ - private transient Locale locale; - - /** The key of message to get. */ - private final String resourceKey; - - /** The key message of message to get. */ - private final IModel resourceKeyModel; - - /** The wrapped model for property substitutions. */ - private final IModel model; - - /** Optional parameters. */ - private final Object[] parameters; - - /** The default value of the message. */ - private final String defaultValue; - - /** - * Localize the given resource key. - * @param resourceKey The resource key for this string resource - */ - public SpringStringResourceModel(final String resourceKey) { - this(resourceKey, null, null, resourceKey); - } - - /** - * Localize the given resource key. - * @param resourceKeyModel The resource key model for this string resource - */ - public SpringStringResourceModel(final IModel resourceKeyModel) { - this(resourceKeyModel, null, null, null); - } - - /** - * Localize the given resource key. - * @param resourceKey The resource key for this string resource - * @param model The model to use for property substitutions - */ - public SpringStringResourceModel(final String resourceKey, final IModel model) { - this(resourceKey, model, null, resourceKey); - } - - /** - * Localize the given resource key. - * @param resourceKeyModel The resource key model for this string resource - * @param model The model to use for property substitutions - */ - public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model) { - this(resourceKeyModel, model, null, null); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKey The resource key for this string resource - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final String resourceKey, final String defaultValue) { - this(resourceKey, null, null, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKeyModel The resource key model for this string resource - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final IModel resourceKeyModel, final String defaultValue) { - this(resourceKeyModel, null, null, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKey The resource key for this string resource - * @param model The model to use for property substitutions - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final String resourceKey, final IModel model, final String defaultValue) { - this(resourceKey, model, null, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKeyModel The resource key model for this string resource - * @param model The model to use for property substitutions - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model, final String defaultValue) { - this(resourceKeyModel, model, null, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKey The resource key for this string resource - * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", - * "{1,date}", "{2,time}" within a message), or null if none. - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final String resourceKey, final Object[] parameters, final String defaultValue) { - this(resourceKey, null, parameters, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKeyModel The resource key model for this string resource - * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", - * "{1,date}", "{2,time}" within a message), or null if none. - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final IModel resourceKeyModel, final Object[] parameters, final String defaultValue) { - this(resourceKeyModel, null, parameters, defaultValue); - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKey The resource key for this string resource - * @param model The model to use for property substitutions - * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", - * "{1,date}", "{2,time}" within a message), or null if none. - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final String resourceKey, final IModel model, final Object[] parameters, final String defaultValue) { - if(resourceKey == null) { - throw new IllegalArgumentException("Resource key must not be null"); - } - this.resourceKeyModel = null; - this.resourceKey = resourceKey; - this.defaultValue = defaultValue; - this.parameters = parameters; - this.model = model; - } - - /** - * Localize the given resource key, return default value if key not found. - * @param resourceKeyModel The resource key model for this string resource - * @param model The model to use for property substitutions - * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", - * "{1,date}", "{2,time}" within a message), or null if none. - * @param defaultValue The default value if the resource key is not found. - */ - public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model, final Object[] parameters, final String defaultValue) { - this.resourceKeyModel = resourceKeyModel; - this.resourceKey = null; - this.defaultValue = defaultValue; - this.parameters = parameters; - this.model = model; - } - - protected Object load() { - // Initialize information that we need to work successfully - final Session session = Session.get(); - if(session != null && Application.get() instanceof SpringWebApplication) { - context = ((SpringWebApplication) Application.get()).getSpringContextLocator().getSpringContext(); - locale = session.getLocale(); - } else { - throw new WicketRuntimeException("Cannot attach a string resource model without a Session context or a valid Application context because that is required to get a Spring application Context"); - } - return getStringResource(); - } - - protected void onDetach() { - // Detach any model - if(model != null) { - model.detach(); - } - if (resourceKeyModel != null) { - resourceKeyModel.detach(); - } - // nullification - context = null; - locale = null; - } - - /** - * Get the resource value from Spring {@link MessageSource}. - * @return - */ - private String getStringResource() { - String key = getResourceKey(); - String value = context.getMessage(key, getParameters(), defaultValue, locale); - - return value != null ? value : key; - } - - public final String getString() { - if(context == null) { - return (String) load(); - } - return getStringResource(); - } - - /** - * Gets the Java MessageFormat substitution parameters. - * - * @return The substitution parameters - */ - protected Object[] getParameters() { - return parameters; - } - - /** - * Gets the resource key for this string resource. If the resource key contains property expressions and the model is - * not null then the returned value is the actual resource key with all substitutions undertaken. - * - * @return The (possibly substituted) resource key - */ - protected final String getResourceKey() { - String key = resourceKey; - if(resourceKeyModel != null) { - key = (String) resourceKeyModel.getObject(); - } - - if(model != null) { - return PropertyVariableInterpolator.interpolate(key, model.getObject()); - } else { - return key; - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.model; + +import java.util.Locale; + +import org.apache.wicket.Application; +import org.apache.wicket.Session; +import org.apache.wicket.WicketRuntimeException; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.LoadableDetachableModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.util.string.interpolator.PropertyVariableInterpolator; +import org.springframework.context.ApplicationContext; +import org.springframework.context.MessageSource; + +/** + * Localization using Spring messages, with the {@link Session} current locale. + * @author Yannick Marcon + * + */ +public class SpringStringResourceModel extends LoadableDetachableModel { + + private static final long serialVersionUID = -1944585777700210245L; + + private ApplicationContext context; + + /** The locale to use. */ + private transient Locale locale; + + /** The key of message to get. */ + private final String resourceKey; + + /** The key message of message to get. */ + private final IModel resourceKeyModel; + + /** The wrapped model for property substitutions. */ + private final IModel model; + + /** Optional parameters. */ + private final Object[] parameters; + + /** The default value of the message. */ + private final String defaultValue; + + /** + * Localize the given resource key. + * @param resourceKey The resource key for this string resource + */ + public SpringStringResourceModel(final String resourceKey) { + this(resourceKey, null, null, resourceKey); + } + + /** + * Localize the given resource key. + * @param resourceKeyModel The resource key model for this string resource + */ + public SpringStringResourceModel(final IModel resourceKeyModel) { + this(resourceKeyModel, null, null, null); + } + + /** + * Localize the given resource key. + * @param resourceKey The resource key for this string resource + * @param model The model to use for property substitutions + */ + public SpringStringResourceModel(final String resourceKey, final IModel model) { + this(resourceKey, model, null, resourceKey); + } + + /** + * Localize the given resource key. + * @param resourceKeyModel The resource key model for this string resource + * @param model The model to use for property substitutions + */ + public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model) { + this(resourceKeyModel, model, null, null); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKey The resource key for this string resource + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final String resourceKey, final String defaultValue) { + this(resourceKey, null, null, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKeyModel The resource key model for this string resource + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final IModel resourceKeyModel, final String defaultValue) { + this(resourceKeyModel, null, null, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKey The resource key for this string resource + * @param model The model to use for property substitutions + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final String resourceKey, final IModel model, final String defaultValue) { + this(resourceKey, model, null, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKeyModel The resource key model for this string resource + * @param model The model to use for property substitutions + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model, final String defaultValue) { + this(resourceKeyModel, model, null, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKey The resource key for this string resource + * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", + * "{1,date}", "{2,time}" within a message), or null if none. + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final String resourceKey, final Object[] parameters, final String defaultValue) { + this(resourceKey, null, parameters, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKeyModel The resource key model for this string resource + * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", + * "{1,date}", "{2,time}" within a message), or null if none. + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final IModel resourceKeyModel, final Object[] parameters, final String defaultValue) { + this(resourceKeyModel, null, parameters, defaultValue); + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKey The resource key for this string resource + * @param model The model to use for property substitutions + * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", + * "{1,date}", "{2,time}" within a message), or null if none. + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final String resourceKey, final IModel model, final Object[] parameters, final String defaultValue) { + if(resourceKey == null) { + throw new IllegalArgumentException("Resource key must not be null"); + } + this.resourceKeyModel = null; + this.resourceKey = resourceKey; + this.defaultValue = defaultValue; + this.parameters = parameters; + this.model = model; + } + + /** + * Localize the given resource key, return default value if key not found. + * @param resourceKeyModel The resource key model for this string resource + * @param model The model to use for property substitutions + * @param parameters Array of arguments that will be filled in for params within the message (params look like "{0}", + * "{1,date}", "{2,time}" within a message), or null if none. + * @param defaultValue The default value if the resource key is not found. + */ + public SpringStringResourceModel(final IModel resourceKeyModel, final IModel model, final Object[] parameters, final String defaultValue) { + this.resourceKeyModel = resourceKeyModel; + this.resourceKey = null; + this.defaultValue = defaultValue; + this.parameters = parameters; + this.model = model; + } + + protected Object load() { + // Initialize information that we need to work successfully + final Session session = Session.get(); + if(session != null && Application.get() instanceof SpringWebApplication) { + context = ((SpringWebApplication) Application.get()).getSpringContextLocator().getSpringContext(); + locale = session.getLocale(); + } else { + throw new WicketRuntimeException("Cannot attach a string resource model without a Session context or a valid Application context because that is required to get a Spring application Context"); + } + return getStringResource(); + } + + protected void onDetach() { + // Detach any model + if(model != null) { + model.detach(); + } + if (resourceKeyModel != null) { + resourceKeyModel.detach(); + } + // nullification + context = null; + locale = null; + } + + /** + * Get the resource value from Spring {@link MessageSource}. + * @return + */ + private String getStringResource() { + String key = getResourceKey(); + String value = context.getMessage(key, getParameters(), defaultValue, locale); + + return value != null ? value : key; + } + + public final String getString() { + if(context == null) { + return (String) load(); + } + return getStringResource(); + } + + /** + * Gets the Java MessageFormat substitution parameters. + * + * @return The substitution parameters + */ + protected Object[] getParameters() { + return parameters; + } + + /** + * Gets the resource key for this string resource. If the resource key contains property expressions and the model is + * not null then the returned value is the actual resource key with all substitutions undertaken. + * + * @return The (possibly substituted) resource key + */ + protected final String getResourceKey() { + String key = resourceKey; + if(resourceKeyModel != null) { + key = (String) resourceKeyModel.getObject(); + } + + if(model != null) { + return PropertyVariableInterpolator.interpolate(key, model.getObject()); + } else { + return key; + } + } + +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/test/ExtendedApplicationContextMock.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/test/ExtendedApplicationContextMock.java index 4deb4267e..01bd37814 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/test/ExtendedApplicationContextMock.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/test/ExtendedApplicationContextMock.java @@ -1,37 +1,46 @@ -package org.obiba.onyx.wicket.test; - -import java.util.Locale; - -import org.apache.wicket.spring.test.ApplicationContextMock; - -public class ExtendedApplicationContextMock extends ApplicationContextMock { - - private static final long serialVersionUID = 1L; - - private String message; - - /** - * Returns a "canned" message -- the message specified by the last call - * to setMessage. - * - * NOTE: All arguments are ignored. The same "canned" message is returned - * in all cases. - * - * @param code message key - * @param args message arguments (for placeholders) - * @param locale message locale - * @return message previously set by setMessage - */ - public String getMessage(String code, Object[] args, Locale locale) { - return message; - } - - /** - * Sets the message returned by getMessage. - * - * @param message the message - */ - public void setMessage(String message) { - this.message = message; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.test; + +import java.util.Locale; + +import org.apache.wicket.spring.test.ApplicationContextMock; + +public class ExtendedApplicationContextMock extends ApplicationContextMock { + + private static final long serialVersionUID = 1L; + + private String message; + + /** + * Returns a "canned" message -- the message specified by the last call + * to setMessage. + * + * NOTE: All arguments are ignored. The same "canned" message is returned + * in all cases. + * + * @param code message key + * @param args message arguments (for placeholders) + * @param locale message locale + * @return message previously set by setMessage + */ + public String getMessage(String code, Object[] args, Locale locale) { + return message; + } + + /** + * Sets the message returned by getMessage. + * + * @param message the message + */ + public void setMessage(String message) { + this.message = message; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/util/DateModelUtils.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/util/DateModelUtils.java index 3da0cbfe2..60243c221 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/util/DateModelUtils.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/util/DateModelUtils.java @@ -1,73 +1,82 @@ -package org.obiba.onyx.wicket.util; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.protocol.http.WebSession; - -public class DateModelUtils { - - public static IModel getShortDateTimeModel(IModel dateModel) { - return new FormatingDateTimeModel(SimpleDateFormat.SHORT, dateModel); - } - - public static IModel getDateTimeModel(IModel dateModel) { - return new FormatingDateTimeModel(SimpleDateFormat.MEDIUM, dateModel); - } - - public static IModel getShortDateModel(IModel dateModel) { - return new FormatingDateModel(SimpleDateFormat.SHORT, dateModel); - } - - public static IModel getDateModel(IModel dateModel) { - return new FormatingDateModel(SimpleDateFormat.MEDIUM, dateModel); - } - - private static class FormatingDateTimeModel extends Model { - - private static final long serialVersionUID = 0L; - - int format; - - IModel dateModel; - - FormatingDateTimeModel(int dateFormat, IModel dateModel) { - this.format = dateFormat; - this.dateModel = dateModel; - } - - @Override - public Object getObject() { - Date date = (Date) dateModel.getObject(); - if(date != null) { - return SimpleDateFormat.getDateTimeInstance(format, SimpleDateFormat.SHORT, WebSession.get().getLocale()).format(date); - } - return ""; - } - } - - private static class FormatingDateModel extends Model { - - private static final long serialVersionUID = 0L; - - int format; - - IModel dateModel; - - FormatingDateModel(int dateFormat, IModel dateModel) { - this.format = dateFormat; - this.dateModel = dateModel; - } - - @Override - public Object getObject() { - Date date = (Date) dateModel.getObject(); - if(date != null) { - return SimpleDateFormat.getDateInstance(format, WebSession.get().getLocale()).format(date); - } - return ""; - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.protocol.http.WebSession; + +public class DateModelUtils { + + public static IModel getShortDateTimeModel(IModel dateModel) { + return new FormatingDateTimeModel(SimpleDateFormat.SHORT, dateModel); + } + + public static IModel getDateTimeModel(IModel dateModel) { + return new FormatingDateTimeModel(SimpleDateFormat.MEDIUM, dateModel); + } + + public static IModel getShortDateModel(IModel dateModel) { + return new FormatingDateModel(SimpleDateFormat.SHORT, dateModel); + } + + public static IModel getDateModel(IModel dateModel) { + return new FormatingDateModel(SimpleDateFormat.MEDIUM, dateModel); + } + + private static class FormatingDateTimeModel extends Model { + + private static final long serialVersionUID = 0L; + + int format; + + IModel dateModel; + + FormatingDateTimeModel(int dateFormat, IModel dateModel) { + this.format = dateFormat; + this.dateModel = dateModel; + } + + @Override + public Object getObject() { + Date date = (Date) dateModel.getObject(); + if(date != null) { + return SimpleDateFormat.getDateTimeInstance(format, SimpleDateFormat.SHORT, WebSession.get().getLocale()).format(date); + } + return ""; + } + } + + private static class FormatingDateModel extends Model { + + private static final long serialVersionUID = 0L; + + int format; + + IModel dateModel; + + FormatingDateModel(int dateFormat, IModel dateModel) { + this.format = dateFormat; + this.dateModel = dateModel; + } + + @Override + public Object getObject() { + Date date = (Date) dateModel.getObject(); + if(date != null) { + return SimpleDateFormat.getDateInstance(format, WebSession.get().getLocale()).format(date); + } + return ""; + } + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/util/JavascriptEventAlert.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/util/JavascriptEventAlert.java index 044217078..3544040b2 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/util/JavascriptEventAlert.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/util/JavascriptEventAlert.java @@ -1,26 +1,35 @@ -package org.obiba.onyx.wicket.util; - -import org.apache.wicket.AttributeModifier; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - -public class JavascriptEventAlert extends AttributeModifier { - - private static final long serialVersionUID = -863765127280937942L; - - public JavascriptEventAlert(String event, String msg) { - super(event, true, new Model(msg)); - } - - public JavascriptEventAlert(String event, IModel model) { - super(event, true, model); - } - - protected String newValue(final String currentValue, final String replacementValue) { - String result = "return alert('" + replacementValue + "')"; - if (currentValue != null) { - result = currentValue + "; " + result; - } - return result; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.util; + +import org.apache.wicket.AttributeModifier; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; + +public class JavascriptEventAlert extends AttributeModifier { + + private static final long serialVersionUID = -863765127280937942L; + + public JavascriptEventAlert(String event, String msg) { + super(event, true, new Model(msg)); + } + + public JavascriptEventAlert(String event, IModel model) { + super(event, true, model); + } + + protected String newValue(final String currentValue, final String replacementValue) { + String result = "return alert('" + replacementValue + "')"; + if (currentValue != null) { + result = currentValue + "; " + result; + } + return result; + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardForm.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardForm.java index cb68eec40..37c505c67 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardForm.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardForm.java @@ -1,215 +1,224 @@ -package org.obiba.onyx.wicket.wizard; - -import org.apache.wicket.AttributeModifier; -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxButton; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.behavior.IBehavior; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class WizardForm extends Form { - - private static final long serialVersionUID = 8829452703870884599L; - - private static final Logger log = LoggerFactory.getLogger(WizardForm.class); - - /** - * Indicates whether the action was canceled or not. TODO: should probably go in an Action interface or abstract class - * of some sort - */ - private boolean canceled = false; - - public WizardForm(String id) { - super(id); - - setOutputMarkupId(true); - setMultiPart(true); - - IBehavior buttonBehavior = new WizardButtonBehavior(); - // finish button - AjaxButton finish = new AjaxButton("finish", this) { - - private static final long serialVersionUID = 0L; - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - log.debug("finish.onSubmit"); - if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); - onFinish(target, form); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - log.debug("finish.onError"); - if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); - WizardForm.this.onError(target, form); - } - - }; - finish.add(new AttributeModifier("value", true, new StringResourceModel("Finish", WizardForm.this, null))); - finish.add(buttonBehavior); - finish.setEnabled(false); - finish.setOutputMarkupId(true); - add(finish); - - // previous button - AjaxLink link = new AjaxLink("previousLink") { - private static final long serialVersionUID = 0L; - - @Override - public void onClick(AjaxRequestTarget target) { - if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); - WizardForm.this.gotoPrevious(target); - } - - }; - link.add(new AttributeModifier("value", true, new StringResourceModel("Previous", WizardForm.this, null))); - link.setEnabled(false); - link.setOutputMarkupId(true); - link.add(buttonBehavior); - add(link); - - // next button - AjaxButton button = new AjaxButton("nextLink") { - private static final long serialVersionUID = 0L; - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - log.debug("next.onSubmit"); - if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); - WizardForm.this.gotoNext(target); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - log.debug("next.onError"); - if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); - WizardForm.this.onError(target, form); - } - - }; - button.add(new AttributeModifier("value", true, new StringResourceModel("Next", WizardForm.this, null))); - button.setOutputMarkupId(true); - button.add(buttonBehavior); - add(button); - - // cancel button - link = new AjaxLink("cancelLink") { - private static final long serialVersionUID = 0L; - - @Override - public void onClick(AjaxRequestTarget target) { - canceled = true; - onCancel(target); - } - - }; - link.add(new AttributeModifier("value", true, new StringResourceModel("Cancel", WizardForm.this, null))); - add(link); - } - - /** - * Called after wizard form submission generates an error (on next or finish click). - * @param target - * @param form - */ - public abstract void onError(AjaxRequestTarget target, Form form); - - /** - * Called when finish is clicked. - * @param target - * @param form - */ - public abstract void onFinish(AjaxRequestTarget target, Form form); - - /** - * Called when cancel is clicked. - * @param target - */ - public abstract void onCancel(AjaxRequestTarget target); - - public Component getNextLink() { - return get("nextLink"); - } - - public Component getPreviousLink() { - return get("previousLink"); - } - - public Component getFinishLink() { - return get("finish"); - } - - public Component getCancelLink() { - return get("cancelLink"); - } - - protected void gotoNext(AjaxRequestTarget target) { - WizardStepPanel currentStep = (WizardStepPanel) get("step"); - log.info("gotoNext.currentStep=" + currentStep.getClass().getName()); - currentStep.onStepOutNext(WizardForm.this, target); - - WizardStepPanel next = currentStep.getNextStep(); - if(next != null) { - currentStep.replaceWith(next); - next.onStepInNext(this, target); - next.handleWizardState(this, target); - } - target.addComponent(this); - } - - protected void gotoPrevious(AjaxRequestTarget target) { - WizardStepPanel currentStep = (WizardStepPanel) get("step"); - log.info("gotoPrevious.currentStep=" + currentStep.getClass().getName()); - currentStep.onStepOutPrevious(WizardForm.this, target); - - WizardStepPanel previous = currentStep.getPreviousStep(); - if(previous != null) { - currentStep.replaceWith(previous); - previous.onStepInPrevious(this, target); - previous.handleWizardState(this, target); - } - target.addComponent(this); - } - - public boolean isCanceled() { - return canceled; - } - - public void setCanceled(boolean canceled) { - this.canceled = canceled; - } - - public FeedbackPanel getFeedbackPanel() { - return null; - } - - public static String getStepId() { - return "step"; - } - - private class WizardButtonBehavior extends AttributeAppender { - - private static final long serialVersionUID = -2793180600410649652L; - - public WizardButtonBehavior() { - super("class", new Model("disabled"), " "); - } - - /** - * Overriden to enable the behaviour if the component is disabled. We want to append the attribute when the - * component is disabled. - */ - @Override - public boolean isEnabled(Component component) { - return component.isEnabled() == false; - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.wizard; + +import org.apache.wicket.AttributeModifier; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.behavior.IBehavior; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class WizardForm extends Form { + + private static final long serialVersionUID = 8829452703870884599L; + + private static final Logger log = LoggerFactory.getLogger(WizardForm.class); + + /** + * Indicates whether the action was canceled or not. TODO: should probably go in an Action interface or abstract class + * of some sort + */ + private boolean canceled = false; + + public WizardForm(String id) { + super(id); + + setOutputMarkupId(true); + setMultiPart(true); + + IBehavior buttonBehavior = new WizardButtonBehavior(); + // finish button + AjaxButton finish = new AjaxButton("finish", this) { + + private static final long serialVersionUID = 0L; + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + log.debug("finish.onSubmit"); + if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); + onFinish(target, form); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + log.debug("finish.onError"); + if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); + WizardForm.this.onError(target, form); + } + + }; + finish.add(new AttributeModifier("value", true, new StringResourceModel("Finish", WizardForm.this, null))); + finish.add(buttonBehavior); + finish.setEnabled(false); + finish.setOutputMarkupId(true); + add(finish); + + // previous button + AjaxLink link = new AjaxLink("previousLink") { + private static final long serialVersionUID = 0L; + + @Override + public void onClick(AjaxRequestTarget target) { + if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); + WizardForm.this.gotoPrevious(target); + } + + }; + link.add(new AttributeModifier("value", true, new StringResourceModel("Previous", WizardForm.this, null))); + link.setEnabled(false); + link.setOutputMarkupId(true); + link.add(buttonBehavior); + add(link); + + // next button + AjaxButton button = new AjaxButton("nextLink") { + private static final long serialVersionUID = 0L; + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + log.debug("next.onSubmit"); + if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); + WizardForm.this.gotoNext(target); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + log.debug("next.onError"); + if(getFeedbackPanel() != null) target.addComponent(getFeedbackPanel()); + WizardForm.this.onError(target, form); + } + + }; + button.add(new AttributeModifier("value", true, new StringResourceModel("Next", WizardForm.this, null))); + button.setOutputMarkupId(true); + button.add(buttonBehavior); + add(button); + + // cancel button + link = new AjaxLink("cancelLink") { + private static final long serialVersionUID = 0L; + + @Override + public void onClick(AjaxRequestTarget target) { + canceled = true; + onCancel(target); + } + + }; + link.add(new AttributeModifier("value", true, new StringResourceModel("Cancel", WizardForm.this, null))); + add(link); + } + + /** + * Called after wizard form submission generates an error (on next or finish click). + * @param target + * @param form + */ + public abstract void onError(AjaxRequestTarget target, Form form); + + /** + * Called when finish is clicked. + * @param target + * @param form + */ + public abstract void onFinish(AjaxRequestTarget target, Form form); + + /** + * Called when cancel is clicked. + * @param target + */ + public abstract void onCancel(AjaxRequestTarget target); + + public Component getNextLink() { + return get("nextLink"); + } + + public Component getPreviousLink() { + return get("previousLink"); + } + + public Component getFinishLink() { + return get("finish"); + } + + public Component getCancelLink() { + return get("cancelLink"); + } + + protected void gotoNext(AjaxRequestTarget target) { + WizardStepPanel currentStep = (WizardStepPanel) get("step"); + log.info("gotoNext.currentStep=" + currentStep.getClass().getName()); + currentStep.onStepOutNext(WizardForm.this, target); + + WizardStepPanel next = currentStep.getNextStep(); + if(next != null) { + currentStep.replaceWith(next); + next.onStepInNext(this, target); + next.handleWizardState(this, target); + } + target.addComponent(this); + } + + protected void gotoPrevious(AjaxRequestTarget target) { + WizardStepPanel currentStep = (WizardStepPanel) get("step"); + log.info("gotoPrevious.currentStep=" + currentStep.getClass().getName()); + currentStep.onStepOutPrevious(WizardForm.this, target); + + WizardStepPanel previous = currentStep.getPreviousStep(); + if(previous != null) { + currentStep.replaceWith(previous); + previous.onStepInPrevious(this, target); + previous.handleWizardState(this, target); + } + target.addComponent(this); + } + + public boolean isCanceled() { + return canceled; + } + + public void setCanceled(boolean canceled) { + this.canceled = canceled; + } + + public FeedbackPanel getFeedbackPanel() { + return null; + } + + public static String getStepId() { + return "step"; + } + + private class WizardButtonBehavior extends AttributeAppender { + + private static final long serialVersionUID = -2793180600410649652L; + + public WizardButtonBehavior() { + super("class", new Model("disabled"), " "); + } + + /** + * Overriden to enable the behaviour if the component is disabled. We want to append the attribute when the + * component is disabled. + */ + @Override + public boolean isEnabled(Component component) { + return component.isEnabled() == false; + } + } +} diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardPanel.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardPanel.java index 02db2c0a8..ca593ae18 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardPanel.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardPanel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.wicket.wizard; import org.apache.wicket.markup.html.panel.Panel; diff --git a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardStepPanel.java b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardStepPanel.java index ae328161c..109b6a6ad 100644 --- a/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardStepPanel.java +++ b/onyx-core/src/main/java/org/obiba/onyx/wicket/wizard/WizardStepPanel.java @@ -1,96 +1,105 @@ -package org.obiba.onyx.wicket.wizard; - -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.panel.Panel; - -public abstract class WizardStepPanel extends Panel { - - private static final long serialVersionUID = -6326593868471433867L; - - protected WizardStepPanel previous; - - protected WizardStepPanel next; - - public WizardStepPanel(String id) { - super(id); - } - - public void setNextStep(WizardStepPanel next) { - this.next = next; - } - - public WizardStepPanel getNextStep() { - return next; - } - - public void setPreviousStep(WizardStepPanel previous) { - this.previous = previous; - } - - public WizardStepPanel getPreviousStep() { - return previous; - } - - protected void setContent(AjaxRequestTarget target, Component content) { - if(!content.getId().equals(getContentId())) throw new IllegalArgumentException("Expected content id is " + getContentId() + " but " + content.getId() + " was found."); - - Component current = get(getContentId()); - if(current == null) { - add(content); - } else { - current.replaceWith(content); - if(target != null) { - target.addComponent(get(getContentId())); - } - } - - } - - /** - * Called when "next" button submit the current step form to go to next step. - * @param form - * @param target - */ - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - - } - - /** - * Called when "previous" button was pressed to leave this step by going to previous step. - * @param form - * @param target - */ - public void onStepOutPrevious(WizardForm form, AjaxRequestTarget target) { - - } - - /** - * Called when "next" button was pressed to go to this step coming from previous step. - * @param form - * @param target - */ - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - - } - - /** - * Called when "previous" button was pressed to go to this step coming from next step. - * @param form - * @param target - */ - public void onStepInPrevious(WizardForm form, AjaxRequestTarget target) { - - } - - public abstract void handleWizardState(WizardForm form, AjaxRequestTarget target); - - public static String getContentId() { - return "panel"; - } - - public static String getTitleId() { - return "title"; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.wicket.wizard; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.panel.Panel; + +public abstract class WizardStepPanel extends Panel { + + private static final long serialVersionUID = -6326593868471433867L; + + protected WizardStepPanel previous; + + protected WizardStepPanel next; + + public WizardStepPanel(String id) { + super(id); + } + + public void setNextStep(WizardStepPanel next) { + this.next = next; + } + + public WizardStepPanel getNextStep() { + return next; + } + + public void setPreviousStep(WizardStepPanel previous) { + this.previous = previous; + } + + public WizardStepPanel getPreviousStep() { + return previous; + } + + protected void setContent(AjaxRequestTarget target, Component content) { + if(!content.getId().equals(getContentId())) throw new IllegalArgumentException("Expected content id is " + getContentId() + " but " + content.getId() + " was found."); + + Component current = get(getContentId()); + if(current == null) { + add(content); + } else { + current.replaceWith(content); + if(target != null) { + target.addComponent(get(getContentId())); + } + } + + } + + /** + * Called when "next" button submit the current step form to go to next step. + * @param form + * @param target + */ + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + + } + + /** + * Called when "previous" button was pressed to leave this step by going to previous step. + * @param form + * @param target + */ + public void onStepOutPrevious(WizardForm form, AjaxRequestTarget target) { + + } + + /** + * Called when "next" button was pressed to go to this step coming from previous step. + * @param form + * @param target + */ + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + + } + + /** + * Called when "previous" button was pressed to go to this step coming from next step. + * @param form + * @param target + */ + public void onStepInPrevious(WizardForm form, AjaxRequestTarget target) { + + } + + public abstract void handleWizardState(WizardForm form, AjaxRequestTarget target); + + public static String getContentId() { + return "panel"; + } + + public static String getTitleId() { + return "title"; + } + +} diff --git a/onyx-core/src/test/java/org/obiba/onyx/core/engine/state/StageExecutionTest.java b/onyx-core/src/test/java/org/obiba/onyx/core/engine/state/StageExecutionTest.java index 2ec9c5ea3..e968fd129 100644 --- a/onyx-core/src/test/java/org/obiba/onyx/core/engine/state/StageExecutionTest.java +++ b/onyx-core/src/test/java/org/obiba/onyx/core/engine/state/StageExecutionTest.java @@ -1,521 +1,530 @@ -package org.obiba.onyx.core.engine.state; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.stage.StageExecutionMemento; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.impl.DefaultActiveInterviewServiceImpl; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.InverseStageDependencyCondition; -import org.obiba.onyx.engine.MultipleStageDependencyCondition; -import org.obiba.onyx.engine.Operator; -import org.obiba.onyx.engine.PreviousStageDependencyCondition; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class StageExecutionTest extends BaseDefaultSpringContextTestCase { - - private static final Logger log = LoggerFactory.getLogger(StageExecutionTest.class); - - @Autowired(required = true) - PersistenceManager persistenceManager; - - @Autowired(required = true) - StageExecutionContext context1; - - @Autowired(required = true) - StageExecutionContext context2; - - @Autowired(required = true) - StageExecutionContext context3; - - ActiveInterviewService activeInterviewService; - - @Before - public void setUp() { - - activeInterviewService = new DefaultActiveInterviewServiceImpl() { - @Override - public PersistenceManager getPersistenceManager() { - return persistenceManager; - } - - @Override - public IStageExecution getStageExecution(String stageName) { - if(stageName.equals("dummy1")) return context1; - if(stageName.equals("dummy2")) return context2; - if(stageName.equals("dummy3")) return context3; - throw new IllegalArgumentException("Unexpected stage name " + stageName); - } - - @Override - public IStageExecution getStageExecution(Stage stage) { - return getStageExecution(stage.getName()); - } - }; - - Stage stage1 = new Stage(); - stage1.setName("dummy1"); - - Interview interview = persistenceManager.save(new Interview()); - context1.setStage(stage1); - context1.setInterview(interview); - ReadyState ready = new ReadyState(); - InProgressState progress = new InProgressState(); - CompletedState completed = new CompletedState(); - - context1.addEdge(ready, TransitionEvent.START, progress); - context1.addEdge(progress, TransitionEvent.CANCEL, ready); - context1.addEdge(progress, TransitionEvent.COMPLETE, completed); - context1.addEdge(completed, TransitionEvent.CANCEL, ready); - context1.setInitialState(ready); - - Stage stage2 = new Stage(); - stage2.setName("dummy2"); - stage2.setStageDependencyCondition(new PreviousStageDependencyCondition("dummy1")); - - context2.setStage(stage2); - context2.setInterview(interview); - WaitingState waiting = new WaitingState(); - ready = new ReadyState(); - progress = new InProgressState(); - completed = new CompletedState(); - - context2.addEdge(waiting, TransitionEvent.VALID, ready); - context2.addEdge(waiting, TransitionEvent.INVALID, waiting); - context2.addEdge(ready, TransitionEvent.INVALID, waiting); - context2.addEdge(ready, TransitionEvent.START, progress); - context2.addEdge(progress, TransitionEvent.CANCEL, ready); - context2.addEdge(progress, TransitionEvent.COMPLETE, completed); - context2.addEdge(completed, TransitionEvent.CANCEL, ready); - context2.addEdge(completed, TransitionEvent.INVALID, waiting); - context1.addTransitionListener(context2); - context2.setInitialState(waiting); - - Stage stage3 = new Stage(); - stage3.setName("dummy3"); - InverseStageDependencyCondition inverseCondition = new InverseStageDependencyCondition(); - inverseCondition.setStageDependencyCondition(new SpecificStageDependencyCondition("dummy2")); - - MultipleStageDependencyCondition multipleCondition = new MultipleStageDependencyCondition(); - multipleCondition.setLeftStageDependencyCondition(inverseCondition); - multipleCondition.setOperator(Operator.AND); - multipleCondition.setRightStageDependencyCondition(new PreviousStageDependencyCondition("dummy1")); - - stage3.setStageDependencyCondition(multipleCondition); - - context3.setStage(stage3); - context3.setInterview(interview); - NotApplicableState notApplicable = new NotApplicableState(); - waiting = new WaitingState(); - ready = new ReadyState(); - progress = new InProgressState(); - completed = new CompletedState(); - - context3.addEdge(waiting, TransitionEvent.VALID, ready); - context3.addEdge(waiting, TransitionEvent.INVALID, waiting); - context3.addEdge(ready, TransitionEvent.INVALID, waiting); - context3.addEdge(ready, TransitionEvent.START, progress); - context3.addEdge(progress, TransitionEvent.CANCEL, ready); - context3.addEdge(progress, TransitionEvent.COMPLETE, completed); - context3.addEdge(completed, TransitionEvent.CANCEL, ready); - context3.addEdge(completed, TransitionEvent.INVALID, waiting); - context3.addEdge(ready, TransitionEvent.NOTAPPLICABLE, notApplicable); - context3.addEdge(notApplicable, TransitionEvent.INVALID, waiting); - context3.addEdge(completed, TransitionEvent.NOTAPPLICABLE, notApplicable); - context1.addTransitionListener(context3); - context2.addTransitionListener(context3); - context3.setInitialState(waiting); - } - - private StageExecutionMemento getMemento(StageExecutionContext context) { - StageExecutionMemento memento = new StageExecutionMemento(); - memento.setStage(context.getStage().getName()); - memento.setInterview(context.getInterview()); - return persistenceManager.matchOne(memento); - } - - private void assertInitialState() { - Assert.assertEquals("Ready", context1.getMessage()); - StageExecutionMemento memento = getMemento(context1); - Assert.assertNull("Memento is not null", memento); - memento = getMemento(context2); - Assert.assertNull("Memento is not null", memento); - memento = getMemento(context3); - Assert.assertNull("Memento is not null", memento); - } - - @Test - public void testSimpleTransition() { - assertInitialState(); - - // Send the START event in the first state machine - doAction(ActionDefinitionBuilder.START_ACTION); - Assert.assertEquals("InProgress", context1.getMessage()); - Assert.assertEquals(false, context1.isCompleted()); - StageExecutionMemento memento = getMemento(context1); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("InProgressState", memento.getState()); - - Assert.assertEquals("Waiting", context2.getMessage()); - memento = getMemento(context2); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - - Assert.assertEquals("Waiting", context3.getMessage()); - memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - } - - @Test - public void testCancelInProgress() { - doAction(ActionDefinitionBuilder.START_ACTION); - Assert.assertEquals("InProgress", context1.getMessage()); - Assert.assertEquals("Waiting", context2.getMessage()); - Assert.assertEquals("Waiting", context3.getMessage()); - - doAction(ActionDefinitionBuilder.CANCEL_ACTION); - Assert.assertEquals("Ready", context1.getMessage()); - Assert.assertEquals(false, context1.isCompleted()); - Assert.assertEquals("Waiting", context2.getMessage()); - Assert.assertEquals("Waiting", context3.getMessage()); - } - - @Test - public void testCommentDuringInProgress() { - doAction(ActionDefinitionBuilder.START_ACTION); - Assert.assertEquals("InProgress", context1.getMessage()); - Assert.assertEquals("Waiting", context2.getMessage()); - Assert.assertEquals("Waiting", context3.getMessage()); - - doAction(ActionDefinitionBuilder.COMMENT_ACTION); - Assert.assertEquals("InProgress", context1.getMessage()); - Assert.assertEquals("Waiting", context2.getMessage()); - Assert.assertEquals("Waiting", context3.getMessage()); - } - - @Test - public void testCompleteInProgress() { - doAction(ActionDefinitionBuilder.START_ACTION); - Assert.assertEquals("InProgress", context1.getMessage()); - Assert.assertEquals("Waiting", context2.getMessage()); - Assert.assertEquals("Waiting", context3.getMessage()); - - // complete the first stage and make assert that the second becomes ready - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - Assert.assertEquals(true, context1.isCompleted()); - Assert.assertEquals("Completed", context1.getMessage()); - Assert.assertEquals(false, context1.isInteractive()); - - Assert.assertEquals("Ready", context2.getMessage()); - StageExecutionMemento memento = getMemento(context2); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("ReadyState", memento.getState()); - - Assert.assertEquals("Ready", context3.getMessage()); - memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("ReadyState", memento.getState()); - } - - @Test - public void testCancelCompleted() { - doAction(ActionDefinitionBuilder.START_ACTION); - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - doAction(ActionDefinitionBuilder.CANCEL_ACTION); - Assert.assertEquals("Ready", context1.getMessage()); - Assert.assertEquals(false, context1.isInteractive()); - StageExecutionMemento memento = getMemento(context1); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("ReadyState", memento.getState()); - - Assert.assertEquals("Waiting", context2.getMessage()); - memento = getMemento(context2); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - - Assert.assertEquals("Waiting", context3.getMessage()); - memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - } - - @Test - public void testCancelFirstWhenBothAreCompleted() { - doAction(ActionDefinitionBuilder.START_ACTION); - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - doAction(context2, ActionDefinitionBuilder.START_ACTION); - doAction(context2, ActionDefinitionBuilder.COMPLETE_ACTION); - Assert.assertEquals("Completed", context1.getMessage()); - Assert.assertEquals("Completed", context2.getMessage()); - Assert.assertEquals("Not Applicable", context3.getMessage()); - - doAction(ActionDefinitionBuilder.CANCEL_ACTION); - Assert.assertEquals("Ready", context1.getMessage()); - Assert.assertEquals(false, context1.isInteractive()); - StageExecutionMemento memento = getMemento(context1); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("ReadyState", memento.getState()); - Assert.assertEquals("Waiting", context2.getMessage()); - memento = getMemento(context2); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - - Assert.assertEquals("Waiting", context3.getMessage()); - memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("WaitingState", memento.getState()); - } - - @Test - public void testCompleteThenCancelAndCompleteAgain() { - doAction(ActionDefinitionBuilder.START_ACTION); - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - doAction(ActionDefinitionBuilder.CANCEL_ACTION); - doAction(ActionDefinitionBuilder.START_ACTION); - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - Assert.assertEquals("Completed", context1.getMessage()); - } - - @Test - public void testMultipleAndInverseCondition() { - doAction(ActionDefinitionBuilder.START_ACTION); - doAction(ActionDefinitionBuilder.COMPLETE_ACTION); - - Assert.assertEquals("Completed", context1.getMessage()); - Assert.assertEquals("Ready", context2.getMessage()); - Assert.assertEquals("Ready", context3.getMessage()); - StageExecutionMemento memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("ReadyState", memento.getState()); - - doAction(context3, ActionDefinitionBuilder.START_ACTION); - doAction(context3, ActionDefinitionBuilder.COMPLETE_ACTION); - - Assert.assertEquals("Completed", context3.getMessage()); - memento = getMemento(context3); - Assert.assertNotNull("Memento is null", memento); - Assert.assertEquals("CompletedState", memento.getState()); - - doAction(context2, ActionDefinitionBuilder.START_ACTION); - doAction(context2, ActionDefinitionBuilder.COMPLETE_ACTION); - Assert.assertEquals("Not Applicable", context3.getMessage()); - } - - private void doAction(ActionDefinition definition) { - doAction(context1, definition); - } - - /** - * Mimics an Action on the specified context. - * @param context - * @param definition - */ - private void doAction(StageExecutionContext context, ActionDefinition definition) { - definition.getType().act(context, new Action(definition)); - } - - public class WaitingState extends AbstractStageState { - - public WaitingState() { - setActiveInterviewService(StageExecutionTest.this.activeInterviewService); - } - - @Override - public void execute(Action action) { - super.execute(action); - log.info("Stage {} is starting", super.getStage().getName()); - castEvent(TransitionEvent.START); - } - - @Override - public String getMessage() { - return "Waiting"; - } - - public String getName() { - return "Waiting"; - } - - } - - public class ReadyState extends AbstractStageState { - - public ReadyState() { - setActiveInterviewService(StageExecutionTest.this.activeInterviewService); - addAction(ActionDefinitionBuilder.START_ACTION); - addAction(ActionDefinitionBuilder.COMMENT_ACTION); - } - - @Override - public void execute(Action action) { - super.execute(action); - log.info("Stage {} is starting", super.getStage().getName()); - castEvent(TransitionEvent.START); - } - - @Override - public String getMessage() { - return "Ready"; - } - - public String getName() { - return "Ready"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.VALID)) return false; - else - return true; - } - } - - public class InProgressState extends AbstractStageState { - - public InProgressState() { - setActiveInterviewService(StageExecutionTest.this.activeInterviewService); - addAction(ActionDefinitionBuilder.CANCEL_ACTION); - addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); - addAction(ActionDefinitionBuilder.COMMENT_ACTION); - } - - @Override - public void stop(Action action) { - log.info("Stage {} is stopping", super.getStage().getName()); - // Invalidate current instrument run - castEvent(TransitionEvent.CANCEL); - } - - @Override - public void complete(Action action) { - log.info("Stage {} is completing", super.getStage().getName()); - // Finish current instrument run - castEvent(TransitionEvent.COMPLETE); - } - - @Override - public boolean isInteractive() { - return true; - } - - @Override - public String getMessage() { - return "InProgress"; - } - - public String getName() { - return "InProgress"; - } - - } - - public class CompletedState extends AbstractStageState { - - public CompletedState() { - setActiveInterviewService(StageExecutionTest.this.activeInterviewService); - addAction(ActionDefinitionBuilder.CANCEL_ACTION); - addAction(ActionDefinitionBuilder.COMMENT_ACTION); - } - - @Override - public void stop(Action action) { - super.execute(action); - log.info("Stage {} is cancelling", super.getStage().getName()); - castEvent(TransitionEvent.CANCEL); - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - public String getMessage() { - return "Completed"; - } - - public String getName() { - return "Completed"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.VALID)) return false; - else - return true; - } - } - - public class NotApplicableState extends AbstractStageState { - - public NotApplicableState() { - setActiveInterviewService(StageExecutionTest.this.activeInterviewService); - } - - @Override - public String getMessage() { - return "Not Applicable"; - } - - public String getName() { - return "NotApplicableState"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; - else - return true; - } - } - - public class SpecificStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private String stageName; - - public SpecificStageDependencyCondition() { - } - - public SpecificStageDependencyCondition(String name) { - this.stageName = name; - } - - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - return activeInterviewService.getStageExecution(stageName).isCompleted(); - } - - @Override - public boolean isDependentOn(String stageName) { - return this.stageName.equals(stageName); - } - - public String getStageName() { - return stageName; - } - - public void setStageName(String stageName) { - this.stageName = stageName; - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.engine.state; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.stage.StageExecutionMemento; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.impl.DefaultActiveInterviewServiceImpl; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.InverseStageDependencyCondition; +import org.obiba.onyx.engine.MultipleStageDependencyCondition; +import org.obiba.onyx.engine.Operator; +import org.obiba.onyx.engine.PreviousStageDependencyCondition; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class StageExecutionTest extends BaseDefaultSpringContextTestCase { + + private static final Logger log = LoggerFactory.getLogger(StageExecutionTest.class); + + @Autowired(required = true) + PersistenceManager persistenceManager; + + @Autowired(required = true) + StageExecutionContext context1; + + @Autowired(required = true) + StageExecutionContext context2; + + @Autowired(required = true) + StageExecutionContext context3; + + ActiveInterviewService activeInterviewService; + + @Before + public void setUp() { + + activeInterviewService = new DefaultActiveInterviewServiceImpl() { + @Override + public PersistenceManager getPersistenceManager() { + return persistenceManager; + } + + @Override + public IStageExecution getStageExecution(String stageName) { + if(stageName.equals("dummy1")) return context1; + if(stageName.equals("dummy2")) return context2; + if(stageName.equals("dummy3")) return context3; + throw new IllegalArgumentException("Unexpected stage name " + stageName); + } + + @Override + public IStageExecution getStageExecution(Stage stage) { + return getStageExecution(stage.getName()); + } + }; + + Stage stage1 = new Stage(); + stage1.setName("dummy1"); + + Interview interview = persistenceManager.save(new Interview()); + context1.setStage(stage1); + context1.setInterview(interview); + ReadyState ready = new ReadyState(); + InProgressState progress = new InProgressState(); + CompletedState completed = new CompletedState(); + + context1.addEdge(ready, TransitionEvent.START, progress); + context1.addEdge(progress, TransitionEvent.CANCEL, ready); + context1.addEdge(progress, TransitionEvent.COMPLETE, completed); + context1.addEdge(completed, TransitionEvent.CANCEL, ready); + context1.setInitialState(ready); + + Stage stage2 = new Stage(); + stage2.setName("dummy2"); + stage2.setStageDependencyCondition(new PreviousStageDependencyCondition("dummy1")); + + context2.setStage(stage2); + context2.setInterview(interview); + WaitingState waiting = new WaitingState(); + ready = new ReadyState(); + progress = new InProgressState(); + completed = new CompletedState(); + + context2.addEdge(waiting, TransitionEvent.VALID, ready); + context2.addEdge(waiting, TransitionEvent.INVALID, waiting); + context2.addEdge(ready, TransitionEvent.INVALID, waiting); + context2.addEdge(ready, TransitionEvent.START, progress); + context2.addEdge(progress, TransitionEvent.CANCEL, ready); + context2.addEdge(progress, TransitionEvent.COMPLETE, completed); + context2.addEdge(completed, TransitionEvent.CANCEL, ready); + context2.addEdge(completed, TransitionEvent.INVALID, waiting); + context1.addTransitionListener(context2); + context2.setInitialState(waiting); + + Stage stage3 = new Stage(); + stage3.setName("dummy3"); + InverseStageDependencyCondition inverseCondition = new InverseStageDependencyCondition(); + inverseCondition.setStageDependencyCondition(new SpecificStageDependencyCondition("dummy2")); + + MultipleStageDependencyCondition multipleCondition = new MultipleStageDependencyCondition(); + multipleCondition.setLeftStageDependencyCondition(inverseCondition); + multipleCondition.setOperator(Operator.AND); + multipleCondition.setRightStageDependencyCondition(new PreviousStageDependencyCondition("dummy1")); + + stage3.setStageDependencyCondition(multipleCondition); + + context3.setStage(stage3); + context3.setInterview(interview); + NotApplicableState notApplicable = new NotApplicableState(); + waiting = new WaitingState(); + ready = new ReadyState(); + progress = new InProgressState(); + completed = new CompletedState(); + + context3.addEdge(waiting, TransitionEvent.VALID, ready); + context3.addEdge(waiting, TransitionEvent.INVALID, waiting); + context3.addEdge(ready, TransitionEvent.INVALID, waiting); + context3.addEdge(ready, TransitionEvent.START, progress); + context3.addEdge(progress, TransitionEvent.CANCEL, ready); + context3.addEdge(progress, TransitionEvent.COMPLETE, completed); + context3.addEdge(completed, TransitionEvent.CANCEL, ready); + context3.addEdge(completed, TransitionEvent.INVALID, waiting); + context3.addEdge(ready, TransitionEvent.NOTAPPLICABLE, notApplicable); + context3.addEdge(notApplicable, TransitionEvent.INVALID, waiting); + context3.addEdge(completed, TransitionEvent.NOTAPPLICABLE, notApplicable); + context1.addTransitionListener(context3); + context2.addTransitionListener(context3); + context3.setInitialState(waiting); + } + + private StageExecutionMemento getMemento(StageExecutionContext context) { + StageExecutionMemento memento = new StageExecutionMemento(); + memento.setStage(context.getStage().getName()); + memento.setInterview(context.getInterview()); + return persistenceManager.matchOne(memento); + } + + private void assertInitialState() { + Assert.assertEquals("Ready", context1.getMessage()); + StageExecutionMemento memento = getMemento(context1); + Assert.assertNull("Memento is not null", memento); + memento = getMemento(context2); + Assert.assertNull("Memento is not null", memento); + memento = getMemento(context3); + Assert.assertNull("Memento is not null", memento); + } + + @Test + public void testSimpleTransition() { + assertInitialState(); + + // Send the START event in the first state machine + doAction(ActionDefinitionBuilder.START_ACTION); + Assert.assertEquals("InProgress", context1.getMessage()); + Assert.assertEquals(false, context1.isCompleted()); + StageExecutionMemento memento = getMemento(context1); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("InProgressState", memento.getState()); + + Assert.assertEquals("Waiting", context2.getMessage()); + memento = getMemento(context2); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + + Assert.assertEquals("Waiting", context3.getMessage()); + memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + } + + @Test + public void testCancelInProgress() { + doAction(ActionDefinitionBuilder.START_ACTION); + Assert.assertEquals("InProgress", context1.getMessage()); + Assert.assertEquals("Waiting", context2.getMessage()); + Assert.assertEquals("Waiting", context3.getMessage()); + + doAction(ActionDefinitionBuilder.CANCEL_ACTION); + Assert.assertEquals("Ready", context1.getMessage()); + Assert.assertEquals(false, context1.isCompleted()); + Assert.assertEquals("Waiting", context2.getMessage()); + Assert.assertEquals("Waiting", context3.getMessage()); + } + + @Test + public void testCommentDuringInProgress() { + doAction(ActionDefinitionBuilder.START_ACTION); + Assert.assertEquals("InProgress", context1.getMessage()); + Assert.assertEquals("Waiting", context2.getMessage()); + Assert.assertEquals("Waiting", context3.getMessage()); + + doAction(ActionDefinitionBuilder.COMMENT_ACTION); + Assert.assertEquals("InProgress", context1.getMessage()); + Assert.assertEquals("Waiting", context2.getMessage()); + Assert.assertEquals("Waiting", context3.getMessage()); + } + + @Test + public void testCompleteInProgress() { + doAction(ActionDefinitionBuilder.START_ACTION); + Assert.assertEquals("InProgress", context1.getMessage()); + Assert.assertEquals("Waiting", context2.getMessage()); + Assert.assertEquals("Waiting", context3.getMessage()); + + // complete the first stage and make assert that the second becomes ready + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + Assert.assertEquals(true, context1.isCompleted()); + Assert.assertEquals("Completed", context1.getMessage()); + Assert.assertEquals(false, context1.isInteractive()); + + Assert.assertEquals("Ready", context2.getMessage()); + StageExecutionMemento memento = getMemento(context2); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("ReadyState", memento.getState()); + + Assert.assertEquals("Ready", context3.getMessage()); + memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("ReadyState", memento.getState()); + } + + @Test + public void testCancelCompleted() { + doAction(ActionDefinitionBuilder.START_ACTION); + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + doAction(ActionDefinitionBuilder.CANCEL_ACTION); + Assert.assertEquals("Ready", context1.getMessage()); + Assert.assertEquals(false, context1.isInteractive()); + StageExecutionMemento memento = getMemento(context1); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("ReadyState", memento.getState()); + + Assert.assertEquals("Waiting", context2.getMessage()); + memento = getMemento(context2); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + + Assert.assertEquals("Waiting", context3.getMessage()); + memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + } + + @Test + public void testCancelFirstWhenBothAreCompleted() { + doAction(ActionDefinitionBuilder.START_ACTION); + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + doAction(context2, ActionDefinitionBuilder.START_ACTION); + doAction(context2, ActionDefinitionBuilder.COMPLETE_ACTION); + Assert.assertEquals("Completed", context1.getMessage()); + Assert.assertEquals("Completed", context2.getMessage()); + Assert.assertEquals("Not Applicable", context3.getMessage()); + + doAction(ActionDefinitionBuilder.CANCEL_ACTION); + Assert.assertEquals("Ready", context1.getMessage()); + Assert.assertEquals(false, context1.isInteractive()); + StageExecutionMemento memento = getMemento(context1); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("ReadyState", memento.getState()); + Assert.assertEquals("Waiting", context2.getMessage()); + memento = getMemento(context2); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + + Assert.assertEquals("Waiting", context3.getMessage()); + memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("WaitingState", memento.getState()); + } + + @Test + public void testCompleteThenCancelAndCompleteAgain() { + doAction(ActionDefinitionBuilder.START_ACTION); + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + doAction(ActionDefinitionBuilder.CANCEL_ACTION); + doAction(ActionDefinitionBuilder.START_ACTION); + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + Assert.assertEquals("Completed", context1.getMessage()); + } + + @Test + public void testMultipleAndInverseCondition() { + doAction(ActionDefinitionBuilder.START_ACTION); + doAction(ActionDefinitionBuilder.COMPLETE_ACTION); + + Assert.assertEquals("Completed", context1.getMessage()); + Assert.assertEquals("Ready", context2.getMessage()); + Assert.assertEquals("Ready", context3.getMessage()); + StageExecutionMemento memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("ReadyState", memento.getState()); + + doAction(context3, ActionDefinitionBuilder.START_ACTION); + doAction(context3, ActionDefinitionBuilder.COMPLETE_ACTION); + + Assert.assertEquals("Completed", context3.getMessage()); + memento = getMemento(context3); + Assert.assertNotNull("Memento is null", memento); + Assert.assertEquals("CompletedState", memento.getState()); + + doAction(context2, ActionDefinitionBuilder.START_ACTION); + doAction(context2, ActionDefinitionBuilder.COMPLETE_ACTION); + Assert.assertEquals("Not Applicable", context3.getMessage()); + } + + private void doAction(ActionDefinition definition) { + doAction(context1, definition); + } + + /** + * Mimics an Action on the specified context. + * @param context + * @param definition + */ + private void doAction(StageExecutionContext context, ActionDefinition definition) { + definition.getType().act(context, new Action(definition)); + } + + public class WaitingState extends AbstractStageState { + + public WaitingState() { + setActiveInterviewService(StageExecutionTest.this.activeInterviewService); + } + + @Override + public void execute(Action action) { + super.execute(action); + log.info("Stage {} is starting", super.getStage().getName()); + castEvent(TransitionEvent.START); + } + + @Override + public String getMessage() { + return "Waiting"; + } + + public String getName() { + return "Waiting"; + } + + } + + public class ReadyState extends AbstractStageState { + + public ReadyState() { + setActiveInterviewService(StageExecutionTest.this.activeInterviewService); + addAction(ActionDefinitionBuilder.START_ACTION); + addAction(ActionDefinitionBuilder.COMMENT_ACTION); + } + + @Override + public void execute(Action action) { + super.execute(action); + log.info("Stage {} is starting", super.getStage().getName()); + castEvent(TransitionEvent.START); + } + + @Override + public String getMessage() { + return "Ready"; + } + + public String getName() { + return "Ready"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.VALID)) return false; + else + return true; + } + } + + public class InProgressState extends AbstractStageState { + + public InProgressState() { + setActiveInterviewService(StageExecutionTest.this.activeInterviewService); + addAction(ActionDefinitionBuilder.CANCEL_ACTION); + addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); + addAction(ActionDefinitionBuilder.COMMENT_ACTION); + } + + @Override + public void stop(Action action) { + log.info("Stage {} is stopping", super.getStage().getName()); + // Invalidate current instrument run + castEvent(TransitionEvent.CANCEL); + } + + @Override + public void complete(Action action) { + log.info("Stage {} is completing", super.getStage().getName()); + // Finish current instrument run + castEvent(TransitionEvent.COMPLETE); + } + + @Override + public boolean isInteractive() { + return true; + } + + @Override + public String getMessage() { + return "InProgress"; + } + + public String getName() { + return "InProgress"; + } + + } + + public class CompletedState extends AbstractStageState { + + public CompletedState() { + setActiveInterviewService(StageExecutionTest.this.activeInterviewService); + addAction(ActionDefinitionBuilder.CANCEL_ACTION); + addAction(ActionDefinitionBuilder.COMMENT_ACTION); + } + + @Override + public void stop(Action action) { + super.execute(action); + log.info("Stage {} is cancelling", super.getStage().getName()); + castEvent(TransitionEvent.CANCEL); + } + + @Override + public boolean isCompleted() { + return true; + } + + @Override + public String getMessage() { + return "Completed"; + } + + public String getName() { + return "Completed"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.VALID)) return false; + else + return true; + } + } + + public class NotApplicableState extends AbstractStageState { + + public NotApplicableState() { + setActiveInterviewService(StageExecutionTest.this.activeInterviewService); + } + + @Override + public String getMessage() { + return "Not Applicable"; + } + + public String getName() { + return "NotApplicableState"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; + else + return true; + } + } + + public class SpecificStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private String stageName; + + public SpecificStageDependencyCondition() { + } + + public SpecificStageDependencyCondition(String name) { + this.stageName = name; + } + + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + return activeInterviewService.getStageExecution(stageName).isCompleted(); + } + + @Override + public boolean isDependentOn(String stageName) { + return this.stageName.equals(stageName); + } + + public String getStageName() { + return stageName; + } + + public void setStageName(String stageName) { + this.stageName = stageName; + } + } + +} diff --git a/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantExcelReader.java b/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantExcelReader.java index 4947f326a..9a5c11029 100644 --- a/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantExcelReader.java +++ b/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantExcelReader.java @@ -1,56 +1,65 @@ -package org.obiba.onyx.core.service; - -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.obiba.onyx.core.domain.participant.Appointment; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.participant.Province; -import org.obiba.onyx.core.etl.participant.AbstractParticipantExcelReader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ParticipantExcelReader extends AbstractParticipantExcelReader { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ParticipantExcelReader.class); - - protected int getStartAtLine() { - return 3; - } - - protected Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator) { - Participant participant = new Participant(); - - participant.setSiteNo(getTextValue(row, evaluator, row.getCell(2))); - participant.setFirstName(getTextValue(row, evaluator, row.getCell(5))); - participant.setLastName(getTextValue(row, evaluator, row.getCell(4))); - Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); - participant.setEnrollmentId(id == null ? null : id.toString()); - participant.setBirthDate(getDateValue(row, evaluator, row.getCell(7))); - String gender = getTextValue(row, evaluator, row.getCell(6)); - if(gender.equals("M")) { - participant.setGender(Gender.MALE); - } else if(gender.equals("F")) { - participant.setGender(Gender.FEMALE); - } - participant.setStreet(getTextValue(row, evaluator, row.getCell(8))); - participant.setCity(getTextValue(row, evaluator, row.getCell(9))); - participant.setProvince(Province.valueOf(getTextValue(row, evaluator, row.getCell(10)))); - participant.setCountry(getTextValue(row, evaluator, row.getCell(11))); - participant.setPostalCode(getTextValue(row, evaluator, row.getCell(12))); - participant.setPhone(getTextValue(row, evaluator, row.getCell(13))); - - return participant; - } - - protected Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator) { - Appointment appointment = new Appointment(); - - Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); - appointment.setAppointmentCode(id == null ? null : id.toString()); - appointment.setDate(getDateValue(row, evaluator, row.getCell(0))); - - return appointment; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.obiba.onyx.core.domain.participant.Appointment; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.participant.Province; +import org.obiba.onyx.core.etl.participant.AbstractParticipantExcelReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ParticipantExcelReader extends AbstractParticipantExcelReader { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ParticipantExcelReader.class); + + protected int getStartAtLine() { + return 3; + } + + protected Participant processParticipant(HSSFRow row, HSSFFormulaEvaluator evaluator) { + Participant participant = new Participant(); + + participant.setSiteNo(getTextValue(row, evaluator, row.getCell(2))); + participant.setFirstName(getTextValue(row, evaluator, row.getCell(5))); + participant.setLastName(getTextValue(row, evaluator, row.getCell(4))); + Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); + participant.setEnrollmentId(id == null ? null : id.toString()); + participant.setBirthDate(getDateValue(row, evaluator, row.getCell(7))); + String gender = getTextValue(row, evaluator, row.getCell(6)); + if(gender.equals("M")) { + participant.setGender(Gender.MALE); + } else if(gender.equals("F")) { + participant.setGender(Gender.FEMALE); + } + participant.setStreet(getTextValue(row, evaluator, row.getCell(8))); + participant.setCity(getTextValue(row, evaluator, row.getCell(9))); + participant.setProvince(Province.valueOf(getTextValue(row, evaluator, row.getCell(10)))); + participant.setCountry(getTextValue(row, evaluator, row.getCell(11))); + participant.setPostalCode(getTextValue(row, evaluator, row.getCell(12))); + participant.setPhone(getTextValue(row, evaluator, row.getCell(13))); + + return participant; + } + + protected Appointment processAppointment(HSSFRow row, HSSFFormulaEvaluator evaluator) { + Appointment appointment = new Appointment(); + + Long id = getNumericValue(row, evaluator, row.getCell(3)).longValue(); + appointment.setAppointmentCode(id == null ? null : id.toString()); + appointment.setDate(getDateValue(row, evaluator, row.getCell(0))); + + return appointment; + } +} diff --git a/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantServiceTest.java b/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantServiceTest.java index fe5eb2e68..a51edca96 100644 --- a/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantServiceTest.java +++ b/onyx-core/src/test/java/org/obiba/onyx/core/service/ParticipantServiceTest.java @@ -1,196 +1,205 @@ -package org.obiba.onyx.core.service; - -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.ObjectError; - -@Transactional -public class ParticipantServiceTest extends BaseDefaultSpringContextTestCase { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ParticipantServiceTest.class); - - @Autowired(required = true) - PersistenceManager persistenceManager; - - @Autowired(required = true) - ParticipantService participantService; - - @Test - @Dataset - public void testParticipantByCode() { - Assert.assertEquals(1, participantService.countParticipantsByCode("1")); - Assert.assertEquals(2, participantService.countParticipantsByCode("100002")); - } - - @Test - @Dataset - public void testParticipantByInterviewStatus() { - Assert.assertEquals(1, participantService.countParticipants(InterviewStatus.COMPLETED)); - Assert.assertEquals(1, participantService.countParticipants(InterviewStatus.IN_PROGRESS)); - } - - @Test - @Dataset - public void testParticipantByName() { - Assert.assertEquals(2, participantService.countParticipantsByName("Hudson")); - Assert.assertEquals(1, participantService.countParticipantsByName("John Hudson")); - Assert.assertEquals(2, participantService.countParticipantsByName("ohn")); - } - - @Test - @Dataset - public void testParticipantByAppointmentDate() { - Calendar cal = Calendar.getInstance(); - cal.set(2008, 8, 1, 0, 0, 0); - Date from = cal.getTime(); - cal.add(Calendar.DAY_OF_MONTH, 1); - Date to = cal.getTime(); - - log.info("from=" + from + " to=" + to); - Assert.assertEquals(2, participantService.countParticipants(from, to)); - } - - @Test - @Dataset - public void testAssignCodeToParticipantWithNoComment() { - long participantId = 4l; - long userId = 1l; // administrator - String barcode = "100004"; - - Participant participant = persistenceManager.get(Participant.class, participantId); - Assert.assertNotNull(participant); - - User user = persistenceManager.get(User.class, userId); - Assert.assertNotNull(user); - - participantService.assignCodeToParticipant(participant, barcode, null, user); - - // Verify that the bar code was persisted. - participant = persistenceManager.get(Participant.class, 4l); - Assert.assertEquals(barcode, participant.getBarcode()); - } - - @Test - @Dataset - public void testAssignCodeToParticipantWithComment() { - long participantId = 4l; - long userId = 1l; // administrator - String barcode = "100004"; - String receptionComment = "test comment"; - - Participant participant = persistenceManager.get(Participant.class, participantId); - Assert.assertNotNull(participant); - - User user = persistenceManager.get(User.class, userId); - Assert.assertNotNull(user); - - participantService.assignCodeToParticipant(participant, barcode, receptionComment, user); - - // Verify that the bar code was persisted. - participant = persistenceManager.get(Participant.class, participantId); - Assert.assertEquals(barcode, participant.getBarcode()); - - // Verify that the comment was persisted. - Action commentTemplate = new Action(); - commentTemplate.setActionType(ActionType.COMMENT); - commentTemplate.setComment(receptionComment); - commentTemplate.setUser(user); - commentTemplate.setInterview(participant.getInterview()); - List comments = persistenceManager.match(commentTemplate, new PagingClause(0)); - Assert.assertTrue(comments.size() == 1); - Assert.assertEquals(comments.get(0).getComment(), receptionComment); - } - - @Test - @Dataset(filenames={"AppConfigurationForParticipantServiceTest.xml"}) - public void testParticipantReader() { - try { - participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); - Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); - - // test we can run same file multiple times without breaking the db - participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); - Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); - Participant p = new Participant(); - p.setEnrollmentId("100001"); - p = persistenceManager.matchOne(p); - Assert.assertNotNull("Cannot find participant", p); - Assert.assertNotNull("Cannot find participant appointment", p.getAppointment()); - Assert.assertNotNull("Cannot find participant appointment date", p.getAppointment().getDate()); - - // add a completed interview - p.setBarcode("1"); - persistenceManager.save(p); - Interview interview = new Interview(); - interview.setStatus(InterviewStatus.COMPLETED); - interview.setParticipant(p); - persistenceManager.save(interview); - p.setInterview(interview); - persistenceManager.save(p); - p = new Participant(); - p.setEnrollmentId("100001"); - p = persistenceManager.matchOne(p); - Assert.assertNotNull("Cannot find participant", p); - Assert.assertNotNull("Cannot find participant interview", p.getInterview()); - Assert.assertEquals("Cannot find participant completed interview", InterviewStatus.COMPLETED, p.getInterview().getStatus()); - - participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); - Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); - p = new Participant(); - p.setEnrollmentId("100001"); - p = persistenceManager.matchOne(p); - Assert.assertNotNull("Cannot find participant", p); - Assert.assertNotNull("Cannot find participant appointment", p.getAppointment()); - Assert.assertNotNull("Cannot find participant appointment date", p.getAppointment().getDate()); - Assert.assertNotNull("Cannot find participant interview", p.getInterview()); - Assert.assertEquals("Cannot find participant completed interview", InterviewStatus.COMPLETED, p.getInterview().getStatus()); - - try { - participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous-corrupted.xls")); - Assert.fail("ValidationRuntimeException not thrown"); - } catch(ValidationRuntimeException ve) { - List oes = ve.getAllObjectErrors(); - Assert.assertEquals("Not the right count of errors", 2, oes.size()); - ObjectError oe = oes.get(0); - Assert.assertEquals("Not the right error code", "ParticipantInterviewCompletedWithAppointmentInTheFuture", oe.getCode()); - Assert.assertEquals("Not the right error arguments count", 2, oe.getArguments().length); - Assert.assertEquals("Not the right error argument line", "3", oe.getArguments()[0]); - Assert.assertEquals("Not the right error argument id", "100001", oe.getArguments()[1]); - oe = oes.get(1); - Assert.assertEquals("Not the right error code", "WrongParticipantSiteName", oe.getCode()); - Assert.assertEquals("Not the right error arguments count", 4, oe.getArguments().length); - Assert.assertEquals("Not the right error argument line", "10", oe.getArguments()[0]); - Assert.assertEquals("Not the right error argument id", "100008", oe.getArguments()[1]); - Assert.assertEquals("Not the right error argument participant site name", "cag002", oe.getArguments()[2]); - Assert.assertEquals("Not the right error argument app site name", "cag001", oe.getArguments()[3]); - log.info(ve.toString()); - } - - } catch(ValidationRuntimeException e) { - Assert.fail(e.getMessage()); - e.printStackTrace(); - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.ObjectError; + +@Transactional +public class ParticipantServiceTest extends BaseDefaultSpringContextTestCase { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ParticipantServiceTest.class); + + @Autowired(required = true) + PersistenceManager persistenceManager; + + @Autowired(required = true) + ParticipantService participantService; + + @Test + @Dataset + public void testParticipantByCode() { + Assert.assertEquals(1, participantService.countParticipantsByCode("1")); + Assert.assertEquals(2, participantService.countParticipantsByCode("100002")); + } + + @Test + @Dataset + public void testParticipantByInterviewStatus() { + Assert.assertEquals(1, participantService.countParticipants(InterviewStatus.COMPLETED)); + Assert.assertEquals(1, participantService.countParticipants(InterviewStatus.IN_PROGRESS)); + } + + @Test + @Dataset + public void testParticipantByName() { + Assert.assertEquals(2, participantService.countParticipantsByName("Hudson")); + Assert.assertEquals(1, participantService.countParticipantsByName("John Hudson")); + Assert.assertEquals(2, participantService.countParticipantsByName("ohn")); + } + + @Test + @Dataset + public void testParticipantByAppointmentDate() { + Calendar cal = Calendar.getInstance(); + cal.set(2008, 8, 1, 0, 0, 0); + Date from = cal.getTime(); + cal.add(Calendar.DAY_OF_MONTH, 1); + Date to = cal.getTime(); + + log.info("from=" + from + " to=" + to); + Assert.assertEquals(2, participantService.countParticipants(from, to)); + } + + @Test + @Dataset + public void testAssignCodeToParticipantWithNoComment() { + long participantId = 4l; + long userId = 1l; // administrator + String barcode = "100004"; + + Participant participant = persistenceManager.get(Participant.class, participantId); + Assert.assertNotNull(participant); + + User user = persistenceManager.get(User.class, userId); + Assert.assertNotNull(user); + + participantService.assignCodeToParticipant(participant, barcode, null, user); + + // Verify that the bar code was persisted. + participant = persistenceManager.get(Participant.class, 4l); + Assert.assertEquals(barcode, participant.getBarcode()); + } + + @Test + @Dataset + public void testAssignCodeToParticipantWithComment() { + long participantId = 4l; + long userId = 1l; // administrator + String barcode = "100004"; + String receptionComment = "test comment"; + + Participant participant = persistenceManager.get(Participant.class, participantId); + Assert.assertNotNull(participant); + + User user = persistenceManager.get(User.class, userId); + Assert.assertNotNull(user); + + participantService.assignCodeToParticipant(participant, barcode, receptionComment, user); + + // Verify that the bar code was persisted. + participant = persistenceManager.get(Participant.class, participantId); + Assert.assertEquals(barcode, participant.getBarcode()); + + // Verify that the comment was persisted. + Action commentTemplate = new Action(); + commentTemplate.setActionType(ActionType.COMMENT); + commentTemplate.setComment(receptionComment); + commentTemplate.setUser(user); + commentTemplate.setInterview(participant.getInterview()); + List comments = persistenceManager.match(commentTemplate, new PagingClause(0)); + Assert.assertTrue(comments.size() == 1); + Assert.assertEquals(comments.get(0).getComment(), receptionComment); + } + + @Test + @Dataset(filenames={"AppConfigurationForParticipantServiceTest.xml"}) + public void testParticipantReader() { + try { + participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); + Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); + + // test we can run same file multiple times without breaking the db + participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); + Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); + Participant p = new Participant(); + p.setEnrollmentId("100001"); + p = persistenceManager.matchOne(p); + Assert.assertNotNull("Cannot find participant", p); + Assert.assertNotNull("Cannot find participant appointment", p.getAppointment()); + Assert.assertNotNull("Cannot find participant appointment date", p.getAppointment().getDate()); + + // add a completed interview + p.setBarcode("1"); + persistenceManager.save(p); + Interview interview = new Interview(); + interview.setStatus(InterviewStatus.COMPLETED); + interview.setParticipant(p); + persistenceManager.save(interview); + p.setInterview(interview); + persistenceManager.save(p); + p = new Participant(); + p.setEnrollmentId("100001"); + p = persistenceManager.matchOne(p); + Assert.assertNotNull("Cannot find participant", p); + Assert.assertNotNull("Cannot find participant interview", p.getInterview()); + Assert.assertEquals("Cannot find participant completed interview", InterviewStatus.COMPLETED, p.getInterview().getStatus()); + + participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous.xls")); + Assert.assertEquals(3l, persistenceManager.match(new Participant()).size()); + p = new Participant(); + p.setEnrollmentId("100001"); + p = persistenceManager.matchOne(p); + Assert.assertNotNull("Cannot find participant", p); + Assert.assertNotNull("Cannot find participant appointment", p.getAppointment()); + Assert.assertNotNull("Cannot find participant appointment date", p.getAppointment().getDate()); + Assert.assertNotNull("Cannot find participant interview", p.getInterview()); + Assert.assertEquals("Cannot find participant completed interview", InterviewStatus.COMPLETED, p.getInterview().getStatus()); + + try { + participantService.updateParticipants(getClass().getResourceAsStream("rendez-vous-corrupted.xls")); + Assert.fail("ValidationRuntimeException not thrown"); + } catch(ValidationRuntimeException ve) { + List oes = ve.getAllObjectErrors(); + Assert.assertEquals("Not the right count of errors", 2, oes.size()); + ObjectError oe = oes.get(0); + Assert.assertEquals("Not the right error code", "ParticipantInterviewCompletedWithAppointmentInTheFuture", oe.getCode()); + Assert.assertEquals("Not the right error arguments count", 2, oe.getArguments().length); + Assert.assertEquals("Not the right error argument line", "3", oe.getArguments()[0]); + Assert.assertEquals("Not the right error argument id", "100001", oe.getArguments()[1]); + oe = oes.get(1); + Assert.assertEquals("Not the right error code", "WrongParticipantSiteName", oe.getCode()); + Assert.assertEquals("Not the right error arguments count", 4, oe.getArguments().length); + Assert.assertEquals("Not the right error argument line", "10", oe.getArguments()[0]); + Assert.assertEquals("Not the right error argument id", "100008", oe.getArguments()[1]); + Assert.assertEquals("Not the right error argument participant site name", "cag002", oe.getArguments()[2]); + Assert.assertEquals("Not the right error argument app site name", "cag001", oe.getArguments()[3]); + log.info(ve.toString()); + } + + } catch(ValidationRuntimeException e) { + Assert.fail(e.getMessage()); + e.printStackTrace(); + } + + } + +} diff --git a/onyx-core/src/test/java/org/obiba/onyx/core/service/UserServiceTest.java b/onyx-core/src/test/java/org/obiba/onyx/core/service/UserServiceTest.java index 52513cb59..de60ebca6 100644 --- a/onyx-core/src/test/java/org/obiba/onyx/core/service/UserServiceTest.java +++ b/onyx-core/src/test/java/org/obiba/onyx/core/service/UserServiceTest.java @@ -1,121 +1,130 @@ -package org.obiba.onyx.core.service; - -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.service.SortingClause; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class UserServiceTest extends BaseDefaultSpringContextTestCase { - - @Autowired(required=true) - PersistenceManager persistenceManager; - - @Autowired(required = true) - UserService userService; - - @Test - @Dataset - public void testGetRoles() { - List roleList = userService.getRoles(new SortingClause("name")); - Assert.assertEquals(3, roleList.size()); - } - - @Test - @Dataset - public void testGetUsers() { - User template = new User(); - template.setDeleted(false); - List userList = userService.getUsers(template, new PagingClause(0), new SortingClause("lastName")); - Assert.assertEquals(3, userList.size()); - } - - @Test - @Dataset - public void testGetUserCount() { - User template = new User(); - template.setDeleted(false); - Assert.assertEquals(3, userService.getUserCount(template)); - } - - @Test - @Dataset - public void testGetUserWithLogin() { - User user = userService.getUserWithLogin("ndupont"); - Assert.assertEquals("Dupont", user.getLastName()); - Assert.assertEquals("Natasha", user.getFirstName()); - } - - @Test - @Dataset - public void testUpdateStatus() { - userService.updateStatus(Long.valueOf("2"), Status.INACTIVE); - Assert.assertEquals(Status.INACTIVE, persistenceManager.get(User.class, Long.valueOf("2")).getStatus()); - } - - @Test - @Dataset - public void testDeleteUser() { - userService.deleteUser(Long.valueOf("2")); - Assert.assertEquals(true, persistenceManager.get(User.class, Long.valueOf("2")).isDeleted()); - } - - @Test - @Dataset - public void testUpdateUserlanguage() { - userService.updateUserLanguage(Long.valueOf("2"), Locale.FRENCH); - Assert.assertEquals(Locale.FRENCH, persistenceManager.get(User.class, Long.valueOf("2")).getLanguage()); - } - - @Test - @Dataset - public void testIsNewPassword() { - Assert.assertEquals(true, userService.isNewPassword(persistenceManager.get(User.class, Long.valueOf("2")), "turlututu")); - } - - @Test - @Dataset - public void testUpdatePassword() { - userService.updatePassword(Long.valueOf("2"), "newpasswordforuser"); - Assert.assertEquals("newpasswordforuser", persistenceManager.get(User.class, Long.valueOf("2")).getPassword()); - } - - @Test - @Dataset - public void testCreateOrUpdateUser() { - User modifUser = persistenceManager.get(User.class, Long.valueOf("3")); - modifUser.setFirstName("Paul"); - userService.createOrUpdateUser(modifUser); - Assert.assertEquals("Paul", persistenceManager.get(User.class, Long.valueOf("3")).getFirstName()); - - User newUser = new User(); - newUser.setLastName("Tremblay"); - newUser.setFirstName("Michel"); - newUser.setLogin("mtremblay"); - newUser.setEmail("tremblay@obiba.org"); - newUser.setPassword("titi"); - newUser.setLanguage(Locale.ENGLISH); - newUser.setStatus(Status.ACTIVE); - Set roles = new HashSet(); - roles.add(persistenceManager.get(Role.class, Long.valueOf("2"))); - newUser.setRoles(roles); - - userService.createOrUpdateUser(newUser); - Assert.assertEquals("Tremblay", userService.getUserWithLogin("mtremblay").getLastName()); - Assert.assertEquals(Long.valueOf("4"), userService.getUserWithLogin("mtremblay").getId()); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.core.service; + +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.service.SortingClause; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class UserServiceTest extends BaseDefaultSpringContextTestCase { + + @Autowired(required=true) + PersistenceManager persistenceManager; + + @Autowired(required = true) + UserService userService; + + @Test + @Dataset + public void testGetRoles() { + List roleList = userService.getRoles(new SortingClause("name")); + Assert.assertEquals(3, roleList.size()); + } + + @Test + @Dataset + public void testGetUsers() { + User template = new User(); + template.setDeleted(false); + List userList = userService.getUsers(template, new PagingClause(0), new SortingClause("lastName")); + Assert.assertEquals(3, userList.size()); + } + + @Test + @Dataset + public void testGetUserCount() { + User template = new User(); + template.setDeleted(false); + Assert.assertEquals(3, userService.getUserCount(template)); + } + + @Test + @Dataset + public void testGetUserWithLogin() { + User user = userService.getUserWithLogin("ndupont"); + Assert.assertEquals("Dupont", user.getLastName()); + Assert.assertEquals("Natasha", user.getFirstName()); + } + + @Test + @Dataset + public void testUpdateStatus() { + userService.updateStatus(Long.valueOf("2"), Status.INACTIVE); + Assert.assertEquals(Status.INACTIVE, persistenceManager.get(User.class, Long.valueOf("2")).getStatus()); + } + + @Test + @Dataset + public void testDeleteUser() { + userService.deleteUser(Long.valueOf("2")); + Assert.assertEquals(true, persistenceManager.get(User.class, Long.valueOf("2")).isDeleted()); + } + + @Test + @Dataset + public void testUpdateUserlanguage() { + userService.updateUserLanguage(Long.valueOf("2"), Locale.FRENCH); + Assert.assertEquals(Locale.FRENCH, persistenceManager.get(User.class, Long.valueOf("2")).getLanguage()); + } + + @Test + @Dataset + public void testIsNewPassword() { + Assert.assertEquals(true, userService.isNewPassword(persistenceManager.get(User.class, Long.valueOf("2")), "turlututu")); + } + + @Test + @Dataset + public void testUpdatePassword() { + userService.updatePassword(Long.valueOf("2"), "newpasswordforuser"); + Assert.assertEquals("newpasswordforuser", persistenceManager.get(User.class, Long.valueOf("2")).getPassword()); + } + + @Test + @Dataset + public void testCreateOrUpdateUser() { + User modifUser = persistenceManager.get(User.class, Long.valueOf("3")); + modifUser.setFirstName("Paul"); + userService.createOrUpdateUser(modifUser); + Assert.assertEquals("Paul", persistenceManager.get(User.class, Long.valueOf("3")).getFirstName()); + + User newUser = new User(); + newUser.setLastName("Tremblay"); + newUser.setFirstName("Michel"); + newUser.setLogin("mtremblay"); + newUser.setEmail("tremblay@obiba.org"); + newUser.setPassword("titi"); + newUser.setLanguage(Locale.ENGLISH); + newUser.setStatus(Status.ACTIVE); + Set roles = new HashSet(); + roles.add(persistenceManager.get(Role.class, Long.valueOf("2"))); + newUser.setRoles(roles); + + userService.createOrUpdateUser(newUser); + Assert.assertEquals("Tremblay", userService.getUserWithLogin("mtremblay").getLastName()); + Assert.assertEquals(Long.valueOf("4"), userService.getUserWithLogin("mtremblay").getId()); + } + +} diff --git a/onyx-core/src/test/java/org/obiba/onyx/engine/StageTest.java b/onyx-core/src/test/java/org/obiba/onyx/engine/StageTest.java index 8a687b363..3012c4ebc 100644 --- a/onyx-core/src/test/java/org/obiba/onyx/engine/StageTest.java +++ b/onyx-core/src/test/java/org/obiba/onyx/engine/StageTest.java @@ -1,81 +1,90 @@ -package org.obiba.onyx.engine; - -import static org.easymock.EasyMock.*; - -import java.util.Locale; - -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.wicket.test.ExtendedApplicationContextMock; - -public class StageTest { - - private ExtendedApplicationContextMock applicationContextMock; - - private UserSessionService userSessionServiceMock; - - @Before - public void setUp() { - applicationContextMock = new ExtendedApplicationContextMock(); - - userSessionServiceMock = createMock(UserSessionService.class); - applicationContextMock.putBean("userSessionService", userSessionServiceMock); - } - - /** - * Tests that the returned stage description is localized. - */ - @Test - public void testGetDescription() { - Stage heightMeasurementStage = new Stage(); - heightMeasurementStage.setApplicationContext(applicationContextMock); - heightMeasurementStage.setUserSessionService(userSessionServiceMock); - - String unLocalizedStageDescription = "Height_Measurement"; - heightMeasurementStage.setDescription(unLocalizedStageDescription); - - // - // Test in English locale ("en"). - // - Locale englishLocale = new Locale("en"); - - String expectedEnglishLocalizedStageDescription = "Height Measurement"; - applicationContextMock.setMessage(expectedEnglishLocalizedStageDescription); - - expect(userSessionServiceMock.getLocale()).andReturn(englishLocale); - - replay(userSessionServiceMock); - - String actualEnglishLocalizedStageDescription = heightMeasurementStage.getDescription(); - - verify(userSessionServiceMock); - - Assert.assertEquals(expectedEnglishLocalizedStageDescription, actualEnglishLocalizedStageDescription); - - // Reset userSessionServiceMock (otherwise in the next part of the test the calls to getLocale() - // won't match expectations). - reset(userSessionServiceMock); - - // - // Test in French locale ("fr"). - // - Locale frenchLocale = new Locale("fr"); - - //TODO: Substitute true French translation when it is added to the resource bundle - String expectedFrenchLocalizedStageDescription = "fr:Height Measurement"; - applicationContextMock.setMessage(expectedFrenchLocalizedStageDescription); - - expect(userSessionServiceMock.getLocale()).andReturn(frenchLocale); - - replay(userSessionServiceMock); - - String actualFrenchLocalizedStageDescription = heightMeasurementStage.getDescription(); - - verify(userSessionServiceMock); - - Assert.assertEquals(expectedFrenchLocalizedStageDescription, actualFrenchLocalizedStageDescription); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.engine; + +import static org.easymock.EasyMock.*; + +import java.util.Locale; + +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.wicket.test.ExtendedApplicationContextMock; + +public class StageTest { + + private ExtendedApplicationContextMock applicationContextMock; + + private UserSessionService userSessionServiceMock; + + @Before + public void setUp() { + applicationContextMock = new ExtendedApplicationContextMock(); + + userSessionServiceMock = createMock(UserSessionService.class); + applicationContextMock.putBean("userSessionService", userSessionServiceMock); + } + + /** + * Tests that the returned stage description is localized. + */ + @Test + public void testGetDescription() { + Stage heightMeasurementStage = new Stage(); + heightMeasurementStage.setApplicationContext(applicationContextMock); + heightMeasurementStage.setUserSessionService(userSessionServiceMock); + + String unLocalizedStageDescription = "Height_Measurement"; + heightMeasurementStage.setDescription(unLocalizedStageDescription); + + // + // Test in English locale ("en"). + // + Locale englishLocale = new Locale("en"); + + String expectedEnglishLocalizedStageDescription = "Height Measurement"; + applicationContextMock.setMessage(expectedEnglishLocalizedStageDescription); + + expect(userSessionServiceMock.getLocale()).andReturn(englishLocale); + + replay(userSessionServiceMock); + + String actualEnglishLocalizedStageDescription = heightMeasurementStage.getDescription(); + + verify(userSessionServiceMock); + + Assert.assertEquals(expectedEnglishLocalizedStageDescription, actualEnglishLocalizedStageDescription); + + // Reset userSessionServiceMock (otherwise in the next part of the test the calls to getLocale() + // won't match expectations). + reset(userSessionServiceMock); + + // + // Test in French locale ("fr"). + // + Locale frenchLocale = new Locale("fr"); + + //TODO: Substitute true French translation when it is added to the resource bundle + String expectedFrenchLocalizedStageDescription = "fr:Height Measurement"; + applicationContextMock.setMessage(expectedFrenchLocalizedStageDescription); + + expect(userSessionServiceMock.getLocale()).andReturn(frenchLocale); + + replay(userSessionServiceMock); + + String actualFrenchLocalizedStageDescription = heightMeasurementStage.getDescription(); + + verify(userSessionServiceMock); + + Assert.assertEquals(expectedFrenchLocalizedStageDescription, actualFrenchLocalizedStageDescription); + } +} diff --git a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/client/JnlpClient.java b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/client/JnlpClient.java index de3c5dbc8..48b336c4b 100644 --- a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/client/JnlpClient.java +++ b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/client/JnlpClient.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.client; import java.io.ByteArrayInputStream; diff --git a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/ExternalAppLauncherHelper.java b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/ExternalAppLauncherHelper.java index 0ea9a58c3..02e37f357 100644 --- a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/ExternalAppLauncherHelper.java +++ b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/ExternalAppLauncherHelper.java @@ -1,154 +1,163 @@ -package org.obiba.onyx.jade.instrument; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.OverlappingFileLockException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JOptionPane; - -import org.obiba.onyx.jade.client.JnlpClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ExternalAppLauncherHelper { - - // Working directory for external software. - protected String workDir; - - // Executable of external software. - protected String executable; - - // Parameters of external software command - protected String parameterStr; - - public void launchExternalSoftware() { - - class OuputPurger extends Thread { - - InputStream inputStream; - - OuputPurger(InputStream pInputStream) { - inputStream = pInputStream; - } - - public void run() { - try { - InputStreamReader wReader = new InputStreamReader(inputStream); - BufferedReader wBuffReader = new BufferedReader(wReader); - - while((wBuffReader.readLine()) != null) { - } - - } catch(IOException wEx) { - } - } - } - - List command = new ArrayList(); - command.add("cmd"); - command.add("/c"); - - if (getParameterStr() == null) - command.add(getExecutable()); - else - command.add(getExecutable() + " " + getParameterStr()); - - ProcessBuilder builder = new ProcessBuilder(command); - builder.directory(new File(getWorkDir())); - - Process wProcess = null; - try { - wProcess = builder.start(); - } catch(IOException wCouldNotCreateProcess) { - JOptionPane.showMessageDialog(null, "Could not create external process for: " + getWorkDir() + getExecutable(), "Cannot start application!", JOptionPane.ERROR_MESSAGE); - System.exit(1); - } - - OuputPurger wOutputErrorPurger = new OuputPurger(wProcess.getErrorStream()); - OuputPurger wOutputPurger = new OuputPurger(wProcess.getInputStream()); - - wOutputErrorPurger.start(); - wOutputPurger.start(); - - try { - wProcess.waitFor(); - } catch(InterruptedException wThreadInterrupted) { - wThreadInterrupted.printStackTrace(); - System.exit(1); - } - - } - - public boolean isSotfwareAlreadyStarted() { - return isSotfwareAlreadyStarted(getExecutable()); - } - - public boolean isSotfwareAlreadyStarted(String lockName) { - - File wFile = new File(System.getProperty("java.io.tmpdir"), lockName + ".lock"); - - try { - - FileChannel channel = new RandomAccessFile(wFile, "rw").getChannel(); - FileLock collectorLock = null; - - try { - collectorLock = channel.tryLock(); - } catch(OverlappingFileLockException wEx) { - return true; - } - - if(collectorLock == null) { - return true; - } else { - return false; - } - - } catch(Exception wCouldNotDetermineIfRunning) { - wCouldNotDetermineIfRunning.printStackTrace(); - return true; - } - - } - - public void launch() { - if(!isSotfwareAlreadyStarted()) { - launchExternalSoftware(); - } else { - JOptionPane.showMessageDialog(null, getExecutable() + " already lock for execution. Please make sure that another instance is not running.", "Cannot start application!", JOptionPane.ERROR_MESSAGE); - } - } - - public String getExecutable() { - return executable; - } - - public void setExecutable(String executable) { - this.executable = executable; - } - - public String getParameterStr() { - return parameterStr; - } - - public void setParameterStr(String parameterStr) { - this.parameterStr = parameterStr; - } - - public String getWorkDir() { - return workDir; - } - - public void setWorkDir(String workDir) { - this.workDir = workDir; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JOptionPane; + +import org.obiba.onyx.jade.client.JnlpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExternalAppLauncherHelper { + + // Working directory for external software. + protected String workDir; + + // Executable of external software. + protected String executable; + + // Parameters of external software command + protected String parameterStr; + + public void launchExternalSoftware() { + + class OuputPurger extends Thread { + + InputStream inputStream; + + OuputPurger(InputStream pInputStream) { + inputStream = pInputStream; + } + + public void run() { + try { + InputStreamReader wReader = new InputStreamReader(inputStream); + BufferedReader wBuffReader = new BufferedReader(wReader); + + while((wBuffReader.readLine()) != null) { + } + + } catch(IOException wEx) { + } + } + } + + List command = new ArrayList(); + command.add("cmd"); + command.add("/c"); + + if (getParameterStr() == null) + command.add(getExecutable()); + else + command.add(getExecutable() + " " + getParameterStr()); + + ProcessBuilder builder = new ProcessBuilder(command); + builder.directory(new File(getWorkDir())); + + Process wProcess = null; + try { + wProcess = builder.start(); + } catch(IOException wCouldNotCreateProcess) { + JOptionPane.showMessageDialog(null, "Could not create external process for: " + getWorkDir() + getExecutable(), "Cannot start application!", JOptionPane.ERROR_MESSAGE); + System.exit(1); + } + + OuputPurger wOutputErrorPurger = new OuputPurger(wProcess.getErrorStream()); + OuputPurger wOutputPurger = new OuputPurger(wProcess.getInputStream()); + + wOutputErrorPurger.start(); + wOutputPurger.start(); + + try { + wProcess.waitFor(); + } catch(InterruptedException wThreadInterrupted) { + wThreadInterrupted.printStackTrace(); + System.exit(1); + } + + } + + public boolean isSotfwareAlreadyStarted() { + return isSotfwareAlreadyStarted(getExecutable()); + } + + public boolean isSotfwareAlreadyStarted(String lockName) { + + File wFile = new File(System.getProperty("java.io.tmpdir"), lockName + ".lock"); + + try { + + FileChannel channel = new RandomAccessFile(wFile, "rw").getChannel(); + FileLock collectorLock = null; + + try { + collectorLock = channel.tryLock(); + } catch(OverlappingFileLockException wEx) { + return true; + } + + if(collectorLock == null) { + return true; + } else { + return false; + } + + } catch(Exception wCouldNotDetermineIfRunning) { + wCouldNotDetermineIfRunning.printStackTrace(); + return true; + } + + } + + public void launch() { + if(!isSotfwareAlreadyStarted()) { + launchExternalSoftware(); + } else { + JOptionPane.showMessageDialog(null, getExecutable() + " already lock for execution. Please make sure that another instance is not running.", "Cannot start application!", JOptionPane.ERROR_MESSAGE); + } + } + + public String getExecutable() { + return executable; + } + + public void setExecutable(String executable) { + this.executable = executable; + } + + public String getParameterStr() { + return parameterStr; + } + + public void setParameterStr(String parameterStr) { + this.parameterStr = parameterStr; + } + + public String getWorkDir() { + return workDir; + } + + public void setWorkDir(String workDir) { + this.workDir = workDir; + } + +} diff --git a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/InstrumentRunner.java b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/InstrumentRunner.java index 9a8fd255b..681f19283 100644 --- a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/InstrumentRunner.java +++ b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/InstrumentRunner.java @@ -1,16 +1,25 @@ -package org.obiba.onyx.jade.instrument; - - - -public interface InstrumentRunner { - - // Initialization before instrument run. - public void initialize(); - - public void run(); - - // If the initialize method is executed (without error), the shutdown method is guaranteed - // to be executed also. Any exception thrown during shutdown will be ignored. - public void shutdown(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument; + + + +public interface InstrumentRunner { + + // Initialization before instrument run. + public void initialize(); + + public void run(); + + // If the initialize method is executed (without error), the shutdown method is guaranteed + // to be executed also. Any exception thrown during shutdown will be ignored. + public void shutdown(); + +} diff --git a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/LocalSettingsHelper.java b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/LocalSettingsHelper.java index bc7ea40ee..ef1801041 100644 --- a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/LocalSettingsHelper.java +++ b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/instrument/LocalSettingsHelper.java @@ -1,124 +1,133 @@ -package org.obiba.onyx.jade.instrument; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Properties; - -/** - * This helper class allows settings to be persisted locally by the instrument bootstrap mechanism. With this we can - * store a list of parameters for an instrument interface running on a specific machine (ex: communication port), so - * they can retrieved the next time the interface is launched. - * - * Practically, this allows a user to setup an instrument interface the first time it is launched, without having to - * worry about setting it up on each run, because the local configuration is kept on disk, and can be retrieved - * automatically. - */ -public class LocalSettingsHelper { - - // The name of the file in which the settings will be saved. - private String settingsFileName; - - // A comment which is included at the top of the file, describing its content. - private String settingsFileComment; - - private static String SETTINGS_DIR = System.getProperty("user.home") + File.separatorChar + ".jade"; - - /** - * Saves the settings to disk. - * - * @param settings A property object containing the settings to be saved. - * @throws CouldNotSaveSettingsException - */ - public void saveSettings(Properties settings) throws CouldNotSaveSettingsException { - - File settingsDir = new File(SETTINGS_DIR); - if(!settingsDir.exists()) { - (new File(SETTINGS_DIR)).mkdir(); - } - - try { - OutputStream os = new FileOutputStream(new File(SETTINGS_DIR, settingsFileName)); - settings.store(os, settingsFileComment); - os.close(); - } catch(IOException couldNotPersistSettingsToLocalFile) { - throw new CouldNotSaveSettingsException(couldNotPersistSettingsToLocalFile); - } - - } - - /** - * Retrieves the setting stored on disk. - * - * @return A property containing the settings retrieved from disk. - * @throws CouldNotRetrieveSettingsException - */ - public Properties retrieveSettings() throws CouldNotRetrieveSettingsException { - - InputStream is; - Properties settings = new Properties(); - try { - is = new FileInputStream(new File(SETTINGS_DIR, settingsFileName)); - - try { - settings.load(is); - } catch(IOException cannotReadSettingsFile) { - throw new CouldNotRetrieveSettingsException(cannotReadSettingsFile); - } - } catch(FileNotFoundException settingsFileDontExist) { - throw new CouldNotRetrieveSettingsException(settingsFileDontExist); - } - - try { - if(is != null) { - is.close(); - } - } catch(Exception e) { - // Ignore - } - - return settings; - - } - - public class CouldNotRetrieveSettingsException extends Exception { - - private static final long serialVersionUID = 1L; - - public CouldNotRetrieveSettingsException(Throwable exception) { - super(exception); - } - - } - - public class CouldNotSaveSettingsException extends Exception { - - private static final long serialVersionUID = 1L; - - public CouldNotSaveSettingsException(Throwable exception) { - super(exception); - } - - } - - public String getSettingsFileName() { - return settingsFileName; - } - - public void setSettingsFileName(String settingsFileName) { - this.settingsFileName = settingsFileName; - } - - public String getSettingsFileComment() { - return settingsFileComment; - } - - public void setSettingsFileComment(String settingsFileComment) { - this.settingsFileComment = settingsFileComment; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Properties; + +/** + * This helper class allows settings to be persisted locally by the instrument bootstrap mechanism. With this we can + * store a list of parameters for an instrument interface running on a specific machine (ex: communication port), so + * they can retrieved the next time the interface is launched. + * + * Practically, this allows a user to setup an instrument interface the first time it is launched, without having to + * worry about setting it up on each run, because the local configuration is kept on disk, and can be retrieved + * automatically. + */ +public class LocalSettingsHelper { + + // The name of the file in which the settings will be saved. + private String settingsFileName; + + // A comment which is included at the top of the file, describing its content. + private String settingsFileComment; + + private static String SETTINGS_DIR = System.getProperty("user.home") + File.separatorChar + ".jade"; + + /** + * Saves the settings to disk. + * + * @param settings A property object containing the settings to be saved. + * @throws CouldNotSaveSettingsException + */ + public void saveSettings(Properties settings) throws CouldNotSaveSettingsException { + + File settingsDir = new File(SETTINGS_DIR); + if(!settingsDir.exists()) { + (new File(SETTINGS_DIR)).mkdir(); + } + + try { + OutputStream os = new FileOutputStream(new File(SETTINGS_DIR, settingsFileName)); + settings.store(os, settingsFileComment); + os.close(); + } catch(IOException couldNotPersistSettingsToLocalFile) { + throw new CouldNotSaveSettingsException(couldNotPersistSettingsToLocalFile); + } + + } + + /** + * Retrieves the setting stored on disk. + * + * @return A property containing the settings retrieved from disk. + * @throws CouldNotRetrieveSettingsException + */ + public Properties retrieveSettings() throws CouldNotRetrieveSettingsException { + + InputStream is; + Properties settings = new Properties(); + try { + is = new FileInputStream(new File(SETTINGS_DIR, settingsFileName)); + + try { + settings.load(is); + } catch(IOException cannotReadSettingsFile) { + throw new CouldNotRetrieveSettingsException(cannotReadSettingsFile); + } + } catch(FileNotFoundException settingsFileDontExist) { + throw new CouldNotRetrieveSettingsException(settingsFileDontExist); + } + + try { + if(is != null) { + is.close(); + } + } catch(Exception e) { + // Ignore + } + + return settings; + + } + + public class CouldNotRetrieveSettingsException extends Exception { + + private static final long serialVersionUID = 1L; + + public CouldNotRetrieveSettingsException(Throwable exception) { + super(exception); + } + + } + + public class CouldNotSaveSettingsException extends Exception { + + private static final long serialVersionUID = 1L; + + public CouldNotSaveSettingsException(Throwable exception) { + super(exception); + } + + } + + public String getSettingsFileName() { + return settingsFileName; + } + + public void setSettingsFileName(String settingsFileName) { + this.settingsFileName = settingsFileName; + } + + public String getSettingsFileComment() { + return settingsFileComment; + } + + public void setSettingsFileComment(String settingsFileComment) { + this.settingsFileComment = settingsFileComment; + } + +} diff --git a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/util/FileUtil.java b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/util/FileUtil.java index 60548b777..8495f41b2 100644 --- a/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/util/FileUtil.java +++ b/onyx-modules/jade/instrument-bootstrap/src/main/java/org/obiba/onyx/jade/util/FileUtil.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.util; import java.io.BufferedReader; diff --git a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunner.java index 2100e4bdb..73bb143f1 100644 --- a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunner.java @@ -1,221 +1,230 @@ -package org.obiba.onyx.jade.instrument.atcor; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.InstrumentRunner; -import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SphygmoCorInstrumentRunner implements InstrumentRunner { - - // - // Constants - // - - private static final Logger log = LoggerFactory.getLogger(SphygmoCorInstrumentRunner.class); - - // - // Instance variables - // - - private ExternalAppLauncherHelper externalAppHelper; - - private InstrumentExecutionService instrumentExecutionService; - - private SphygmoCorDao sphygmoCorDao; - - private String participantLastName; - - private String participantFirstName; - - private Date participantBirthDate; - - private String participantGender; - - private Long systolicPressure; - - private Long diastolicPressure; - - // - // Methods - // - - public void initialize() { - // First, remove any data (patients and measurements) currently in the AtCor database. - sphygmoCorDao.deleteAllOutput(); - sphygmoCorDao.deleteAllPatients(); - - // Fetch the current participant's data. - participantLastName = instrumentExecutionService.getParticipantLastName(); - participantFirstName = instrumentExecutionService.getParticipantFirstName(); - participantBirthDate = instrumentExecutionService.getParticipantBirthDate(); - participantGender = instrumentExecutionService.getParticipantGender(); - - systolicPressure = instrumentExecutionService.getInputParameterValue("SystolicPressure").getValue(); - diastolicPressure = instrumentExecutionService.getInputParameterValue("DiastolicPressure").getValue(); - - writeSphygmoCorInputFile(); - - } - - private void writeSphygmoCorInputFile() { - BufferedWriter localInputFile = null; - try { - localInputFile = new BufferedWriter(new FileWriter(externalAppHelper.getWorkDir() + File.separator + "patient.txt")); - localInputFile.write(participantLastName + "\n"); - localInputFile.write(participantFirstName + "\n"); - - SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); - localInputFile.write(formatter.format(participantBirthDate) + "\n"); - - localInputFile.write(participantGender + "\n"); - localInputFile.write(instrumentExecutionService.getParticipantID() + "\n"); - localInputFile.write(systolicPressure + "\n"); - localInputFile.write(diastolicPressure + "\n"); - } catch(IOException e) { - log.error("Could not write input file!"); - throw new RuntimeException(e); - } finally { - try { - localInputFile.close(); - } catch(Exception e) { - } - } - } - - public void run() { - log.info("*** Running SphygmoCor Runner ***"); - - // Launch the SphygmoCor software. - externalAppHelper.launch(); - - // Retrieve the output (measurements taken for the current participant). - // NOTE: The getOutput method returns the output as a List of Maps. There - // *should* only be one Map, corresponding to the single run. - List output = sphygmoCorDao.getOutput(Integer.parseInt(instrumentExecutionService.getParticipantID())); - - if(output != null) { - // Send the data to the server. - if(output.size() > 1) { - log.warn("Multiple device outputs found; sending first one"); - sendDataToServer((Map) output.get(0)); - } - - sendDataToServer((Map) output.get(0)); - - } else { - String errMsg = "No device output found"; - log.error(errMsg); - - throw new RuntimeException(errMsg); - } - } - - public void shutdown() { - log.info("*** Shutdown SphygmoCor Runner ***"); - - // Delete locally stored participant data. - sphygmoCorDao.deleteAllOutput(); - sphygmoCorDao.deleteAllPatients(); - } - - private void sendDataToServer(Map data) { - - Map outputToSend = new HashMap(); - - outputToSend.put("Participant Barcode", DataBuilder.buildText((String) data.get("PATIENT_ID"))); - outputToSend.put("Participant First Name", DataBuilder.buildText((String) data.get("FIRST_NAME"))); - outputToSend.put("Participant Last Name", DataBuilder.buildText((String) data.get("FAM_NAME"))); - outputToSend.put("Participant Date of Birth", DataBuilder.buildDate((Date)data.get("DOB"))); - outputToSend.put("Participant Gender", DataBuilder.buildText((String) data.get("SEX"))); - outputToSend.put("Systolic Pressure", DataBuilder.buildInteger(((Float)data.get("SP")).longValue())); - outputToSend.put("Diastolic Pressure", DataBuilder.buildInteger(((Float) data.get("DP")).longValue())); - - outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Height", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PH")))); - outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Height_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PHV")))); - outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Length_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PLV")))); - outputToSend.put("Peripheral_Pulse_Quality_Control_Diastolic_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_DV")))); - outputToSend.put("Peripheral_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_SP")))); - outputToSend.put("Peripheral_Diastolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_DP")))); - outputToSend.put("Peripheral_Mean_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_MEANP")))); - outputToSend.put("Peripheral_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("P_T1")))); - outputToSend.put("Peripheral_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("P_T2")))); - outputToSend.put("Peripheral_Augmentation_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("P_AI")))); - outputToSend.put("End_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_ESP")))); - outputToSend.put("Peripheral_P1", new Data(DataType.DECIMAL, new Double((Float) data.get("P_P1")))); - outputToSend.put("Peripheral_P2", new Data(DataType.DECIMAL, new Double((Float) data.get("P_P2")))); - outputToSend.put("Peripheral_Confidence_Level_of_T1", new Data(DataType.INTEGER, new Long((Integer) data.get("P_QUALITY_T1")))); - outputToSend.put("Peripheral_Confidence_Level_of_T2", new Data(DataType.INTEGER, new Long((Integer) data.get("P_QUALITY_T2")))); - outputToSend.put("Central_Augmented_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AP")))); - outputToSend.put("Central_Mean_Pressure_of_Systole", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MPS")))); - outputToSend.put("Central_Mean_Pressure_of_Diastole", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MPD")))); - outputToSend.put("Central_Tension_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_TTI")))); - outputToSend.put("Central_Diastolic_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DTI")))); - outputToSend.put("Central_Buckberg_SubEndocardial_Viability_Ratio", new Data(DataType.DECIMAL, new Double((Float) data.get("C_SVI")))); - outputToSend.put("Augmentation_Load", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AL")))); - outputToSend.put("Augmentation_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ATI")))); - outputToSend.put("Heart_Rate", new Data(DataType.DECIMAL, new Double((Float) data.get("HR")))); - outputToSend.put("Central_Pulse_Period", new Data(DataType.DECIMAL, new Double((Float) data.get("C_PERIOD")))); - outputToSend.put("Central_Diastolic_Duration", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DD")))); - outputToSend.put("Central_ED_Period_Percent_Ejection_duration", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ED_PERIOD")))); - outputToSend.put("Period_ED_Period_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DD_PERIOD")))); - outputToSend.put("Central_Pulse_Height", new Data(DataType.DECIMAL, new Double((Float) data.get("C_PH")))); - outputToSend.put("Central_Aug_PH_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AGPH")))); - outputToSend.put("Central_Pressure_at_T1_Dp", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P1_HEIGHT")))); - outputToSend.put("Time_of_the_Start_of_the_Reflected_Wave", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1R")))); - outputToSend.put("Central_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_SP")))); - outputToSend.put("Central_Diastolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DP")))); - outputToSend.put("Central_Mean_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MEANP")))); - outputToSend.put("Central_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1")))); - outputToSend.put("Central_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T2")))); - outputToSend.put("Central_Augmentation_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AI")))); - outputToSend.put("Central_End_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ESP")))); - outputToSend.put("Central_Pressure_at_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P1")))); - outputToSend.put("Central_Pressure_at_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P2")))); - outputToSend.put("Central_T1_ED_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1ED")))); - outputToSend.put("Central_T2_ED_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T2ED")))); - outputToSend.put("Central_Confidence_Level_of_T1", new Data(DataType.INTEGER, new Long((Integer) data.get("C_QUALITY_T1")))); - outputToSend.put("Central_Confidence_Level_of_T2", new Data(DataType.INTEGER, new Long((Integer) data.get("C_QUALITY_T2")))); - outputToSend.put("Operator_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_OTHER4")))); - - instrumentExecutionService.addOutputParameterValues(outputToSend); - } - - public ExternalAppLauncherHelper getExternalAppHelper() { - return externalAppHelper; - } - - public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { - this.externalAppHelper = externalAppHelper; - } - - public InstrumentExecutionService getInstrumentExecutionService() { - return instrumentExecutionService; - } - - public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { - this.instrumentExecutionService = instrumentExecutionService; - } - - public SphygmoCorDao getSphygmoCorDao() { - return sphygmoCorDao; - } - - public void setSphygmoCorDao(SphygmoCorDao sphygmoCorDao) { - this.sphygmoCorDao = sphygmoCorDao; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.atcor; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.InstrumentRunner; +import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SphygmoCorInstrumentRunner implements InstrumentRunner { + + // + // Constants + // + + private static final Logger log = LoggerFactory.getLogger(SphygmoCorInstrumentRunner.class); + + // + // Instance variables + // + + private ExternalAppLauncherHelper externalAppHelper; + + private InstrumentExecutionService instrumentExecutionService; + + private SphygmoCorDao sphygmoCorDao; + + private String participantLastName; + + private String participantFirstName; + + private Date participantBirthDate; + + private String participantGender; + + private Long systolicPressure; + + private Long diastolicPressure; + + // + // Methods + // + + public void initialize() { + // First, remove any data (patients and measurements) currently in the AtCor database. + sphygmoCorDao.deleteAllOutput(); + sphygmoCorDao.deleteAllPatients(); + + // Fetch the current participant's data. + participantLastName = instrumentExecutionService.getParticipantLastName(); + participantFirstName = instrumentExecutionService.getParticipantFirstName(); + participantBirthDate = instrumentExecutionService.getParticipantBirthDate(); + participantGender = instrumentExecutionService.getParticipantGender(); + + systolicPressure = instrumentExecutionService.getInputParameterValue("SystolicPressure").getValue(); + diastolicPressure = instrumentExecutionService.getInputParameterValue("DiastolicPressure").getValue(); + + writeSphygmoCorInputFile(); + + } + + private void writeSphygmoCorInputFile() { + BufferedWriter localInputFile = null; + try { + localInputFile = new BufferedWriter(new FileWriter(externalAppHelper.getWorkDir() + File.separator + "patient.txt")); + localInputFile.write(participantLastName + "\n"); + localInputFile.write(participantFirstName + "\n"); + + SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + localInputFile.write(formatter.format(participantBirthDate) + "\n"); + + localInputFile.write(participantGender + "\n"); + localInputFile.write(instrumentExecutionService.getParticipantID() + "\n"); + localInputFile.write(systolicPressure + "\n"); + localInputFile.write(diastolicPressure + "\n"); + } catch(IOException e) { + log.error("Could not write input file!"); + throw new RuntimeException(e); + } finally { + try { + localInputFile.close(); + } catch(Exception e) { + } + } + } + + public void run() { + log.info("*** Running SphygmoCor Runner ***"); + + // Launch the SphygmoCor software. + externalAppHelper.launch(); + + // Retrieve the output (measurements taken for the current participant). + // NOTE: The getOutput method returns the output as a List of Maps. There + // *should* only be one Map, corresponding to the single run. + List output = sphygmoCorDao.getOutput(Integer.parseInt(instrumentExecutionService.getParticipantID())); + + if(output != null) { + // Send the data to the server. + if(output.size() > 1) { + log.warn("Multiple device outputs found; sending first one"); + sendDataToServer((Map) output.get(0)); + } + + sendDataToServer((Map) output.get(0)); + + } else { + String errMsg = "No device output found"; + log.error(errMsg); + + throw new RuntimeException(errMsg); + } + } + + public void shutdown() { + log.info("*** Shutdown SphygmoCor Runner ***"); + + // Delete locally stored participant data. + sphygmoCorDao.deleteAllOutput(); + sphygmoCorDao.deleteAllPatients(); + } + + private void sendDataToServer(Map data) { + + Map outputToSend = new HashMap(); + + outputToSend.put("Participant Barcode", DataBuilder.buildText((String) data.get("PATIENT_ID"))); + outputToSend.put("Participant First Name", DataBuilder.buildText((String) data.get("FIRST_NAME"))); + outputToSend.put("Participant Last Name", DataBuilder.buildText((String) data.get("FAM_NAME"))); + outputToSend.put("Participant Date of Birth", DataBuilder.buildDate((Date)data.get("DOB"))); + outputToSend.put("Participant Gender", DataBuilder.buildText((String) data.get("SEX"))); + outputToSend.put("Systolic Pressure", DataBuilder.buildInteger(((Float)data.get("SP")).longValue())); + outputToSend.put("Diastolic Pressure", DataBuilder.buildInteger(((Float) data.get("DP")).longValue())); + + outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Height", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PH")))); + outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Height_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PHV")))); + outputToSend.put("Peripheral_Pulse_Quality_Control_Pulse_Length_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_PLV")))); + outputToSend.put("Peripheral_Pulse_Quality_Control_Diastolic_Variation", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_DV")))); + outputToSend.put("Peripheral_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_SP")))); + outputToSend.put("Peripheral_Diastolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_DP")))); + outputToSend.put("Peripheral_Mean_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_MEANP")))); + outputToSend.put("Peripheral_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("P_T1")))); + outputToSend.put("Peripheral_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("P_T2")))); + outputToSend.put("Peripheral_Augmentation_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("P_AI")))); + outputToSend.put("End_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("P_ESP")))); + outputToSend.put("Peripheral_P1", new Data(DataType.DECIMAL, new Double((Float) data.get("P_P1")))); + outputToSend.put("Peripheral_P2", new Data(DataType.DECIMAL, new Double((Float) data.get("P_P2")))); + outputToSend.put("Peripheral_Confidence_Level_of_T1", new Data(DataType.INTEGER, new Long((Integer) data.get("P_QUALITY_T1")))); + outputToSend.put("Peripheral_Confidence_Level_of_T2", new Data(DataType.INTEGER, new Long((Integer) data.get("P_QUALITY_T2")))); + outputToSend.put("Central_Augmented_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AP")))); + outputToSend.put("Central_Mean_Pressure_of_Systole", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MPS")))); + outputToSend.put("Central_Mean_Pressure_of_Diastole", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MPD")))); + outputToSend.put("Central_Tension_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_TTI")))); + outputToSend.put("Central_Diastolic_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DTI")))); + outputToSend.put("Central_Buckberg_SubEndocardial_Viability_Ratio", new Data(DataType.DECIMAL, new Double((Float) data.get("C_SVI")))); + outputToSend.put("Augmentation_Load", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AL")))); + outputToSend.put("Augmentation_Time_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ATI")))); + outputToSend.put("Heart_Rate", new Data(DataType.DECIMAL, new Double((Float) data.get("HR")))); + outputToSend.put("Central_Pulse_Period", new Data(DataType.DECIMAL, new Double((Float) data.get("C_PERIOD")))); + outputToSend.put("Central_Diastolic_Duration", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DD")))); + outputToSend.put("Central_ED_Period_Percent_Ejection_duration", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ED_PERIOD")))); + outputToSend.put("Period_ED_Period_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DD_PERIOD")))); + outputToSend.put("Central_Pulse_Height", new Data(DataType.DECIMAL, new Double((Float) data.get("C_PH")))); + outputToSend.put("Central_Aug_PH_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AGPH")))); + outputToSend.put("Central_Pressure_at_T1_Dp", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P1_HEIGHT")))); + outputToSend.put("Time_of_the_Start_of_the_Reflected_Wave", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1R")))); + outputToSend.put("Central_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_SP")))); + outputToSend.put("Central_Diastolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_DP")))); + outputToSend.put("Central_Mean_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_MEANP")))); + outputToSend.put("Central_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1")))); + outputToSend.put("Central_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T2")))); + outputToSend.put("Central_Augmentation_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("C_AI")))); + outputToSend.put("Central_End_Systolic_Pressure", new Data(DataType.DECIMAL, new Double((Float) data.get("C_ESP")))); + outputToSend.put("Central_Pressure_at_T1", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P1")))); + outputToSend.put("Central_Pressure_at_T2", new Data(DataType.DECIMAL, new Double((Float) data.get("C_P2")))); + outputToSend.put("Central_T1_ED_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T1ED")))); + outputToSend.put("Central_T2_ED_Percent", new Data(DataType.DECIMAL, new Double((Float) data.get("C_T2ED")))); + outputToSend.put("Central_Confidence_Level_of_T1", new Data(DataType.INTEGER, new Long((Integer) data.get("C_QUALITY_T1")))); + outputToSend.put("Central_Confidence_Level_of_T2", new Data(DataType.INTEGER, new Long((Integer) data.get("C_QUALITY_T2")))); + outputToSend.put("Operator_Index", new Data(DataType.DECIMAL, new Double((Float) data.get("P_QC_OTHER4")))); + + instrumentExecutionService.addOutputParameterValues(outputToSend); + } + + public ExternalAppLauncherHelper getExternalAppHelper() { + return externalAppHelper; + } + + public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { + this.externalAppHelper = externalAppHelper; + } + + public InstrumentExecutionService getInstrumentExecutionService() { + return instrumentExecutionService; + } + + public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { + this.instrumentExecutionService = instrumentExecutionService; + } + + public SphygmoCorDao getSphygmoCorDao() { + return sphygmoCorDao; + } + + public void setSphygmoCorDao(SphygmoCorDao sphygmoCorDao) { + this.sphygmoCorDao = sphygmoCorDao; + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/SphygmoCorDao.java b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/SphygmoCorDao.java index 9bae4140c..c348c8320 100644 --- a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/SphygmoCorDao.java +++ b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/SphygmoCorDao.java @@ -1,19 +1,28 @@ -package org.obiba.onyx.jade.instrument.atcor.dao; - -import java.sql.Date; -import java.util.List; - -public interface SphygmoCorDao { - - public void addPatient(String systemId, String studyId, String patientId, int patientNo, String familyName, String firstName, Date birthDate, String gender); - - public void deletePatientById(String patientId); - - public void deletePatientByNumber(int patientNo); - - public void deleteAllPatients(); - - public void deleteAllOutput(); - - public List getOutput(int patientNo); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.atcor.dao; + +import java.sql.Date; +import java.util.List; + +public interface SphygmoCorDao { + + public void addPatient(String systemId, String studyId, String patientId, int patientNo, String familyName, String firstName, Date birthDate, String gender); + + public void deletePatientById(String patientId); + + public void deletePatientByNumber(int patientNo); + + public void deleteAllPatients(); + + public void deleteAllOutput(); + + public List getOutput(int patientNo); +} diff --git a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/impl/JdbcSphygmoCorDao.java b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/impl/JdbcSphygmoCorDao.java index c7b578f47..4e3dedada 100644 --- a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/impl/JdbcSphygmoCorDao.java +++ b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/main/java/org/obiba/onyx/jade/instrument/atcor/dao/impl/JdbcSphygmoCorDao.java @@ -1,112 +1,121 @@ -package org.obiba.onyx.jade.instrument.atcor.dao.impl; - -import java.sql.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.FileSystemXmlApplicationContext; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; - -public class JdbcSphygmoCorDao extends NamedParameterJdbcDaoSupport implements SphygmoCorDao { - - // - // Constants - // - - private static final String INSERT_PATIENT_SQL = "insert into PATIENT (SYSTEM_ID, STUDY_ID, PATIENT_ID, PATIENT_NO, FAM_NAME, FIRST_NAME, DOB, SEX) " + "values (:systemId, :studyId, :patientId, :patientNo, :familyName, :firstName, :birthDate, :gender)"; - - private static final String DELETE_PATIENT_BY_ID_SQL = "delete from PATIENT where PATIENT_ID = :patientId"; - - private static final String DELETE_PATIENT_BY_NUMBER_SQL = "delete from PATIENT where PATIENT_NO = :patientNo"; - - private static final String DELETE_ALL_PATIENTS_SQL = "delete from PATIENT"; - - private static final String DELETE_ALL_OUTPUT_SQL = "delete from M_PWA"; - - private static final String GET_OUTPUT_SQL = "select * from M_PWA, PATIENT where PATIENT_ID = :patientNo and M_PWA.PATIENT_NO = PATIENT.PATIENT_NO"; - - // - // Methods - // - - public void addPatient(String systemId, String studyId, String patientId, int patientNo, String familyName, String firstName, Date birthDate, String gender) { - Map paramMap = new HashMap(); - - paramMap.put("systemId", systemId); - paramMap.put("studyId", studyId); - paramMap.put("patientId", patientId); - paramMap.put("patientNo", patientNo); - paramMap.put("familyName", familyName); - paramMap.put("firstName", firstName); - paramMap.put("birthDate", birthDate); - paramMap.put("gender", gender); - - getNamedParameterJdbcTemplate().update(INSERT_PATIENT_SQL, paramMap); - } - - public void deletePatientById(String patientId) { - Map paramMap = new HashMap(); - - paramMap.put("patientId", patientId); - - getNamedParameterJdbcTemplate().update(DELETE_PATIENT_BY_ID_SQL, paramMap); - } - - public void deletePatientByNumber(int patientNo) { - Map paramMap = new HashMap(); - - paramMap.put("patientNo", patientNo); - - getNamedParameterJdbcTemplate().update(DELETE_PATIENT_BY_NUMBER_SQL, paramMap); - } - - public void deleteAllPatients() { - Map paramMap = new HashMap(); - - getNamedParameterJdbcTemplate().update(DELETE_ALL_PATIENTS_SQL, paramMap); - } - - public void deleteAllOutput() { - Map paramMap = new HashMap(); - - getNamedParameterJdbcTemplate().update(DELETE_ALL_OUTPUT_SQL, paramMap); - } - - public List getOutput(int patientNo) { - Map paramMap = new HashMap(); - paramMap.put("patientNo", patientNo); - - List matches = getNamedParameterJdbcTemplate().queryForList(GET_OUTPUT_SQL, paramMap); - - return matches.size() > 0 ? matches : null; - } - - public static void main(String[] args) throws Exception { - - ApplicationContext appContext = new FileSystemXmlApplicationContext("C:\\eclipse-SDK-3.3.2-win32\\eclipse-workspaces\\onyx\\trunk\\onyx-modules\\jade\\instrument-parent\\interface-arterialstiffness\\src\\main\\resources\\META-INF\\spring\\instrument-context.xml"); - - SphygmoCorDao sphygmoCorDao = (SphygmoCorDao) appContext.getBean("sphygmoCorDao"); - - // sphygmoCorDao.deleteAllOutput(); - // sphygmoCorDao.deleteAllPatients(); - - // sphygmoCorDao.addPatient("01400", "DATA", "4AAA", 1, "Spathis", "Dennis", new java.sql.Date(new - // java.util.Date().getTime()), "MALE".toString()); - // sphygmoCorDao.addPatient("01400", "DATA", "4AAA", 1, "Spathis", "Stella", new java.sql.Date(new - // java.util.Date().getTime()), "FEMALE".toString()); - - List output = sphygmoCorDao.getOutput(1); - - if(output != null) { - System.out.println("Got output!"); - System.out.println("Rows: " + output.size()); - - System.out.println("Row 0..."); - Map firstRow = (Map) output.get(0); - System.out.println("P_QC_PH: " + firstRow.get("P_QC_PH")); - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.atcor.dao.impl; + +import java.sql.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; + +public class JdbcSphygmoCorDao extends NamedParameterJdbcDaoSupport implements SphygmoCorDao { + + // + // Constants + // + + private static final String INSERT_PATIENT_SQL = "insert into PATIENT (SYSTEM_ID, STUDY_ID, PATIENT_ID, PATIENT_NO, FAM_NAME, FIRST_NAME, DOB, SEX) " + "values (:systemId, :studyId, :patientId, :patientNo, :familyName, :firstName, :birthDate, :gender)"; + + private static final String DELETE_PATIENT_BY_ID_SQL = "delete from PATIENT where PATIENT_ID = :patientId"; + + private static final String DELETE_PATIENT_BY_NUMBER_SQL = "delete from PATIENT where PATIENT_NO = :patientNo"; + + private static final String DELETE_ALL_PATIENTS_SQL = "delete from PATIENT"; + + private static final String DELETE_ALL_OUTPUT_SQL = "delete from M_PWA"; + + private static final String GET_OUTPUT_SQL = "select * from M_PWA, PATIENT where PATIENT_ID = :patientNo and M_PWA.PATIENT_NO = PATIENT.PATIENT_NO"; + + // + // Methods + // + + public void addPatient(String systemId, String studyId, String patientId, int patientNo, String familyName, String firstName, Date birthDate, String gender) { + Map paramMap = new HashMap(); + + paramMap.put("systemId", systemId); + paramMap.put("studyId", studyId); + paramMap.put("patientId", patientId); + paramMap.put("patientNo", patientNo); + paramMap.put("familyName", familyName); + paramMap.put("firstName", firstName); + paramMap.put("birthDate", birthDate); + paramMap.put("gender", gender); + + getNamedParameterJdbcTemplate().update(INSERT_PATIENT_SQL, paramMap); + } + + public void deletePatientById(String patientId) { + Map paramMap = new HashMap(); + + paramMap.put("patientId", patientId); + + getNamedParameterJdbcTemplate().update(DELETE_PATIENT_BY_ID_SQL, paramMap); + } + + public void deletePatientByNumber(int patientNo) { + Map paramMap = new HashMap(); + + paramMap.put("patientNo", patientNo); + + getNamedParameterJdbcTemplate().update(DELETE_PATIENT_BY_NUMBER_SQL, paramMap); + } + + public void deleteAllPatients() { + Map paramMap = new HashMap(); + + getNamedParameterJdbcTemplate().update(DELETE_ALL_PATIENTS_SQL, paramMap); + } + + public void deleteAllOutput() { + Map paramMap = new HashMap(); + + getNamedParameterJdbcTemplate().update(DELETE_ALL_OUTPUT_SQL, paramMap); + } + + public List getOutput(int patientNo) { + Map paramMap = new HashMap(); + paramMap.put("patientNo", patientNo); + + List matches = getNamedParameterJdbcTemplate().queryForList(GET_OUTPUT_SQL, paramMap); + + return matches.size() > 0 ? matches : null; + } + + public static void main(String[] args) throws Exception { + + ApplicationContext appContext = new FileSystemXmlApplicationContext("C:\\eclipse-SDK-3.3.2-win32\\eclipse-workspaces\\onyx\\trunk\\onyx-modules\\jade\\instrument-parent\\interface-arterialstiffness\\src\\main\\resources\\META-INF\\spring\\instrument-context.xml"); + + SphygmoCorDao sphygmoCorDao = (SphygmoCorDao) appContext.getBean("sphygmoCorDao"); + + // sphygmoCorDao.deleteAllOutput(); + // sphygmoCorDao.deleteAllPatients(); + + // sphygmoCorDao.addPatient("01400", "DATA", "4AAA", 1, "Spathis", "Dennis", new java.sql.Date(new + // java.util.Date().getTime()), "MALE".toString()); + // sphygmoCorDao.addPatient("01400", "DATA", "4AAA", 1, "Spathis", "Stella", new java.sql.Date(new + // java.util.Date().getTime()), "FEMALE".toString()); + + List output = sphygmoCorDao.getOutput(1); + + if(output != null) { + System.out.println("Got output!"); + System.out.println("Rows: " + output.size()); + + System.out.println("Row 0..."); + Map firstRow = (Map) output.get(0); + System.out.println("P_QC_PH: " + firstRow.get("P_QC_PH")); + } + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/test/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunnerTest.java b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/test/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunnerTest.java index c49f74102..46458504c 100644 --- a/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/test/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunnerTest.java +++ b/onyx-modules/jade/instrument-parent/interface-arterialstiffness-sphygmocor/src/test/java/org/obiba/onyx/jade/instrument/atcor/SphygmoCorInstrumentRunnerTest.java @@ -1,262 +1,271 @@ -package org.obiba.onyx.jade.instrument.atcor; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.fail; - -import java.io.File; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -public class SphygmoCorInstrumentRunnerTest { - - private ExternalAppLauncherHelper externalAppHelper; - - private SphygmoCorInstrumentRunner sphygmoCorInstrumentRunner; - - private SphygmoCorDao sphygmoCorDaoMock; - - private InstrumentExecutionService instrumentExecutionServiceMock; - - @Before - public void setUp() { - sphygmoCorInstrumentRunner = new SphygmoCorInstrumentRunner(); - - // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), - // so for now, use the class itself with the launch method overridden to - // do nothing. - externalAppHelper = new ExternalAppLauncherHelper() { - public void launch() { - // do nothing - } - }; - externalAppHelper.setWorkDir("target"); - - sphygmoCorInstrumentRunner.setExternalAppHelper(externalAppHelper); - - sphygmoCorDaoMock = createMock(SphygmoCorDao.class); - sphygmoCorInstrumentRunner.setSphygmoCorDao(sphygmoCorDaoMock); - - instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); - sphygmoCorInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); - } - - /** - * Test that the initialize method does the following: - * - *

    - *
  • Deletes all instrument data (measurements and patients)
  • - *
  • Fetches the current participant
  • - *
  • Adds the current participant as a patient
  • - *
- */ - @Test - public void testInitialize() { - // Expect that all instrument data are deleted. - sphygmoCorDaoMock.deleteAllOutput(); - sphygmoCorDaoMock.deleteAllPatients(); - - // Expect that the current participant is retrieved... - String participantId = "123456789"; - String participantLastName = "Tremblay"; - String participantFirstName = "Chantal"; - java.util.Date participantBirthDate = getBirthDate(); - String participantGender = "FEMALE"; - long systolicPressure = 123; - long diastolicPressure = 65; - - expect(instrumentExecutionServiceMock.getParticipantID()).andReturn(participantId); - expect(instrumentExecutionServiceMock.getParticipantLastName()).andReturn(participantLastName); - expect(instrumentExecutionServiceMock.getParticipantFirstName()).andReturn(participantFirstName); - expect(instrumentExecutionServiceMock.getParticipantBirthDate()).andReturn(participantBirthDate); - expect(instrumentExecutionServiceMock.getParticipantGender()).andReturn(participantGender); - - expect(instrumentExecutionServiceMock.getInputParameterValue("SystolicPressure")).andReturn(DataBuilder.buildInteger(systolicPressure)); - expect(instrumentExecutionServiceMock.getInputParameterValue("DiastolicPressure")).andReturn(DataBuilder.buildInteger(diastolicPressure)); - - // ...and added as a patient. - //sphygmoCorDaoMock.addPatient(SYSTEM_ID, STUDY_ID, participantId, 1, participantLastName, participantFirstName, new java.sql.Date(participantBirthDate.getTime()), participantGender); - - replay(sphygmoCorDaoMock); - replay(instrumentExecutionServiceMock); - - sphygmoCorInstrumentRunner.initialize(); - - verify(sphygmoCorDaoMock); - verify(instrumentExecutionServiceMock); - } - - /** - * Test the behaviour of the run method, when the instrument's output is - * successfully retrieved (normal case). - */ - //@Test - public void testRunOutputNotNull() { - expect(instrumentExecutionServiceMock.getParticipantID()).andReturn("1"); - - // Expect that the measurements taken for the current participant are retrieved, - // with a non-null return value. - expect(sphygmoCorDaoMock.getOutput(1)).andReturn(getOutput()); - - // Expect that the measurements are sent to the server. - instrumentExecutionServiceMock.addOutputParameterValues(formatOutputForServer(getOutput().get(0))); - - replay(instrumentExecutionServiceMock); - replay(sphygmoCorDaoMock); - - sphygmoCorInstrumentRunner.run(); - - verify(instrumentExecutionServiceMock); - verify(sphygmoCorDaoMock); - } - - /** - * Test the behaviour of the run method, when the instrument's output is - * null (error case). - */ - @Test - public void testRunOutputIsNull() { - - expect(instrumentExecutionServiceMock.getParticipantID()).andReturn("1"); - - // Expect that the measurements taken for the current participant are retrieved, - // with a null return value, and that this results in a RuntimeException. - expect(sphygmoCorDaoMock.getOutput(1)).andReturn(null); - - replay(instrumentExecutionServiceMock); - replay(sphygmoCorDaoMock); - - try { - sphygmoCorInstrumentRunner.run(); - fail("Expected RuntimeException"); - } - catch(RuntimeException ex) { - // expected - } - - verify(sphygmoCorDaoMock); - verify(instrumentExecutionServiceMock); - } - - /** - * Test that the shutdown method deletes all instrument data (measurements - * and patients). - */ - @Test - public void testShutdown() { - sphygmoCorDaoMock.deleteAllOutput(); - sphygmoCorDaoMock.deleteAllPatients(); - - replay(sphygmoCorDaoMock); - - sphygmoCorInstrumentRunner.shutdown(); - - verify(sphygmoCorDaoMock); - } - - private java.util.Date getBirthDate() { - Calendar c = Calendar.getInstance(); - c.set(Calendar.YEAR, 1964); - c.set(Calendar.MONTH, 2); - c.set(Calendar.DAY_OF_MONTH, 12); - - return c.getTime(); - } - - private List getOutput() { - List output = new ArrayList(); - - Map outputMap = new HashMap(); - - outputMap.put("P_QC_PH", new Float(1.0f)); - outputMap.put("P_QC_PHV", new Float(1.0f)); - outputMap.put("P_QC_PLV", new Float(1.0f)); - outputMap.put("P_QC_DV", new Float(1.0f)); - outputMap.put("P_SP", new Float(1.0f)); - outputMap.put("P_DP", new Float(1.0f)); - outputMap.put("P_MEANP", new Float(1.0f)); - outputMap.put("P_T1", new Float(1.0f)); - outputMap.put("P_T2", new Float(1.0f)); - outputMap.put("P_AI", new Float(1.0f)); - outputMap.put("P_ESP", new Float(1.0f)); - outputMap.put("P_P1", new Float(1.0f)); - outputMap.put("P_P2", new Float(1.0f)); - outputMap.put("P_QUALITY_T1", new Integer(1)); - outputMap.put("P_QUALITY_T2", new Integer(1)); - outputMap.put("C_AP", new Float(1.0f)); - outputMap.put("C_MPS", new Float(1.0f)); - outputMap.put("C_MPD", new Float(1.0f)); - outputMap.put("C_TTI", new Float(1.0f)); - outputMap.put("C_DTI", new Float(1.0f)); - outputMap.put("C_SVI", new Float(1.0f)); - outputMap.put("C_AL", new Float(1.0f)); - outputMap.put("C_ATI", new Float(1.0f)); - outputMap.put("HR", new Float(1.0f)); - outputMap.put("C_PERIOD", new Float(1.0f)); - outputMap.put("C_DD", new Float(1.0f)); - outputMap.put("C_ED_PERIOD", new Float(1.0f)); - outputMap.put("C_DD_PERIOD", new Float(1.0f)); - outputMap.put("C_PH", new Float(1.0f)); - outputMap.put("C_AGPH", new Float(1.0f)); - outputMap.put("C_P1_HEIGHT", new Float(1.0f)); - outputMap.put("C_T1R", new Float(1.0f)); - outputMap.put("C_SP", new Float(1.0f)); - outputMap.put("C_DP", new Float(1.0f)); - outputMap.put("C_MEANP", new Float(1.0f)); - outputMap.put("C_T1", new Float(1.0f)); - outputMap.put("C_T2", new Float(1.0f)); - outputMap.put("C_AI", new Float(1.0f)); - outputMap.put("C_ESP", new Float(1.0f)); - outputMap.put("C_P1", new Float(1.0f)); - outputMap.put("C_P2", new Float(1.0f)); - outputMap.put("C_T1ED", new Float(1.0f)); - outputMap.put("C_T2ED", new Float(1.0f)); - outputMap.put("C_QUALITY_T1", new Integer(1)); - outputMap.put("C_QUALITY_T2", new Integer(1)); - outputMap.put("P_QC_OTHER4", new Float(1.0f)); - - output.add(outputMap); - - return output; - } - - private Map formatOutputForServer(Map data) { - Map outputToSend = new HashMap(); - - Iterator dataIter = data.entrySet().iterator(); - - while (dataIter.hasNext()) { - Map.Entry dataEntry = (Map.Entry)dataIter.next(); - - Data dataObj = null; - - Object value = dataEntry.getValue(); - - if (value instanceof Float) { - dataObj = new Data(DataType.DECIMAL, new Double((Float)value)); - } - else if (value instanceof Integer) { - value = new Data(DataType.INTEGER, new Long((Integer)value)); - } - - outputToSend.put((String)dataEntry.getKey(), dataObj); - } - - return outputToSend; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.atcor; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.fail; + +import java.io.File; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.atcor.dao.SphygmoCorDao; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +public class SphygmoCorInstrumentRunnerTest { + + private ExternalAppLauncherHelper externalAppHelper; + + private SphygmoCorInstrumentRunner sphygmoCorInstrumentRunner; + + private SphygmoCorDao sphygmoCorDaoMock; + + private InstrumentExecutionService instrumentExecutionServiceMock; + + @Before + public void setUp() { + sphygmoCorInstrumentRunner = new SphygmoCorInstrumentRunner(); + + // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), + // so for now, use the class itself with the launch method overridden to + // do nothing. + externalAppHelper = new ExternalAppLauncherHelper() { + public void launch() { + // do nothing + } + }; + externalAppHelper.setWorkDir("target"); + + sphygmoCorInstrumentRunner.setExternalAppHelper(externalAppHelper); + + sphygmoCorDaoMock = createMock(SphygmoCorDao.class); + sphygmoCorInstrumentRunner.setSphygmoCorDao(sphygmoCorDaoMock); + + instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); + sphygmoCorInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); + } + + /** + * Test that the initialize method does the following: + * + *
    + *
  • Deletes all instrument data (measurements and patients)
  • + *
  • Fetches the current participant
  • + *
  • Adds the current participant as a patient
  • + *
+ */ + @Test + public void testInitialize() { + // Expect that all instrument data are deleted. + sphygmoCorDaoMock.deleteAllOutput(); + sphygmoCorDaoMock.deleteAllPatients(); + + // Expect that the current participant is retrieved... + String participantId = "123456789"; + String participantLastName = "Tremblay"; + String participantFirstName = "Chantal"; + java.util.Date participantBirthDate = getBirthDate(); + String participantGender = "FEMALE"; + long systolicPressure = 123; + long diastolicPressure = 65; + + expect(instrumentExecutionServiceMock.getParticipantID()).andReturn(participantId); + expect(instrumentExecutionServiceMock.getParticipantLastName()).andReturn(participantLastName); + expect(instrumentExecutionServiceMock.getParticipantFirstName()).andReturn(participantFirstName); + expect(instrumentExecutionServiceMock.getParticipantBirthDate()).andReturn(participantBirthDate); + expect(instrumentExecutionServiceMock.getParticipantGender()).andReturn(participantGender); + + expect(instrumentExecutionServiceMock.getInputParameterValue("SystolicPressure")).andReturn(DataBuilder.buildInteger(systolicPressure)); + expect(instrumentExecutionServiceMock.getInputParameterValue("DiastolicPressure")).andReturn(DataBuilder.buildInteger(diastolicPressure)); + + // ...and added as a patient. + //sphygmoCorDaoMock.addPatient(SYSTEM_ID, STUDY_ID, participantId, 1, participantLastName, participantFirstName, new java.sql.Date(participantBirthDate.getTime()), participantGender); + + replay(sphygmoCorDaoMock); + replay(instrumentExecutionServiceMock); + + sphygmoCorInstrumentRunner.initialize(); + + verify(sphygmoCorDaoMock); + verify(instrumentExecutionServiceMock); + } + + /** + * Test the behaviour of the run method, when the instrument's output is + * successfully retrieved (normal case). + */ + //@Test + public void testRunOutputNotNull() { + expect(instrumentExecutionServiceMock.getParticipantID()).andReturn("1"); + + // Expect that the measurements taken for the current participant are retrieved, + // with a non-null return value. + expect(sphygmoCorDaoMock.getOutput(1)).andReturn(getOutput()); + + // Expect that the measurements are sent to the server. + instrumentExecutionServiceMock.addOutputParameterValues(formatOutputForServer(getOutput().get(0))); + + replay(instrumentExecutionServiceMock); + replay(sphygmoCorDaoMock); + + sphygmoCorInstrumentRunner.run(); + + verify(instrumentExecutionServiceMock); + verify(sphygmoCorDaoMock); + } + + /** + * Test the behaviour of the run method, when the instrument's output is + * null (error case). + */ + @Test + public void testRunOutputIsNull() { + + expect(instrumentExecutionServiceMock.getParticipantID()).andReturn("1"); + + // Expect that the measurements taken for the current participant are retrieved, + // with a null return value, and that this results in a RuntimeException. + expect(sphygmoCorDaoMock.getOutput(1)).andReturn(null); + + replay(instrumentExecutionServiceMock); + replay(sphygmoCorDaoMock); + + try { + sphygmoCorInstrumentRunner.run(); + fail("Expected RuntimeException"); + } + catch(RuntimeException ex) { + // expected + } + + verify(sphygmoCorDaoMock); + verify(instrumentExecutionServiceMock); + } + + /** + * Test that the shutdown method deletes all instrument data (measurements + * and patients). + */ + @Test + public void testShutdown() { + sphygmoCorDaoMock.deleteAllOutput(); + sphygmoCorDaoMock.deleteAllPatients(); + + replay(sphygmoCorDaoMock); + + sphygmoCorInstrumentRunner.shutdown(); + + verify(sphygmoCorDaoMock); + } + + private java.util.Date getBirthDate() { + Calendar c = Calendar.getInstance(); + c.set(Calendar.YEAR, 1964); + c.set(Calendar.MONTH, 2); + c.set(Calendar.DAY_OF_MONTH, 12); + + return c.getTime(); + } + + private List getOutput() { + List output = new ArrayList(); + + Map outputMap = new HashMap(); + + outputMap.put("P_QC_PH", new Float(1.0f)); + outputMap.put("P_QC_PHV", new Float(1.0f)); + outputMap.put("P_QC_PLV", new Float(1.0f)); + outputMap.put("P_QC_DV", new Float(1.0f)); + outputMap.put("P_SP", new Float(1.0f)); + outputMap.put("P_DP", new Float(1.0f)); + outputMap.put("P_MEANP", new Float(1.0f)); + outputMap.put("P_T1", new Float(1.0f)); + outputMap.put("P_T2", new Float(1.0f)); + outputMap.put("P_AI", new Float(1.0f)); + outputMap.put("P_ESP", new Float(1.0f)); + outputMap.put("P_P1", new Float(1.0f)); + outputMap.put("P_P2", new Float(1.0f)); + outputMap.put("P_QUALITY_T1", new Integer(1)); + outputMap.put("P_QUALITY_T2", new Integer(1)); + outputMap.put("C_AP", new Float(1.0f)); + outputMap.put("C_MPS", new Float(1.0f)); + outputMap.put("C_MPD", new Float(1.0f)); + outputMap.put("C_TTI", new Float(1.0f)); + outputMap.put("C_DTI", new Float(1.0f)); + outputMap.put("C_SVI", new Float(1.0f)); + outputMap.put("C_AL", new Float(1.0f)); + outputMap.put("C_ATI", new Float(1.0f)); + outputMap.put("HR", new Float(1.0f)); + outputMap.put("C_PERIOD", new Float(1.0f)); + outputMap.put("C_DD", new Float(1.0f)); + outputMap.put("C_ED_PERIOD", new Float(1.0f)); + outputMap.put("C_DD_PERIOD", new Float(1.0f)); + outputMap.put("C_PH", new Float(1.0f)); + outputMap.put("C_AGPH", new Float(1.0f)); + outputMap.put("C_P1_HEIGHT", new Float(1.0f)); + outputMap.put("C_T1R", new Float(1.0f)); + outputMap.put("C_SP", new Float(1.0f)); + outputMap.put("C_DP", new Float(1.0f)); + outputMap.put("C_MEANP", new Float(1.0f)); + outputMap.put("C_T1", new Float(1.0f)); + outputMap.put("C_T2", new Float(1.0f)); + outputMap.put("C_AI", new Float(1.0f)); + outputMap.put("C_ESP", new Float(1.0f)); + outputMap.put("C_P1", new Float(1.0f)); + outputMap.put("C_P2", new Float(1.0f)); + outputMap.put("C_T1ED", new Float(1.0f)); + outputMap.put("C_T2ED", new Float(1.0f)); + outputMap.put("C_QUALITY_T1", new Integer(1)); + outputMap.put("C_QUALITY_T2", new Integer(1)); + outputMap.put("P_QC_OTHER4", new Float(1.0f)); + + output.add(outputMap); + + return output; + } + + private Map formatOutputForServer(Map data) { + Map outputToSend = new HashMap(); + + Iterator dataIter = data.entrySet().iterator(); + + while (dataIter.hasNext()) { + Map.Entry dataEntry = (Map.Entry)dataIter.next(); + + Data dataObj = null; + + Object value = dataEntry.getValue(); + + if (value instanceof Float) { + dataObj = new Data(DataType.DECIMAL, new Double((Float)value)); + } + else if (value instanceof Integer) { + value = new Data(DataType.INTEGER, new Long((Integer)value)); + } + + outputToSend.put((String)dataEntry.getKey(), dataObj); + } + + return outputToSend; + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Bc418InstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Bc418InstrumentRunner.java index 9dbf55e66..cbdcdb7b8 100644 --- a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Bc418InstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Bc418InstrumentRunner.java @@ -1,478 +1,487 @@ -package org.obiba.onyx.jade.instrument.tanita; - -import gnu.io.CommPortIdentifier; -import gnu.io.SerialPort; -import gnu.io.SerialPortEvent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.TooManyListenersException; - -import javax.swing.JOptionPane; -import javax.swing.JTextField; - -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.LoggerFactory; - -/** - * This is a simple Swing application that connects to a bioimpedance and weight device (Tanita Body Composition - * Analyzer). It allows the data to be inputed and retrieved automatically through the serial port of the device. - * - * @author mbelhiah - * - */ -public class Bc418InstrumentRunner extends TanitaInstrument { - - // Interface components - protected JTextField dateTxt; - - protected JTextField timeTxt; - - protected JTextField rLegImpedanceTxt; - - protected JTextField lLegImpedanceTxt; - - protected JTextField rArmImpedanceTxt; - - protected JTextField lArmImpedanceTxt; - - protected JTextField rLegFatPctTxt; - - protected JTextField rLegFatMassTxt; - - protected JTextField rLegFfmTxt; - - protected JTextField rLegPredictedMuscleMassTxt; - - protected JTextField lLegFatPctTxt; - - protected JTextField lLegFatMassTxt; - - protected JTextField lLegFfmTxt; - - protected JTextField lLegPredictedMuscleMassTxt; - - protected JTextField rArmFatPctTxt; - - protected JTextField rArmFatMassTxt; - - protected JTextField rArmFfmTxt; - - protected JTextField rArmPredictedMuscleMassTxt; - - protected JTextField lArmFatPctTxt; - - protected JTextField lArmFatMassTxt; - - protected JTextField lArmFfmTxt; - - protected JTextField lArmPredictedMuscleMassTxt; - - protected JTextField trunkFatPctTxt; - - protected JTextField trunkFatMassTxt; - - protected JTextField trunkFfmTxt; - - protected JTextField trunkPredictedMuscleMassTxt; - - private BufferedReader bufferedReader; - - public Bc418InstrumentRunner() throws Exception { - - super(); - - log = LoggerFactory.getLogger(Bc418InstrumentRunner.class); - - // Initialize interface components. - dateTxt = new ResultTextField(); - timeTxt = new ResultTextField(); - - rLegImpedanceTxt = new ResultTextField(); - lLegImpedanceTxt = new ResultTextField(); - rArmImpedanceTxt = new ResultTextField(); - lArmImpedanceTxt = new ResultTextField(); - - rLegFatPctTxt = new ResultTextField(); - rLegFatMassTxt = new ResultTextField(); - rLegFfmTxt = new ResultTextField(); - rLegPredictedMuscleMassTxt = new ResultTextField(); - - lLegFatPctTxt = new ResultTextField(); - lLegFatMassTxt = new ResultTextField(); - lLegFfmTxt = new ResultTextField(); - lLegPredictedMuscleMassTxt = new ResultTextField(); - - rArmFatPctTxt = new ResultTextField(); - rArmFatMassTxt = new ResultTextField(); - rArmFfmTxt = new ResultTextField(); - rArmPredictedMuscleMassTxt = new ResultTextField(); - - lArmFatPctTxt = new ResultTextField(); - lArmFatMassTxt = new ResultTextField(); - lArmFfmTxt = new ResultTextField(); - lArmPredictedMuscleMassTxt = new ResultTextField(); - - trunkFatPctTxt = new ResultTextField(); - trunkFatMassTxt = new ResultTextField(); - trunkFfmTxt = new ResultTextField(); - trunkPredictedMuscleMassTxt = new ResultTextField(); - - } - - /** - * Establish the connection with the device connected to the serial port. - */ - protected void setupSerialPort() { - - try { - // If port already open, close it. - if(serialPort != null) { - serialPort.close(); - serialPort = null; - } - - // Initialize serial port attributes. - log.info("Fetching communication port {}", getTanitaCommPort()); - CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort()); - - log.info("Opening communication port {}", getTanitaCommPort()); - serialPort = (SerialPort) wPortId.open(portOwnerName, 2000); - - // Set serial port parameters. - serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity); - - portIsAvailable = true; - } catch(Exception wCouldNotAccessSerialPort) { - portIsAvailable = false; - log.warn("Could not access the specified serial port.", wCouldNotAccessSerialPort); - } - } - - /** - * Handles any serial port events from the Tanita. - * - * @param pTanitaOutput The serial port event. - */ - public void serialEvent(SerialPortEvent pEvent) { - - switch(pEvent.getEventType()) { - - // Data is available at the serial port, so read it... - case SerialPortEvent.DATA_AVAILABLE: - - try { - if(bufferedReader.ready()){ - // Parse and sets the data in the GUI. - String wResponse = bufferedReader.readLine().trim(); - setTanitaData(parseTanitaData(wResponse)); - - // Enable save button, so data can be saved. - saveDataBtn.setEnabled(true); - } - } - catch(IOException wErrorReadingDataOnSerialPort) { - JOptionPane.showMessageDialog(appWindow, tanitaResourceBundle.getString("Err.Result_communication"), tanitaResourceBundle.getString("Title.Communication_error"), JOptionPane.ERROR_MESSAGE); - } - break; - } - } - - /** - * Retrieve participant data from the database and transfer them to the bioimpedance device - * @throws IOException - * @throws Exception - */ - private void initParticipantData() { - - Map inputData = instrumentExecutionService.getInputParametersValue("ClothesWeight", "Gender", "BodyType", "Height", "Age"); - - try { - bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); - } catch(IOException e) { - throw new RuntimeException("Cannot open serial port on BC-418", e); - } - - try { - String wUnitsOfMeasure = "U0\r\n"; - - String wClothesWeight = "D0001.0\r\n"; - - String wGender = null; - if(inputData.get("Gender").getValueAsString().equals("MALE")) { - wGender = "D11\r\n"; - } else { - if(inputData.get("Gender").getValueAsString().equals("FEMALE")) { - wGender = "D12\r\n"; - } - } - - String wBodyType = null; - if(inputData.get("BodyType").getValueAsString().equals("STANDARD")) { - wBodyType = "D20\r\n"; - } else { - if(inputData.get("BodyType").getValueAsString().equals("ATHLETIC")) { - wBodyType = "D22\r\n"; - } - } - - String wHeight = null; - Float inputHeight = Float.parseFloat(inputData.get("Height").getValueAsString()); - - if(inputHeight.intValue() < 100) { - wHeight = "D3000" + inputData.get("Height") + "\r\n"; - } else { - if(inputHeight.intValue() >= 100) { - wHeight = "D300" + inputHeight.intValue() + "\r\n"; - } - } - - String wAge; - wAge = "D4" + inputData.get("Age").getValueAsString() + "\r\n"; - - // Send commands and receives response - - // Send the units of measurement - String wResponse = null; - wResponse = sendReceive(wUnitsOfMeasure); - - if(!wResponse.equals("U0")) { - throw new RuntimeException("Error when setting units of measurement"); - } - - // Send tare weight - wResponse = sendReceive(wClothesWeight); - if(!wResponse.equals("D0")) { - throw new RuntimeException("Error when setting tare weight"); - } - - // Send gender - wResponse = sendReceive(wGender); - if(!wResponse.equals("D1")) { - throw new RuntimeException("Error when setting gender"); - } - - // Send body type - wResponse = sendReceive(wBodyType); - if(!wResponse.equals("D2")) { - throw new RuntimeException("Error when setting body type"); - } - - // Send height - wResponse = sendReceive(wHeight); - if(!wResponse.equals("D3")) { - throw new RuntimeException("Error when setting height"); - } - - // Send age - wResponse = sendReceive(wAge); - if(!wResponse.equals("D4")) { - throw new RuntimeException("Error when setting age"); - } - - // Start measurement - wResponse = sendReceive("G1\r\n"); - if(!wResponse.equals("G1")) { - throw new RuntimeException("Error when setting input parameters"); - } - } catch(Exception ex) { - throw new RuntimeException("Error initializing TANITA-BC418 input parameters: ", ex); - } - } - - public void initialize() { - super.initialize(); - initParticipantData(); - } - - public void run() { - if(!externalAppHelper.isSotfwareAlreadyStarted("tanitaInstrumentRunner")) { - - log.info("Starting Tanita BC-418 GUI"); - buildGUI(); - - try { - serialPort.addEventListener(this); - } - catch(TooManyListenersException e) { - throw new RuntimeException(e); - } - serialPort.notifyOnDataAvailable(true); - - // Obtain the lock outside the UI thread. This will block until the - // UI releases the lock, at which point it should - // be safe to exit the main thread. - - synchronized(uiLock) { - try { - uiLock.wait(); - } catch(InterruptedException e) { - throw new RuntimeException(e); - } - } - log.info("Lock obtained. Exiting software."); - } - else { - JOptionPane.showMessageDialog(null, tanitaResourceBundle.getString("Err.Application_lock"), tanitaResourceBundle.getString("Title.Cannot_start_application"), JOptionPane.ERROR_MESSAGE); - } - } - - /** - * Send receive. - */ - private String sendReceive(String pCommand) { - - String wResponse = null; - - try { - if(pCommand != null) { - - outputStream = serialPort.getOutputStream(); - // Send parameter - outputStream.write(pCommand.getBytes()); - log.info("Sending data:{}", pCommand); - } - } catch(IOException e) { - throw new RuntimeException("Error when sending data to device", e); - } - - // Read response - try { - wResponse = bufferedReader.readLine().trim(); - log.info("Receiving response:{}", wResponse); - } catch(IOException e) { - throw new RuntimeException("Error when receiving data from device", e); - } - - return wResponse; - } - - /** - * Sets the Bioimpedance data in the GUI components. - * - * @param pOutputData The parsed output data from the Tanita. - * @throws ParseException - */ - protected void setTanitaData(String[] pOutputData) { - - dateTxt.setText(pOutputData[0]); - timeTxt.setText(pOutputData[1]); - - String wBodyTypeCode = pOutputData[2]; - if(wBodyTypeCode.endsWith("0")) { - bodyTypeTxt.setText("STANDARD"); - } else if(wBodyTypeCode.endsWith("2")) { - bodyTypeTxt.setText("ATHLETIC"); - } - - String wGender = pOutputData[3]; - if(wGender.equals("1")) { - genderTxt.setText("MALE"); - } else if(wGender.equals("2")) { - genderTxt.setText("FEMALE"); - } - - heightTxt.setText(pOutputData[4]); - weightTxt.setText(pOutputData[5]); - fatPctTxt.setText(pOutputData[6]); - fatMassTxt.setText(pOutputData[7]); - ffmTxt.setText(pOutputData[8]); - tbwTxt.setText(pOutputData[9]); - ageTxt.setText(pOutputData[10]); - bmiTxt.setText(pOutputData[11]); - bmrTxt.setText(pOutputData[12]); - - impedanceTxt.setText(pOutputData[13]); - rLegImpedanceTxt.setText(pOutputData[14]); - lLegImpedanceTxt.setText(pOutputData[15]); - rArmImpedanceTxt.setText(pOutputData[16]); - lArmImpedanceTxt.setText(pOutputData[17]); - - rLegFatPctTxt.setText(pOutputData[18]); - rLegFatMassTxt.setText(pOutputData[19]); - rLegFfmTxt.setText(pOutputData[20]); - rLegPredictedMuscleMassTxt.setText(pOutputData[21]); - - lLegFatPctTxt.setText(pOutputData[22]); - lLegFatMassTxt.setText(pOutputData[23]); - lLegFfmTxt.setText(pOutputData[24]); - lLegPredictedMuscleMassTxt.setText(pOutputData[25]); - - rArmFatPctTxt.setText(pOutputData[26]); - rArmFatMassTxt.setText(pOutputData[27]); - rArmFfmTxt.setText(pOutputData[28]); - rArmPredictedMuscleMassTxt.setText(pOutputData[29]); - - lArmFatPctTxt.setText(pOutputData[30]); - lArmFatMassTxt.setText(pOutputData[31]); - lArmFfmTxt.setText(pOutputData[32]); - lArmPredictedMuscleMassTxt.setText(pOutputData[33]); - - trunkFatPctTxt.setText(pOutputData[34]); - trunkFatMassTxt.setText(pOutputData[35]); - trunkFfmTxt.setText(pOutputData[36]); - trunkPredictedMuscleMassTxt.setText(pOutputData[37]); - - } - - protected void sendOutputToServer() { - log.info("Sending output of Tanita BC-418 to server..."); - - Map output = new HashMap(); - - output.put("BodyType", new Data(DataType.TEXT, bodyTypeTxt.getText())); - output.put("Weight", getDecimalValue(weightTxt)); - output.put("Impedance", getIntegerValue(impedanceTxt)); - output.put("BMI", getDecimalValue(bmiTxt)); - output.put("BMR", getIntegerValue(bmrTxt)); - output.put("FatFreeMass", getDecimalValue(ffmTxt)); - output.put("FatMass", getDecimalValue(fatMassTxt)); - output.put("TotalBodyWater", getDecimalValue(tbwTxt)); - output.put("FatPercentage", getDecimalValue(fatPctTxt)); - output.put("Gender", new Data(DataType.TEXT, genderTxt.getText())); - output.put("Height", getDecimalValue(heightTxt)); - output.put("Age", getIntegerValue(ageTxt)); - - output.put("Date", new Data(DataType.TEXT, dateTxt.getText())); - output.put("Time", new Data(DataType.TEXT, timeTxt.getText())); - - output.put("RightLegImpedance", getIntegerValue(rLegImpedanceTxt)); - output.put("LeftLegImpedance", getIntegerValue(lLegImpedanceTxt)); - output.put("RightArmImpedance", getIntegerValue(rArmImpedanceTxt)); - output.put("LeftArmImpedance", getIntegerValue(lArmImpedanceTxt)); - - output.put("RightLegFatPercentage", getDecimalValue(rLegFatPctTxt)); - output.put("RightLegFatMass", getDecimalValue(rLegFatMassTxt)); - output.put("RightLegFatFreeMass", getDecimalValue(rLegFfmTxt)); - output.put("RightLegPredictedMuscleMass", getDecimalValue(rLegPredictedMuscleMassTxt)); - - output.put("LeftLegFatPercentage", getDecimalValue(lLegFatPctTxt)); - output.put("LeftLegFatMass", getDecimalValue(lLegFatMassTxt)); - output.put("LeftLegFatFreeMass", getDecimalValue(lLegFfmTxt)); - output.put("LeftLegPredictedMuscleMass", getDecimalValue(lLegPredictedMuscleMassTxt)); - - output.put("RightArmFatPercentage", getDecimalValue(rArmFatPctTxt)); - output.put("RightArmFatMass", getDecimalValue(rArmFatMassTxt)); - output.put("RightArmFatFreeMass", getDecimalValue(rArmFfmTxt)); - output.put("RightArmPredictedMuscleMass", getDecimalValue(rArmPredictedMuscleMassTxt)); - - output.put("LeftArmFatPercentage", getDecimalValue(lArmFatPctTxt)); - output.put("LeftArmFatMass", getDecimalValue(lArmFatMassTxt)); - output.put("LeftArmFatFreeMass", getDecimalValue(lArmFfmTxt)); - output.put("LeftArmPredictedMuscleMass", getDecimalValue(lArmPredictedMuscleMassTxt)); - - output.put("TrunkFatPercentage", getDecimalValue(trunkFatPctTxt)); - output.put("TrunkFatMass", getDecimalValue(trunkFatMassTxt)); - output.put("TrunkFatFreeMass", getDecimalValue(trunkFfmTxt)); - output.put("TrunkPredictedMuscleMass", getDecimalValue(trunkPredictedMuscleMassTxt)); - - instrumentExecutionService.addOutputParameterValues(output); - log.info("Sending output of Tanita BC-418 to server done..."); - exitUI(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.tanita; + +import gnu.io.CommPortIdentifier; +import gnu.io.SerialPort; +import gnu.io.SerialPortEvent; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; +import java.util.TooManyListenersException; + +import javax.swing.JOptionPane; +import javax.swing.JTextField; + +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.LoggerFactory; + +/** + * This is a simple Swing application that connects to a bioimpedance and weight device (Tanita Body Composition + * Analyzer). It allows the data to be inputed and retrieved automatically through the serial port of the device. + * + * @author mbelhiah + * + */ +public class Bc418InstrumentRunner extends TanitaInstrument { + + // Interface components + protected JTextField dateTxt; + + protected JTextField timeTxt; + + protected JTextField rLegImpedanceTxt; + + protected JTextField lLegImpedanceTxt; + + protected JTextField rArmImpedanceTxt; + + protected JTextField lArmImpedanceTxt; + + protected JTextField rLegFatPctTxt; + + protected JTextField rLegFatMassTxt; + + protected JTextField rLegFfmTxt; + + protected JTextField rLegPredictedMuscleMassTxt; + + protected JTextField lLegFatPctTxt; + + protected JTextField lLegFatMassTxt; + + protected JTextField lLegFfmTxt; + + protected JTextField lLegPredictedMuscleMassTxt; + + protected JTextField rArmFatPctTxt; + + protected JTextField rArmFatMassTxt; + + protected JTextField rArmFfmTxt; + + protected JTextField rArmPredictedMuscleMassTxt; + + protected JTextField lArmFatPctTxt; + + protected JTextField lArmFatMassTxt; + + protected JTextField lArmFfmTxt; + + protected JTextField lArmPredictedMuscleMassTxt; + + protected JTextField trunkFatPctTxt; + + protected JTextField trunkFatMassTxt; + + protected JTextField trunkFfmTxt; + + protected JTextField trunkPredictedMuscleMassTxt; + + private BufferedReader bufferedReader; + + public Bc418InstrumentRunner() throws Exception { + + super(); + + log = LoggerFactory.getLogger(Bc418InstrumentRunner.class); + + // Initialize interface components. + dateTxt = new ResultTextField(); + timeTxt = new ResultTextField(); + + rLegImpedanceTxt = new ResultTextField(); + lLegImpedanceTxt = new ResultTextField(); + rArmImpedanceTxt = new ResultTextField(); + lArmImpedanceTxt = new ResultTextField(); + + rLegFatPctTxt = new ResultTextField(); + rLegFatMassTxt = new ResultTextField(); + rLegFfmTxt = new ResultTextField(); + rLegPredictedMuscleMassTxt = new ResultTextField(); + + lLegFatPctTxt = new ResultTextField(); + lLegFatMassTxt = new ResultTextField(); + lLegFfmTxt = new ResultTextField(); + lLegPredictedMuscleMassTxt = new ResultTextField(); + + rArmFatPctTxt = new ResultTextField(); + rArmFatMassTxt = new ResultTextField(); + rArmFfmTxt = new ResultTextField(); + rArmPredictedMuscleMassTxt = new ResultTextField(); + + lArmFatPctTxt = new ResultTextField(); + lArmFatMassTxt = new ResultTextField(); + lArmFfmTxt = new ResultTextField(); + lArmPredictedMuscleMassTxt = new ResultTextField(); + + trunkFatPctTxt = new ResultTextField(); + trunkFatMassTxt = new ResultTextField(); + trunkFfmTxt = new ResultTextField(); + trunkPredictedMuscleMassTxt = new ResultTextField(); + + } + + /** + * Establish the connection with the device connected to the serial port. + */ + protected void setupSerialPort() { + + try { + // If port already open, close it. + if(serialPort != null) { + serialPort.close(); + serialPort = null; + } + + // Initialize serial port attributes. + log.info("Fetching communication port {}", getTanitaCommPort()); + CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort()); + + log.info("Opening communication port {}", getTanitaCommPort()); + serialPort = (SerialPort) wPortId.open(portOwnerName, 2000); + + // Set serial port parameters. + serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity); + + portIsAvailable = true; + } catch(Exception wCouldNotAccessSerialPort) { + portIsAvailable = false; + log.warn("Could not access the specified serial port.", wCouldNotAccessSerialPort); + } + } + + /** + * Handles any serial port events from the Tanita. + * + * @param pTanitaOutput The serial port event. + */ + public void serialEvent(SerialPortEvent pEvent) { + + switch(pEvent.getEventType()) { + + // Data is available at the serial port, so read it... + case SerialPortEvent.DATA_AVAILABLE: + + try { + if(bufferedReader.ready()){ + // Parse and sets the data in the GUI. + String wResponse = bufferedReader.readLine().trim(); + setTanitaData(parseTanitaData(wResponse)); + + // Enable save button, so data can be saved. + saveDataBtn.setEnabled(true); + } + } + catch(IOException wErrorReadingDataOnSerialPort) { + JOptionPane.showMessageDialog(appWindow, tanitaResourceBundle.getString("Err.Result_communication"), tanitaResourceBundle.getString("Title.Communication_error"), JOptionPane.ERROR_MESSAGE); + } + break; + } + } + + /** + * Retrieve participant data from the database and transfer them to the bioimpedance device + * @throws IOException + * @throws Exception + */ + private void initParticipantData() { + + Map inputData = instrumentExecutionService.getInputParametersValue("ClothesWeight", "Gender", "BodyType", "Height", "Age"); + + try { + bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); + } catch(IOException e) { + throw new RuntimeException("Cannot open serial port on BC-418", e); + } + + try { + String wUnitsOfMeasure = "U0\r\n"; + + String wClothesWeight = "D0001.0\r\n"; + + String wGender = null; + if(inputData.get("Gender").getValueAsString().equals("MALE")) { + wGender = "D11\r\n"; + } else { + if(inputData.get("Gender").getValueAsString().equals("FEMALE")) { + wGender = "D12\r\n"; + } + } + + String wBodyType = null; + if(inputData.get("BodyType").getValueAsString().equals("STANDARD")) { + wBodyType = "D20\r\n"; + } else { + if(inputData.get("BodyType").getValueAsString().equals("ATHLETIC")) { + wBodyType = "D22\r\n"; + } + } + + String wHeight = null; + Float inputHeight = Float.parseFloat(inputData.get("Height").getValueAsString()); + + if(inputHeight.intValue() < 100) { + wHeight = "D3000" + inputData.get("Height") + "\r\n"; + } else { + if(inputHeight.intValue() >= 100) { + wHeight = "D300" + inputHeight.intValue() + "\r\n"; + } + } + + String wAge; + wAge = "D4" + inputData.get("Age").getValueAsString() + "\r\n"; + + // Send commands and receives response + + // Send the units of measurement + String wResponse = null; + wResponse = sendReceive(wUnitsOfMeasure); + + if(!wResponse.equals("U0")) { + throw new RuntimeException("Error when setting units of measurement"); + } + + // Send tare weight + wResponse = sendReceive(wClothesWeight); + if(!wResponse.equals("D0")) { + throw new RuntimeException("Error when setting tare weight"); + } + + // Send gender + wResponse = sendReceive(wGender); + if(!wResponse.equals("D1")) { + throw new RuntimeException("Error when setting gender"); + } + + // Send body type + wResponse = sendReceive(wBodyType); + if(!wResponse.equals("D2")) { + throw new RuntimeException("Error when setting body type"); + } + + // Send height + wResponse = sendReceive(wHeight); + if(!wResponse.equals("D3")) { + throw new RuntimeException("Error when setting height"); + } + + // Send age + wResponse = sendReceive(wAge); + if(!wResponse.equals("D4")) { + throw new RuntimeException("Error when setting age"); + } + + // Start measurement + wResponse = sendReceive("G1\r\n"); + if(!wResponse.equals("G1")) { + throw new RuntimeException("Error when setting input parameters"); + } + } catch(Exception ex) { + throw new RuntimeException("Error initializing TANITA-BC418 input parameters: ", ex); + } + } + + public void initialize() { + super.initialize(); + initParticipantData(); + } + + public void run() { + if(!externalAppHelper.isSotfwareAlreadyStarted("tanitaInstrumentRunner")) { + + log.info("Starting Tanita BC-418 GUI"); + buildGUI(); + + try { + serialPort.addEventListener(this); + } + catch(TooManyListenersException e) { + throw new RuntimeException(e); + } + serialPort.notifyOnDataAvailable(true); + + // Obtain the lock outside the UI thread. This will block until the + // UI releases the lock, at which point it should + // be safe to exit the main thread. + + synchronized(uiLock) { + try { + uiLock.wait(); + } catch(InterruptedException e) { + throw new RuntimeException(e); + } + } + log.info("Lock obtained. Exiting software."); + } + else { + JOptionPane.showMessageDialog(null, tanitaResourceBundle.getString("Err.Application_lock"), tanitaResourceBundle.getString("Title.Cannot_start_application"), JOptionPane.ERROR_MESSAGE); + } + } + + /** + * Send receive. + */ + private String sendReceive(String pCommand) { + + String wResponse = null; + + try { + if(pCommand != null) { + + outputStream = serialPort.getOutputStream(); + // Send parameter + outputStream.write(pCommand.getBytes()); + log.info("Sending data:{}", pCommand); + } + } catch(IOException e) { + throw new RuntimeException("Error when sending data to device", e); + } + + // Read response + try { + wResponse = bufferedReader.readLine().trim(); + log.info("Receiving response:{}", wResponse); + } catch(IOException e) { + throw new RuntimeException("Error when receiving data from device", e); + } + + return wResponse; + } + + /** + * Sets the Bioimpedance data in the GUI components. + * + * @param pOutputData The parsed output data from the Tanita. + * @throws ParseException + */ + protected void setTanitaData(String[] pOutputData) { + + dateTxt.setText(pOutputData[0]); + timeTxt.setText(pOutputData[1]); + + String wBodyTypeCode = pOutputData[2]; + if(wBodyTypeCode.endsWith("0")) { + bodyTypeTxt.setText("STANDARD"); + } else if(wBodyTypeCode.endsWith("2")) { + bodyTypeTxt.setText("ATHLETIC"); + } + + String wGender = pOutputData[3]; + if(wGender.equals("1")) { + genderTxt.setText("MALE"); + } else if(wGender.equals("2")) { + genderTxt.setText("FEMALE"); + } + + heightTxt.setText(pOutputData[4]); + weightTxt.setText(pOutputData[5]); + fatPctTxt.setText(pOutputData[6]); + fatMassTxt.setText(pOutputData[7]); + ffmTxt.setText(pOutputData[8]); + tbwTxt.setText(pOutputData[9]); + ageTxt.setText(pOutputData[10]); + bmiTxt.setText(pOutputData[11]); + bmrTxt.setText(pOutputData[12]); + + impedanceTxt.setText(pOutputData[13]); + rLegImpedanceTxt.setText(pOutputData[14]); + lLegImpedanceTxt.setText(pOutputData[15]); + rArmImpedanceTxt.setText(pOutputData[16]); + lArmImpedanceTxt.setText(pOutputData[17]); + + rLegFatPctTxt.setText(pOutputData[18]); + rLegFatMassTxt.setText(pOutputData[19]); + rLegFfmTxt.setText(pOutputData[20]); + rLegPredictedMuscleMassTxt.setText(pOutputData[21]); + + lLegFatPctTxt.setText(pOutputData[22]); + lLegFatMassTxt.setText(pOutputData[23]); + lLegFfmTxt.setText(pOutputData[24]); + lLegPredictedMuscleMassTxt.setText(pOutputData[25]); + + rArmFatPctTxt.setText(pOutputData[26]); + rArmFatMassTxt.setText(pOutputData[27]); + rArmFfmTxt.setText(pOutputData[28]); + rArmPredictedMuscleMassTxt.setText(pOutputData[29]); + + lArmFatPctTxt.setText(pOutputData[30]); + lArmFatMassTxt.setText(pOutputData[31]); + lArmFfmTxt.setText(pOutputData[32]); + lArmPredictedMuscleMassTxt.setText(pOutputData[33]); + + trunkFatPctTxt.setText(pOutputData[34]); + trunkFatMassTxt.setText(pOutputData[35]); + trunkFfmTxt.setText(pOutputData[36]); + trunkPredictedMuscleMassTxt.setText(pOutputData[37]); + + } + + protected void sendOutputToServer() { + log.info("Sending output of Tanita BC-418 to server..."); + + Map output = new HashMap(); + + output.put("BodyType", new Data(DataType.TEXT, bodyTypeTxt.getText())); + output.put("Weight", getDecimalValue(weightTxt)); + output.put("Impedance", getIntegerValue(impedanceTxt)); + output.put("BMI", getDecimalValue(bmiTxt)); + output.put("BMR", getIntegerValue(bmrTxt)); + output.put("FatFreeMass", getDecimalValue(ffmTxt)); + output.put("FatMass", getDecimalValue(fatMassTxt)); + output.put("TotalBodyWater", getDecimalValue(tbwTxt)); + output.put("FatPercentage", getDecimalValue(fatPctTxt)); + output.put("Gender", new Data(DataType.TEXT, genderTxt.getText())); + output.put("Height", getDecimalValue(heightTxt)); + output.put("Age", getIntegerValue(ageTxt)); + + output.put("Date", new Data(DataType.TEXT, dateTxt.getText())); + output.put("Time", new Data(DataType.TEXT, timeTxt.getText())); + + output.put("RightLegImpedance", getIntegerValue(rLegImpedanceTxt)); + output.put("LeftLegImpedance", getIntegerValue(lLegImpedanceTxt)); + output.put("RightArmImpedance", getIntegerValue(rArmImpedanceTxt)); + output.put("LeftArmImpedance", getIntegerValue(lArmImpedanceTxt)); + + output.put("RightLegFatPercentage", getDecimalValue(rLegFatPctTxt)); + output.put("RightLegFatMass", getDecimalValue(rLegFatMassTxt)); + output.put("RightLegFatFreeMass", getDecimalValue(rLegFfmTxt)); + output.put("RightLegPredictedMuscleMass", getDecimalValue(rLegPredictedMuscleMassTxt)); + + output.put("LeftLegFatPercentage", getDecimalValue(lLegFatPctTxt)); + output.put("LeftLegFatMass", getDecimalValue(lLegFatMassTxt)); + output.put("LeftLegFatFreeMass", getDecimalValue(lLegFfmTxt)); + output.put("LeftLegPredictedMuscleMass", getDecimalValue(lLegPredictedMuscleMassTxt)); + + output.put("RightArmFatPercentage", getDecimalValue(rArmFatPctTxt)); + output.put("RightArmFatMass", getDecimalValue(rArmFatMassTxt)); + output.put("RightArmFatFreeMass", getDecimalValue(rArmFfmTxt)); + output.put("RightArmPredictedMuscleMass", getDecimalValue(rArmPredictedMuscleMassTxt)); + + output.put("LeftArmFatPercentage", getDecimalValue(lArmFatPctTxt)); + output.put("LeftArmFatMass", getDecimalValue(lArmFatMassTxt)); + output.put("LeftArmFatFreeMass", getDecimalValue(lArmFfmTxt)); + output.put("LeftArmPredictedMuscleMass", getDecimalValue(lArmPredictedMuscleMassTxt)); + + output.put("TrunkFatPercentage", getDecimalValue(trunkFatPctTxt)); + output.put("TrunkFatMass", getDecimalValue(trunkFatMassTxt)); + output.put("TrunkFatFreeMass", getDecimalValue(trunkFfmTxt)); + output.put("TrunkPredictedMuscleMass", getDecimalValue(trunkPredictedMuscleMassTxt)); + + instrumentExecutionService.addOutputParameterValues(output); + log.info("Sending output of Tanita BC-418 to server done..."); + exitUI(); + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/TanitaInstrument.java b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/TanitaInstrument.java index 4168d6cc5..20c6a5df8 100644 --- a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/TanitaInstrument.java +++ b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/TanitaInstrument.java @@ -1,682 +1,691 @@ -package org.obiba.onyx.jade.instrument.tanita; - -import gnu.io.CommPortIdentifier; -import gnu.io.SerialPort; -import gnu.io.SerialPortEvent; -import gnu.io.SerialPortEventListener; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Locale; -import java.util.Properties; -import java.util.ResourceBundle; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.JTextField; - -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.InstrumentRunner; -import org.obiba.onyx.jade.instrument.LocalSettingsHelper; -import org.obiba.onyx.jade.instrument.LocalSettingsHelper.CouldNotRetrieveSettingsException; -import org.obiba.onyx.jade.instrument.LocalSettingsHelper.CouldNotSaveSettingsException; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.Logger; -import org.springframework.beans.factory.InitializingBean; - -/** - * This is a simple Swing application that connects to a bioimpedance and weight device (Tanita Body Composition - * Analyzer). It allows the data to retrieve automatically through the serial port of the device. - * - * @author cag-mboulanger - * - */ - -@SuppressWarnings( { "unused", "unused" }) -public class TanitaInstrument implements InstrumentRunner, InitializingBean, SerialPortEventListener { - - protected Logger log; - - protected ResourceBundle tanitaResourceBundle; - - @SuppressWarnings("unused") - private String tanitaCommPort; - - protected BufferedReader bufferedReader; - - protected OutputStream outputStream; - - private Locale locale; - - // Injected by spring. - protected InstrumentExecutionService instrumentExecutionService; - - protected ExternalAppLauncherHelper externalAppHelper; - - protected LocalSettingsHelper settingsHelper; - - // Interface components - protected JFrame appWindow; - - protected JTextField bodyTypeTxt; - - protected JTextField genderTxt; - - protected JTextField heightTxt; - - protected JTextField weightTxt; - - protected JTextField impedanceTxt; - - protected JTextField fatPctTxt; - - protected JTextField fatMassTxt; - - protected JTextField ffmTxt; - - protected JTextField tbwTxt; - - protected JTextField ageTxt; - - protected JTextField bmiTxt; - - protected JTextField bmrTxt; - - protected JButton saveDataBtn; - - // Interface components dimension - protected int appWindowWidth; - - protected int appWindowHeight; - - protected int gridCol; - - /** - * Lock used to block the main thread as long as the UI has not finished its job - */ - protected final Object uiLock = new Object(); - - class ResultTextField extends JTextField { - - private static final long serialVersionUID = 1L; - - public ResultTextField() { - super(); - this.setEditable(false); - this.setSelectionColor(Color.WHITE); - this.setBackground(Color.WHITE); - this.setHorizontalAlignment(JTextField.RIGHT); - this.setPreferredSize(new Dimension(30, 0)); - } - } - - // Serial port configuration - protected SerialPort serialPort = null; - - protected int baudeRate; - - protected int dataLength; - - protected int parity; - - protected int stopBit; - - protected boolean portIsAvailable = false; - - protected String portOwnerName; - - private ArrayList availablePortNames; - - protected boolean shutdown = false; - - protected Properties tanitaLocalSettings; - - protected TanitaInstrument() throws Exception { - - // Initialize interface components. - bodyTypeTxt = new ResultTextField(); - bodyTypeTxt.setHorizontalAlignment(JTextField.LEFT); - bodyTypeTxt.setPreferredSize(new Dimension(100, 0)); - genderTxt = new ResultTextField(); - genderTxt.setHorizontalAlignment(JTextField.LEFT); - genderTxt.setPreferredSize(new Dimension(100, 0)); - heightTxt = new ResultTextField(); - weightTxt = new ResultTextField(); - impedanceTxt = new ResultTextField(); - fatPctTxt = new ResultTextField(); - fatMassTxt = new ResultTextField(); - ffmTxt = new ResultTextField(); - tbwTxt = new ResultTextField(); - ageTxt = new ResultTextField(); - bmiTxt = new ResultTextField(); - bmrTxt = new ResultTextField(); - - saveDataBtn = new JButton(); - saveDataBtn.setMnemonic('S'); - saveDataBtn.setEnabled(false); - - // Initialize interface components size - appWindowWidth = 525; - appWindowHeight = 260; - gridCol = 2; - - // Initialize serial port. - portOwnerName = "TANITA Body Composition Analyzer"; - } - - public void afterPropertiesSet() throws Exception { - // Attempt to retrieve settings persisted locally (if exist). - try { - tanitaLocalSettings = settingsHelper.retrieveSettings(); - } catch(CouldNotRetrieveSettingsException e) { - } - - log.info("Setting bioimpedance-locale to {}", getLocale().getDisplayLanguage()); - - tanitaResourceBundle = ResourceBundle.getBundle("bioimpedance-instrument", getLocale()); - saveDataBtn.setToolTipText(tanitaResourceBundle.getString("ToolTip.Save_and_return")); - saveDataBtn.setText(tanitaResourceBundle.getString("Save")); - } - - public InstrumentExecutionService getInstrumentExecutionService() { - return instrumentExecutionService; - } - - public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { - this.instrumentExecutionService = instrumentExecutionService; - } - - public ExternalAppLauncherHelper getExternalAppHelper() { - return externalAppHelper; - } - - public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { - this.externalAppHelper = externalAppHelper; - } - - public LocalSettingsHelper getSettingsHelper() { - return settingsHelper; - } - - public void setSettingsHelper(LocalSettingsHelper settingsHelper) { - this.settingsHelper = settingsHelper; - } - - public String getTanitaCommPort() { - return tanitaLocalSettings.getProperty("commPort"); - } - - public void setTanitaCommPort(String tanitaCommPort) { - if(tanitaLocalSettings == null) { - tanitaLocalSettings = new Properties(); - } - tanitaLocalSettings.setProperty("commPort", tanitaCommPort); - } - - public int getBaudeRate() { - return baudeRate; - } - - public void setBaudeRate(int baudeRate) { - this.baudeRate = baudeRate; - } - - public int getDataLength() { - return dataLength; - } - - public void setDataLength(int dataLength) { - this.dataLength = dataLength; - } - - public int getParity() { - return parity; - } - - public void setParity(int parity) { - this.parity = parity; - } - - public int getStopBit() { - return stopBit; - } - - public void setStopBit(int stopBit) { - this.stopBit = stopBit; - } - - public JTextField getBodyTypeTxt() { - return bodyTypeTxt; - } - - public void setBodyTypeTxt(JTextField bodyTypeTxt) { - this.bodyTypeTxt = bodyTypeTxt; - } - - public JTextField getGenderTxt() { - return genderTxt; - } - - public void setGenderTxt(JTextField genderTxt) { - this.genderTxt = genderTxt; - } - - public JTextField getHeightTxt() { - return heightTxt; - } - - public void setHeightTxt(JTextField heightTxt) { - this.heightTxt = heightTxt; - } - - public JTextField getWeightTxt() { - return weightTxt; - } - - public void setWeightTxt(JTextField weightTxt) { - this.weightTxt = weightTxt; - } - - public JTextField getImpedanceTxt() { - return impedanceTxt; - } - - public void setImpedanceTxt(JTextField impedanceTxt) { - this.impedanceTxt = impedanceTxt; - } - - public JTextField getFatPctTxt() { - return fatPctTxt; - } - - public void setFatPctTxt(JTextField fatPctTxt) { - this.fatPctTxt = fatPctTxt; - } - - public JTextField getFatMassTxt() { - return fatMassTxt; - } - - public void setFatMassTxt(JTextField fatMassTxt) { - this.fatMassTxt = fatMassTxt; - } - - public JTextField getFfmTxt() { - return ffmTxt; - } - - public void setFfmTxt(JTextField ffmTxt) { - this.ffmTxt = ffmTxt; - } - - public JTextField getTbwTxt() { - return tbwTxt; - } - - public void setTbwTxt(JTextField tbwTxt) { - this.tbwTxt = tbwTxt; - } - - public JTextField getAgeTxt() { - return ageTxt; - } - - public void setAgeTxt(JTextField ageTxt) { - this.ageTxt = ageTxt; - } - - public JTextField getBmiTxt() { - return bmiTxt; - } - - public void setBmiTxt(JTextField bmiTxt) { - this.bmiTxt = bmiTxt; - } - - public JTextField getBmrTxt() { - return bmrTxt; - } - - public void setBmrTxt(JTextField bmrTxt) { - this.bmrTxt = bmrTxt; - } - - public Locale getLocale() { - return locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - protected Data getIntegerValue(JTextField f) { - return new Data(DataType.INTEGER, new Long(f.getText().trim())); - } - - protected Data getDecimalValue(JTextField f) { - return new Data(DataType.DECIMAL, new Double(f.getText().trim())); - } - - @SuppressWarnings("unchecked") - protected void refreshSerialPortList() { - - log.info("Refreshing serial port list..."); - Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); - availablePortNames = new ArrayList(); - - // Build a list of all serial ports found. - while(portEnum != null && portEnum.hasMoreElements()) { - - CommPortIdentifier port = portEnum.nextElement(); - if(port.getPortType() == CommPortIdentifier.PORT_SERIAL) { - log.info("Port name={}, Port type={}", port.getName(), port.getPortType()); - availablePortNames.add(port.getName()); - } - } - } - - /** - * Parses the Bioimpedance device output string (Tanita). - * - * @param pTanitaOutput Output string. - * @return Parsed output string. - */ - protected String[] parseTanitaData(String pTanitaOutput) { - return pTanitaOutput.split(","); - } - - /** - * Sets the Bioimpedance data in the GUI components. - * - * @param pOutputData The parsed output data from the Tanita. - */ - protected void setTanitaData(String[] pOutputData) { - } - - protected void sendOutputToServer() { - } - - /** - * Builds the GUI which will display the bioimpedance results. - */ - protected void buildGUI() { - - appWindow = new JFrame(tanitaResourceBundle.getString("Title.Tanita")); - - appWindow.setAlwaysOnTop(true); - appWindow.setUndecorated(true); - appWindow.setResizable(false); - appWindow.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); - appWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - - appWindow.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - confirmOnExit(); - } - }); - - appWindow.getContentPane().add(buildMainPanel(), BorderLayout.CENTER); - - appWindow.pack(); - appWindow.setSize(appWindowWidth, appWindowHeight); - - // Display the GUI in the middle of the screen. - Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize(); - appWindow.setLocation(SCREEN_SIZE.width / 2 - appWindowWidth / 2, SCREEN_SIZE.height / 2 - appWindowHeight / 2); - - appWindow.setBackground(Color.white); - appWindow.setVisible(true); - } - - /** - * Signals that the UI has finished its job. - */ - protected void exitUI() { - appWindow.setVisible(false); - synchronized(uiLock) { - uiLock.notify(); - } - setTanitaCommPort(null); - } - - /** - * Build results sub panel - */ - protected JPanel buildResultSubPanel() { - // Add the results sub panel. - JPanel wResultPanel = new JPanel(); - - // Number of elements per line - GridLayout wResultPanelLayout = new GridLayout(0, gridCol); - wResultPanel.setBackground(new Color(206, 231, 255)); - wResultPanelLayout.setHgap(60); - wResultPanel.setLayout(wResultPanelLayout); - wResultPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - - addDataField(bodyTypeTxt, wResultPanel, tanitaResourceBundle.getString("Body_type"), null); - addDataField(genderTxt, wResultPanel, tanitaResourceBundle.getString("Gender"), null); - addDataField(heightTxt, wResultPanel, tanitaResourceBundle.getString("Height"), tanitaResourceBundle.getString("cm")); - addDataField(weightTxt, wResultPanel, tanitaResourceBundle.getString("Weight"), tanitaResourceBundle.getString("kg")); - addDataField(impedanceTxt, wResultPanel, tanitaResourceBundle.getString("Impedance"), tanitaResourceBundle.getString("Ohm")); - addDataField(fatPctTxt, wResultPanel, tanitaResourceBundle.getString("Fat_percentage"), tanitaResourceBundle.getString("%")); - addDataField(fatMassTxt, wResultPanel, tanitaResourceBundle.getString("Fat_mass"), tanitaResourceBundle.getString("kg")); - addDataField(ffmTxt, wResultPanel, tanitaResourceBundle.getString("Fat_free_mass"), tanitaResourceBundle.getString("kg")); - addDataField(tbwTxt, wResultPanel, tanitaResourceBundle.getString("Total_body_water"), tanitaResourceBundle.getString("kg")); - addDataField(ageTxt, wResultPanel, tanitaResourceBundle.getString("Age"), tanitaResourceBundle.getString("years")); - addDataField(bmiTxt, wResultPanel, tanitaResourceBundle.getString("BMI"), null); - addDataField(bmrTxt, wResultPanel, tanitaResourceBundle.getString("BMR"), tanitaResourceBundle.getString("kJ")); - - return (wResultPanel); - } - - /** - * Build action buttons sub panel - */ - protected JPanel buildActionButtonSubPanel() { - - // Add the action buttons sub panel. - JPanel wButtonPanel = new JPanel(); - wButtonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - wButtonPanel.setLayout(new BoxLayout(wButtonPanel, BoxLayout.X_AXIS)); - wButtonPanel.setBackground(new Color(206, 231, 255)); - JButton wCancelBtn = new JButton(tanitaResourceBundle.getString("Cancel")); - wCancelBtn.setMnemonic('A'); - wCancelBtn.setToolTipText(tanitaResourceBundle.getString("ToolTip.Cancel_measurement")); - wButtonPanel.add(Box.createHorizontalGlue()); - wButtonPanel.add(saveDataBtn); - wButtonPanel.add(Box.createRigidArea(new Dimension(10, 0))); - wButtonPanel.add(wCancelBtn); - - // Save button listener. - saveDataBtn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - sendOutputToServer(); - } - }); - - // Cancel button listener. - wCancelBtn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - confirmOnExit(); - } - }); - - return (wButtonPanel); - } - - /** - * Puts together the GUI main panel component. - * - * @return - */ - protected JPanel buildMainPanel() { - - JPanel wMainPanel = new JPanel(); - wMainPanel.setBackground(new Color(206, 231, 255)); - wMainPanel.setLayout(new BoxLayout(wMainPanel, BoxLayout.Y_AXIS)); - wMainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - wMainPanel.add(buildResultSubPanel()); - wMainPanel.add(buildActionButtonSubPanel()); - - return wMainPanel; - } - - /** - * Adds a data field to the GUI. - * - * @param pField JTextField object. - * @param pTargetPanel Target panel to which the data field will be added. - * @param pLabel A label which will be displayed to the left of the field. - * @param pUnits Units which will be displayed to the right of the field. - */ - protected void addDataField(JTextField pField, JPanel pTargetPanel, String pLabel, String pUnits) { - - // Create field sub panel. - JPanel wFieldPanel = new JPanel(); - wFieldPanel.setBackground(new Color(206, 231, 255)); - wFieldPanel.setLayout(new BoxLayout(wFieldPanel, BoxLayout.X_AXIS)); - wFieldPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); - - // Add field label. - JLabel wFieldLabel = new JLabel(pLabel + ":"); - wFieldLabel.setPreferredSize(new Dimension(100, 60)); - wFieldPanel.add(wFieldLabel); - - // Add text field. - wFieldPanel.add(pField); - - // Add units label. - if(pUnits != null) { - JLabel wFieldUnit = new JLabel(" " + pUnits); - wFieldUnit.setPreferredSize(new Dimension(55, 60)); - wFieldPanel.add(wFieldUnit); - } - - // Add sub panel to main panel. - pTargetPanel.add(wFieldPanel); - - } - - /** - * Displays a confirmation window when the application is closed by the user without saving. - */ - protected void confirmOnExit() { - - // Ask for confirmation only if data has been fetch from the device. - if(saveDataBtn.isEnabled()) { - - int wConfirmation = JOptionPane.showConfirmDialog(appWindow, tanitaResourceBundle.getString("Confirmation.Close_window"), tanitaResourceBundle.getString("Title.Confirmation"), JOptionPane.YES_NO_OPTION); - - // If confirmed, application is closed. - if(wConfirmation == JOptionPane.YES_OPTION) { - exitUI(); - } - - } else { - exitUI(); - } - } - - /** - * Reestablish a lost connection. - */ - protected void reestablishConnection() { - - String[] options = { tanitaResourceBundle.getString("OK"), tanitaResourceBundle.getString("Cancel"), tanitaResourceBundle.getString("Settings") }; - - // Loop until connection is reestablished. - int selectedOption; - while(serialPort == null || !serialPort.isCTS()) { - - selectedOption = JOptionPane.showOptionDialog(appWindow, tanitaResourceBundle.getString("Err.No_communication"), tanitaResourceBundle.getString("Title.Communication_problem"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, tanitaResourceBundle.getString("OK")); - - // OK option selected. - if(selectedOption == 0) { - - // Try to reestablish connection. - setupSerialPort(); - - // Cancel option selected. - } else if(selectedOption == 1) { - - // Temporary fix, need to find another solution... - exitUI(); - - // Configuration option selected. - } else if(selectedOption == 2) { - - // List all serial port in a drop down list, so a new one can be - // selected. - refreshSerialPortList(); - String selectedPort = (String) JOptionPane.showInputDialog(appWindow, tanitaResourceBundle.getString("Instruction.Choose_port"), tanitaResourceBundle.getString("Title.Settings"), JOptionPane.QUESTION_MESSAGE, null, availablePortNames.toArray(), getTanitaCommPort()); - - if(selectedPort != null) { - setTanitaCommPort(selectedPort); - - try { - settingsHelper.saveSettings(tanitaLocalSettings); - } catch(CouldNotSaveSettingsException e) { - log.error("Local settings could not be persisted.", e); - } - - setupSerialPort(); - } else { - exitUI(); - } - } - } - } - - protected void setupSerialPort() { - } - - public void serialEvent(SerialPortEvent pEvent) { - } - - public void initialize() { - log.info("Refresh serial port list"); - refreshSerialPortList(); - log.info("Setup serial port"); - setupSerialPort(); - // If serial port is not available display error message - if(!portIsAvailable) { - reestablishConnection(); - } - } - - public void run() { - } - - public void shutdown() { - shutdown = true; - if(serialPort != null) { - try { - log.info("Closing serial port"); - serialPort.close(); - } catch(Exception e) { - // ignore - log.info("Error Closing serial port"); - } - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.tanita; + +import gnu.io.CommPortIdentifier; +import gnu.io.SerialPort; +import gnu.io.SerialPortEvent; +import gnu.io.SerialPortEventListener; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.BufferedReader; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Properties; +import java.util.ResourceBundle; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRootPane; +import javax.swing.JTextField; + +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.InstrumentRunner; +import org.obiba.onyx.jade.instrument.LocalSettingsHelper; +import org.obiba.onyx.jade.instrument.LocalSettingsHelper.CouldNotRetrieveSettingsException; +import org.obiba.onyx.jade.instrument.LocalSettingsHelper.CouldNotSaveSettingsException; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.Logger; +import org.springframework.beans.factory.InitializingBean; + +/** + * This is a simple Swing application that connects to a bioimpedance and weight device (Tanita Body Composition + * Analyzer). It allows the data to retrieve automatically through the serial port of the device. + * + * @author cag-mboulanger + * + */ + +@SuppressWarnings( { "unused", "unused" }) +public class TanitaInstrument implements InstrumentRunner, InitializingBean, SerialPortEventListener { + + protected Logger log; + + protected ResourceBundle tanitaResourceBundle; + + @SuppressWarnings("unused") + private String tanitaCommPort; + + protected BufferedReader bufferedReader; + + protected OutputStream outputStream; + + private Locale locale; + + // Injected by spring. + protected InstrumentExecutionService instrumentExecutionService; + + protected ExternalAppLauncherHelper externalAppHelper; + + protected LocalSettingsHelper settingsHelper; + + // Interface components + protected JFrame appWindow; + + protected JTextField bodyTypeTxt; + + protected JTextField genderTxt; + + protected JTextField heightTxt; + + protected JTextField weightTxt; + + protected JTextField impedanceTxt; + + protected JTextField fatPctTxt; + + protected JTextField fatMassTxt; + + protected JTextField ffmTxt; + + protected JTextField tbwTxt; + + protected JTextField ageTxt; + + protected JTextField bmiTxt; + + protected JTextField bmrTxt; + + protected JButton saveDataBtn; + + // Interface components dimension + protected int appWindowWidth; + + protected int appWindowHeight; + + protected int gridCol; + + /** + * Lock used to block the main thread as long as the UI has not finished its job + */ + protected final Object uiLock = new Object(); + + class ResultTextField extends JTextField { + + private static final long serialVersionUID = 1L; + + public ResultTextField() { + super(); + this.setEditable(false); + this.setSelectionColor(Color.WHITE); + this.setBackground(Color.WHITE); + this.setHorizontalAlignment(JTextField.RIGHT); + this.setPreferredSize(new Dimension(30, 0)); + } + } + + // Serial port configuration + protected SerialPort serialPort = null; + + protected int baudeRate; + + protected int dataLength; + + protected int parity; + + protected int stopBit; + + protected boolean portIsAvailable = false; + + protected String portOwnerName; + + private ArrayList availablePortNames; + + protected boolean shutdown = false; + + protected Properties tanitaLocalSettings; + + protected TanitaInstrument() throws Exception { + + // Initialize interface components. + bodyTypeTxt = new ResultTextField(); + bodyTypeTxt.setHorizontalAlignment(JTextField.LEFT); + bodyTypeTxt.setPreferredSize(new Dimension(100, 0)); + genderTxt = new ResultTextField(); + genderTxt.setHorizontalAlignment(JTextField.LEFT); + genderTxt.setPreferredSize(new Dimension(100, 0)); + heightTxt = new ResultTextField(); + weightTxt = new ResultTextField(); + impedanceTxt = new ResultTextField(); + fatPctTxt = new ResultTextField(); + fatMassTxt = new ResultTextField(); + ffmTxt = new ResultTextField(); + tbwTxt = new ResultTextField(); + ageTxt = new ResultTextField(); + bmiTxt = new ResultTextField(); + bmrTxt = new ResultTextField(); + + saveDataBtn = new JButton(); + saveDataBtn.setMnemonic('S'); + saveDataBtn.setEnabled(false); + + // Initialize interface components size + appWindowWidth = 525; + appWindowHeight = 260; + gridCol = 2; + + // Initialize serial port. + portOwnerName = "TANITA Body Composition Analyzer"; + } + + public void afterPropertiesSet() throws Exception { + // Attempt to retrieve settings persisted locally (if exist). + try { + tanitaLocalSettings = settingsHelper.retrieveSettings(); + } catch(CouldNotRetrieveSettingsException e) { + } + + log.info("Setting bioimpedance-locale to {}", getLocale().getDisplayLanguage()); + + tanitaResourceBundle = ResourceBundle.getBundle("bioimpedance-instrument", getLocale()); + saveDataBtn.setToolTipText(tanitaResourceBundle.getString("ToolTip.Save_and_return")); + saveDataBtn.setText(tanitaResourceBundle.getString("Save")); + } + + public InstrumentExecutionService getInstrumentExecutionService() { + return instrumentExecutionService; + } + + public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { + this.instrumentExecutionService = instrumentExecutionService; + } + + public ExternalAppLauncherHelper getExternalAppHelper() { + return externalAppHelper; + } + + public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { + this.externalAppHelper = externalAppHelper; + } + + public LocalSettingsHelper getSettingsHelper() { + return settingsHelper; + } + + public void setSettingsHelper(LocalSettingsHelper settingsHelper) { + this.settingsHelper = settingsHelper; + } + + public String getTanitaCommPort() { + return tanitaLocalSettings.getProperty("commPort"); + } + + public void setTanitaCommPort(String tanitaCommPort) { + if(tanitaLocalSettings == null) { + tanitaLocalSettings = new Properties(); + } + tanitaLocalSettings.setProperty("commPort", tanitaCommPort); + } + + public int getBaudeRate() { + return baudeRate; + } + + public void setBaudeRate(int baudeRate) { + this.baudeRate = baudeRate; + } + + public int getDataLength() { + return dataLength; + } + + public void setDataLength(int dataLength) { + this.dataLength = dataLength; + } + + public int getParity() { + return parity; + } + + public void setParity(int parity) { + this.parity = parity; + } + + public int getStopBit() { + return stopBit; + } + + public void setStopBit(int stopBit) { + this.stopBit = stopBit; + } + + public JTextField getBodyTypeTxt() { + return bodyTypeTxt; + } + + public void setBodyTypeTxt(JTextField bodyTypeTxt) { + this.bodyTypeTxt = bodyTypeTxt; + } + + public JTextField getGenderTxt() { + return genderTxt; + } + + public void setGenderTxt(JTextField genderTxt) { + this.genderTxt = genderTxt; + } + + public JTextField getHeightTxt() { + return heightTxt; + } + + public void setHeightTxt(JTextField heightTxt) { + this.heightTxt = heightTxt; + } + + public JTextField getWeightTxt() { + return weightTxt; + } + + public void setWeightTxt(JTextField weightTxt) { + this.weightTxt = weightTxt; + } + + public JTextField getImpedanceTxt() { + return impedanceTxt; + } + + public void setImpedanceTxt(JTextField impedanceTxt) { + this.impedanceTxt = impedanceTxt; + } + + public JTextField getFatPctTxt() { + return fatPctTxt; + } + + public void setFatPctTxt(JTextField fatPctTxt) { + this.fatPctTxt = fatPctTxt; + } + + public JTextField getFatMassTxt() { + return fatMassTxt; + } + + public void setFatMassTxt(JTextField fatMassTxt) { + this.fatMassTxt = fatMassTxt; + } + + public JTextField getFfmTxt() { + return ffmTxt; + } + + public void setFfmTxt(JTextField ffmTxt) { + this.ffmTxt = ffmTxt; + } + + public JTextField getTbwTxt() { + return tbwTxt; + } + + public void setTbwTxt(JTextField tbwTxt) { + this.tbwTxt = tbwTxt; + } + + public JTextField getAgeTxt() { + return ageTxt; + } + + public void setAgeTxt(JTextField ageTxt) { + this.ageTxt = ageTxt; + } + + public JTextField getBmiTxt() { + return bmiTxt; + } + + public void setBmiTxt(JTextField bmiTxt) { + this.bmiTxt = bmiTxt; + } + + public JTextField getBmrTxt() { + return bmrTxt; + } + + public void setBmrTxt(JTextField bmrTxt) { + this.bmrTxt = bmrTxt; + } + + public Locale getLocale() { + return locale; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + protected Data getIntegerValue(JTextField f) { + return new Data(DataType.INTEGER, new Long(f.getText().trim())); + } + + protected Data getDecimalValue(JTextField f) { + return new Data(DataType.DECIMAL, new Double(f.getText().trim())); + } + + @SuppressWarnings("unchecked") + protected void refreshSerialPortList() { + + log.info("Refreshing serial port list..."); + Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); + availablePortNames = new ArrayList(); + + // Build a list of all serial ports found. + while(portEnum != null && portEnum.hasMoreElements()) { + + CommPortIdentifier port = portEnum.nextElement(); + if(port.getPortType() == CommPortIdentifier.PORT_SERIAL) { + log.info("Port name={}, Port type={}", port.getName(), port.getPortType()); + availablePortNames.add(port.getName()); + } + } + } + + /** + * Parses the Bioimpedance device output string (Tanita). + * + * @param pTanitaOutput Output string. + * @return Parsed output string. + */ + protected String[] parseTanitaData(String pTanitaOutput) { + return pTanitaOutput.split(","); + } + + /** + * Sets the Bioimpedance data in the GUI components. + * + * @param pOutputData The parsed output data from the Tanita. + */ + protected void setTanitaData(String[] pOutputData) { + } + + protected void sendOutputToServer() { + } + + /** + * Builds the GUI which will display the bioimpedance results. + */ + protected void buildGUI() { + + appWindow = new JFrame(tanitaResourceBundle.getString("Title.Tanita")); + + appWindow.setAlwaysOnTop(true); + appWindow.setUndecorated(true); + appWindow.setResizable(false); + appWindow.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); + appWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); + + appWindow.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + confirmOnExit(); + } + }); + + appWindow.getContentPane().add(buildMainPanel(), BorderLayout.CENTER); + + appWindow.pack(); + appWindow.setSize(appWindowWidth, appWindowHeight); + + // Display the GUI in the middle of the screen. + Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize(); + appWindow.setLocation(SCREEN_SIZE.width / 2 - appWindowWidth / 2, SCREEN_SIZE.height / 2 - appWindowHeight / 2); + + appWindow.setBackground(Color.white); + appWindow.setVisible(true); + } + + /** + * Signals that the UI has finished its job. + */ + protected void exitUI() { + appWindow.setVisible(false); + synchronized(uiLock) { + uiLock.notify(); + } + setTanitaCommPort(null); + } + + /** + * Build results sub panel + */ + protected JPanel buildResultSubPanel() { + // Add the results sub panel. + JPanel wResultPanel = new JPanel(); + + // Number of elements per line + GridLayout wResultPanelLayout = new GridLayout(0, gridCol); + wResultPanel.setBackground(new Color(206, 231, 255)); + wResultPanelLayout.setHgap(60); + wResultPanel.setLayout(wResultPanelLayout); + wResultPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + addDataField(bodyTypeTxt, wResultPanel, tanitaResourceBundle.getString("Body_type"), null); + addDataField(genderTxt, wResultPanel, tanitaResourceBundle.getString("Gender"), null); + addDataField(heightTxt, wResultPanel, tanitaResourceBundle.getString("Height"), tanitaResourceBundle.getString("cm")); + addDataField(weightTxt, wResultPanel, tanitaResourceBundle.getString("Weight"), tanitaResourceBundle.getString("kg")); + addDataField(impedanceTxt, wResultPanel, tanitaResourceBundle.getString("Impedance"), tanitaResourceBundle.getString("Ohm")); + addDataField(fatPctTxt, wResultPanel, tanitaResourceBundle.getString("Fat_percentage"), tanitaResourceBundle.getString("%")); + addDataField(fatMassTxt, wResultPanel, tanitaResourceBundle.getString("Fat_mass"), tanitaResourceBundle.getString("kg")); + addDataField(ffmTxt, wResultPanel, tanitaResourceBundle.getString("Fat_free_mass"), tanitaResourceBundle.getString("kg")); + addDataField(tbwTxt, wResultPanel, tanitaResourceBundle.getString("Total_body_water"), tanitaResourceBundle.getString("kg")); + addDataField(ageTxt, wResultPanel, tanitaResourceBundle.getString("Age"), tanitaResourceBundle.getString("years")); + addDataField(bmiTxt, wResultPanel, tanitaResourceBundle.getString("BMI"), null); + addDataField(bmrTxt, wResultPanel, tanitaResourceBundle.getString("BMR"), tanitaResourceBundle.getString("kJ")); + + return (wResultPanel); + } + + /** + * Build action buttons sub panel + */ + protected JPanel buildActionButtonSubPanel() { + + // Add the action buttons sub panel. + JPanel wButtonPanel = new JPanel(); + wButtonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + wButtonPanel.setLayout(new BoxLayout(wButtonPanel, BoxLayout.X_AXIS)); + wButtonPanel.setBackground(new Color(206, 231, 255)); + JButton wCancelBtn = new JButton(tanitaResourceBundle.getString("Cancel")); + wCancelBtn.setMnemonic('A'); + wCancelBtn.setToolTipText(tanitaResourceBundle.getString("ToolTip.Cancel_measurement")); + wButtonPanel.add(Box.createHorizontalGlue()); + wButtonPanel.add(saveDataBtn); + wButtonPanel.add(Box.createRigidArea(new Dimension(10, 0))); + wButtonPanel.add(wCancelBtn); + + // Save button listener. + saveDataBtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + sendOutputToServer(); + } + }); + + // Cancel button listener. + wCancelBtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + confirmOnExit(); + } + }); + + return (wButtonPanel); + } + + /** + * Puts together the GUI main panel component. + * + * @return + */ + protected JPanel buildMainPanel() { + + JPanel wMainPanel = new JPanel(); + wMainPanel.setBackground(new Color(206, 231, 255)); + wMainPanel.setLayout(new BoxLayout(wMainPanel, BoxLayout.Y_AXIS)); + wMainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + wMainPanel.add(buildResultSubPanel()); + wMainPanel.add(buildActionButtonSubPanel()); + + return wMainPanel; + } + + /** + * Adds a data field to the GUI. + * + * @param pField JTextField object. + * @param pTargetPanel Target panel to which the data field will be added. + * @param pLabel A label which will be displayed to the left of the field. + * @param pUnits Units which will be displayed to the right of the field. + */ + protected void addDataField(JTextField pField, JPanel pTargetPanel, String pLabel, String pUnits) { + + // Create field sub panel. + JPanel wFieldPanel = new JPanel(); + wFieldPanel.setBackground(new Color(206, 231, 255)); + wFieldPanel.setLayout(new BoxLayout(wFieldPanel, BoxLayout.X_AXIS)); + wFieldPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); + + // Add field label. + JLabel wFieldLabel = new JLabel(pLabel + ":"); + wFieldLabel.setPreferredSize(new Dimension(100, 60)); + wFieldPanel.add(wFieldLabel); + + // Add text field. + wFieldPanel.add(pField); + + // Add units label. + if(pUnits != null) { + JLabel wFieldUnit = new JLabel(" " + pUnits); + wFieldUnit.setPreferredSize(new Dimension(55, 60)); + wFieldPanel.add(wFieldUnit); + } + + // Add sub panel to main panel. + pTargetPanel.add(wFieldPanel); + + } + + /** + * Displays a confirmation window when the application is closed by the user without saving. + */ + protected void confirmOnExit() { + + // Ask for confirmation only if data has been fetch from the device. + if(saveDataBtn.isEnabled()) { + + int wConfirmation = JOptionPane.showConfirmDialog(appWindow, tanitaResourceBundle.getString("Confirmation.Close_window"), tanitaResourceBundle.getString("Title.Confirmation"), JOptionPane.YES_NO_OPTION); + + // If confirmed, application is closed. + if(wConfirmation == JOptionPane.YES_OPTION) { + exitUI(); + } + + } else { + exitUI(); + } + } + + /** + * Reestablish a lost connection. + */ + protected void reestablishConnection() { + + String[] options = { tanitaResourceBundle.getString("OK"), tanitaResourceBundle.getString("Cancel"), tanitaResourceBundle.getString("Settings") }; + + // Loop until connection is reestablished. + int selectedOption; + while(serialPort == null || !serialPort.isCTS()) { + + selectedOption = JOptionPane.showOptionDialog(appWindow, tanitaResourceBundle.getString("Err.No_communication"), tanitaResourceBundle.getString("Title.Communication_problem"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, tanitaResourceBundle.getString("OK")); + + // OK option selected. + if(selectedOption == 0) { + + // Try to reestablish connection. + setupSerialPort(); + + // Cancel option selected. + } else if(selectedOption == 1) { + + // Temporary fix, need to find another solution... + exitUI(); + + // Configuration option selected. + } else if(selectedOption == 2) { + + // List all serial port in a drop down list, so a new one can be + // selected. + refreshSerialPortList(); + String selectedPort = (String) JOptionPane.showInputDialog(appWindow, tanitaResourceBundle.getString("Instruction.Choose_port"), tanitaResourceBundle.getString("Title.Settings"), JOptionPane.QUESTION_MESSAGE, null, availablePortNames.toArray(), getTanitaCommPort()); + + if(selectedPort != null) { + setTanitaCommPort(selectedPort); + + try { + settingsHelper.saveSettings(tanitaLocalSettings); + } catch(CouldNotSaveSettingsException e) { + log.error("Local settings could not be persisted.", e); + } + + setupSerialPort(); + } else { + exitUI(); + } + } + } + } + + protected void setupSerialPort() { + } + + public void serialEvent(SerialPortEvent pEvent) { + } + + public void initialize() { + log.info("Refresh serial port list"); + refreshSerialPortList(); + log.info("Setup serial port"); + setupSerialPort(); + // If serial port is not available display error message + if(!portIsAvailable) { + reestablishConnection(); + } + } + + public void run() { + } + + public void shutdown() { + shutdown = true; + if(serialPort != null) { + try { + log.info("Closing serial port"); + serialPort.close(); + } catch(Exception e) { + // ignore + log.info("Error Closing serial port"); + } + } + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunner.java index c078c9866..d009b773e 100644 --- a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/main/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunner.java @@ -1,196 +1,205 @@ -package org.obiba.onyx.jade.instrument.tanita; - -import gnu.io.CommPortIdentifier; -import gnu.io.SerialPort; -import gnu.io.SerialPortEvent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.JOptionPane; - -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.LoggerFactory; - -public class Tbf310InstrumentRunner extends TanitaInstrument { - - public Tbf310InstrumentRunner() throws Exception { - - super(); - log = LoggerFactory.getLogger(Tbf310InstrumentRunner.class); - } - - /** - * Establish the connection with the device connected to the serial port. - */ - public void setupSerialPort() { - - try { - - // If port already open, close it. - if(serialPort != null) { - serialPort.close(); - serialPort = null; - } - - // Initialize serial port attributes. - log.info("Fetching communication port {}", getTanitaCommPort()); - CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort()); - - log.info("Opening communication port {}", getTanitaCommPort()); - serialPort = (SerialPort) wPortId.open(portOwnerName, 2000); - - // Make sure the port is "Clear To Send" - serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity); - bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); - - if(serialPort.isCTS()) { - - // Set serial port parameters. - serialPort.addEventListener(this); - serialPort.notifyOnDataAvailable(true); - serialPort.notifyOnCTS(true); - serialPort.notifyOnCarrierDetect(true); - serialPort.notifyOnRingIndicator(true); - serialPort.notifyOnDSR(true); - - portIsAvailable = true; - - } else { - portIsAvailable = false; - } - - } catch(Exception wCouldNotAccessSerialPort) { - portIsAvailable = false; - log.warn("Could not access the specified serial port."); - } - } - - /** - * Handles any serial port events from the Tanita. - * - * @param pTanitaOutput The serial port event. - */ - public void serialEvent(SerialPortEvent pEvent) { - - switch(pEvent.getEventType()) { - - // Clear to send - case SerialPortEvent.CTS: - - // If serial is not CTS, it means that the cable was disconnected. - // Attempt to reestablish the connection. - if(shutdown == false) { - // Only try to reestablish if we're not shutting down the - // application. - reestablishConnection(); - } - - break; - - // Data is available at the serial port, so read it... - case SerialPortEvent.DATA_AVAILABLE: - - try { - if(bufferedReader.ready()){ - - // Parse and sets the data in the GUI. - String wResponse = bufferedReader.readLine().trim(); - setTanitaData(parseTanitaData(wResponse)); - - // Enable save button, so data can be saved. - saveDataBtn.setEnabled(true); - } - } - catch(IOException wErrorReadingDataOnSerialPort) { - JOptionPane.showMessageDialog(appWindow, tanitaResourceBundle.getString("Err.Result_communication"), tanitaResourceBundle.getString("Title.Communication_error"), JOptionPane.ERROR_MESSAGE); - } - break; - } - } - - public void run() { - - if(!externalAppHelper.isSotfwareAlreadyStarted("tbf310InstrumentRunner")) { - - log.info("Starting TBF-310 GUI"); - buildGUI(); - - // Obtain the lock outside the UI thread. This will block until the UI releases the lock, at which point it should - // be safe to exit the main thread. - synchronized(uiLock) { - try { - uiLock.wait(); - } catch(InterruptedException e) { - throw new RuntimeException(e); - } - } - - log.info("Lock obtained. Exiting software."); - - } else { - JOptionPane.showMessageDialog(null, tanitaResourceBundle.getString("Err.Application_lock"), tanitaResourceBundle.getString("Title.Cannot_start_application"), JOptionPane.ERROR_MESSAGE); - } - } - - /** - * Sets the Bioimpedance data in the GUI components. - * - * @param pOutputData The parsed output data from the Tanita. - */ - protected void setTanitaData(String[] pOutputData) { - - String wBodyTypeCode = pOutputData[0]; - if(wBodyTypeCode.endsWith("0")) { - bodyTypeTxt.setText("STANDARD"); - } else if(wBodyTypeCode.endsWith("2")) { - bodyTypeTxt.setText("ATHLETIC"); - } - - String wGender = pOutputData[1]; - if(wGender.equals("1")) { - genderTxt.setText("MALE"); - } else if(wGender.equals("2")) { - genderTxt.setText("FEMALE"); - } - - heightTxt.setText(pOutputData[2]); - weightTxt.setText(pOutputData[3]); - impedanceTxt.setText(pOutputData[4]); - fatPctTxt.setText(pOutputData[5]); - fatMassTxt.setText(pOutputData[6]); - ffmTxt.setText(pOutputData[7]); - tbwTxt.setText(pOutputData[8]); - ageTxt.setText(pOutputData[9]); - bmiTxt.setText(pOutputData[10]); - bmrTxt.setText(pOutputData[11]); - - } - - public void sendOutputToServer() { - log.info("Sending output of tanita to server..."); - - Map output = new HashMap(); - - output.put("BodyType", new Data(DataType.TEXT, bodyTypeTxt.getText())); - output.put("Weight", getDecimalValue(weightTxt)); - output.put("Impedance", getIntegerValue(impedanceTxt)); - output.put("BMI", getDecimalValue(bmiTxt)); - output.put("BMR", getIntegerValue(bmrTxt)); - output.put("FatFreeMass", getDecimalValue(ffmTxt)); - output.put("FatMass", getDecimalValue(fatMassTxt)); - output.put("TotalBodyWater", getDecimalValue(tbwTxt)); - output.put("FatPercentage", getDecimalValue(fatPctTxt)); - output.put("Gender", new Data(DataType.TEXT, genderTxt.getText())); - output.put("Height", getDecimalValue(heightTxt)); - output.put("Age", getIntegerValue(ageTxt)); - - instrumentExecutionService.addOutputParameterValues(output); - log.info("Sending output of tanita to server done..."); - exitUI(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.tanita; + +import gnu.io.CommPortIdentifier; +import gnu.io.SerialPort; +import gnu.io.SerialPortEvent; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.JOptionPane; + +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.LoggerFactory; + +public class Tbf310InstrumentRunner extends TanitaInstrument { + + public Tbf310InstrumentRunner() throws Exception { + + super(); + log = LoggerFactory.getLogger(Tbf310InstrumentRunner.class); + } + + /** + * Establish the connection with the device connected to the serial port. + */ + public void setupSerialPort() { + + try { + + // If port already open, close it. + if(serialPort != null) { + serialPort.close(); + serialPort = null; + } + + // Initialize serial port attributes. + log.info("Fetching communication port {}", getTanitaCommPort()); + CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort()); + + log.info("Opening communication port {}", getTanitaCommPort()); + serialPort = (SerialPort) wPortId.open(portOwnerName, 2000); + + // Make sure the port is "Clear To Send" + serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity); + bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); + + if(serialPort.isCTS()) { + + // Set serial port parameters. + serialPort.addEventListener(this); + serialPort.notifyOnDataAvailable(true); + serialPort.notifyOnCTS(true); + serialPort.notifyOnCarrierDetect(true); + serialPort.notifyOnRingIndicator(true); + serialPort.notifyOnDSR(true); + + portIsAvailable = true; + + } else { + portIsAvailable = false; + } + + } catch(Exception wCouldNotAccessSerialPort) { + portIsAvailable = false; + log.warn("Could not access the specified serial port."); + } + } + + /** + * Handles any serial port events from the Tanita. + * + * @param pTanitaOutput The serial port event. + */ + public void serialEvent(SerialPortEvent pEvent) { + + switch(pEvent.getEventType()) { + + // Clear to send + case SerialPortEvent.CTS: + + // If serial is not CTS, it means that the cable was disconnected. + // Attempt to reestablish the connection. + if(shutdown == false) { + // Only try to reestablish if we're not shutting down the + // application. + reestablishConnection(); + } + + break; + + // Data is available at the serial port, so read it... + case SerialPortEvent.DATA_AVAILABLE: + + try { + if(bufferedReader.ready()){ + + // Parse and sets the data in the GUI. + String wResponse = bufferedReader.readLine().trim(); + setTanitaData(parseTanitaData(wResponse)); + + // Enable save button, so data can be saved. + saveDataBtn.setEnabled(true); + } + } + catch(IOException wErrorReadingDataOnSerialPort) { + JOptionPane.showMessageDialog(appWindow, tanitaResourceBundle.getString("Err.Result_communication"), tanitaResourceBundle.getString("Title.Communication_error"), JOptionPane.ERROR_MESSAGE); + } + break; + } + } + + public void run() { + + if(!externalAppHelper.isSotfwareAlreadyStarted("tbf310InstrumentRunner")) { + + log.info("Starting TBF-310 GUI"); + buildGUI(); + + // Obtain the lock outside the UI thread. This will block until the UI releases the lock, at which point it should + // be safe to exit the main thread. + synchronized(uiLock) { + try { + uiLock.wait(); + } catch(InterruptedException e) { + throw new RuntimeException(e); + } + } + + log.info("Lock obtained. Exiting software."); + + } else { + JOptionPane.showMessageDialog(null, tanitaResourceBundle.getString("Err.Application_lock"), tanitaResourceBundle.getString("Title.Cannot_start_application"), JOptionPane.ERROR_MESSAGE); + } + } + + /** + * Sets the Bioimpedance data in the GUI components. + * + * @param pOutputData The parsed output data from the Tanita. + */ + protected void setTanitaData(String[] pOutputData) { + + String wBodyTypeCode = pOutputData[0]; + if(wBodyTypeCode.endsWith("0")) { + bodyTypeTxt.setText("STANDARD"); + } else if(wBodyTypeCode.endsWith("2")) { + bodyTypeTxt.setText("ATHLETIC"); + } + + String wGender = pOutputData[1]; + if(wGender.equals("1")) { + genderTxt.setText("MALE"); + } else if(wGender.equals("2")) { + genderTxt.setText("FEMALE"); + } + + heightTxt.setText(pOutputData[2]); + weightTxt.setText(pOutputData[3]); + impedanceTxt.setText(pOutputData[4]); + fatPctTxt.setText(pOutputData[5]); + fatMassTxt.setText(pOutputData[6]); + ffmTxt.setText(pOutputData[7]); + tbwTxt.setText(pOutputData[8]); + ageTxt.setText(pOutputData[9]); + bmiTxt.setText(pOutputData[10]); + bmrTxt.setText(pOutputData[11]); + + } + + public void sendOutputToServer() { + log.info("Sending output of tanita to server..."); + + Map output = new HashMap(); + + output.put("BodyType", new Data(DataType.TEXT, bodyTypeTxt.getText())); + output.put("Weight", getDecimalValue(weightTxt)); + output.put("Impedance", getIntegerValue(impedanceTxt)); + output.put("BMI", getDecimalValue(bmiTxt)); + output.put("BMR", getIntegerValue(bmrTxt)); + output.put("FatFreeMass", getDecimalValue(ffmTxt)); + output.put("FatMass", getDecimalValue(fatMassTxt)); + output.put("TotalBodyWater", getDecimalValue(tbwTxt)); + output.put("FatPercentage", getDecimalValue(fatPctTxt)); + output.put("Gender", new Data(DataType.TEXT, genderTxt.getText())); + output.put("Height", getDecimalValue(heightTxt)); + output.put("Age", getIntegerValue(ageTxt)); + + instrumentExecutionService.addOutputParameterValues(output); + log.info("Sending output of tanita to server done..."); + exitUI(); + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/test/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunnerTest.java b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/test/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunnerTest.java index 8a653059d..2a3ab119f 100644 --- a/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/test/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunnerTest.java +++ b/onyx-modules/jade/instrument-parent/interface-bioimpedance-tanita-tbf310/src/test/java/org/obiba/onyx/jade/instrument/tanita/Tbf310InstrumentRunnerTest.java @@ -1,74 +1,83 @@ -package org.obiba.onyx.jade.instrument.tanita; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; - -import java.util.Map; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.util.data.Data; - -public class Tbf310InstrumentRunnerTest { - - private ExternalAppLauncherHelper externalAppHelper; - private Tbf310InstrumentRunner tbf310InstrumentRunner; - private InstrumentExecutionService instrumentExecutionServiceMock; - - @Before - public void setUp() throws Exception{ - - tbf310InstrumentRunner = new Tbf310InstrumentRunner(); - - // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), - // so for now, use the class itself with the launch method overridden to - // do nothing. - externalAppHelper = new ExternalAppLauncherHelper() { - public void launch() { - // do nothing - } - }; - tbf310InstrumentRunner.setExternalAppHelper(externalAppHelper); - - // Create a mock instrumentExecutionService for testing. - instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); - tbf310InstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); - } - - - /** - * Test the behaviour of the run method, when the instrument's output is - * successfully retrieved (normal case). - */ - @Test - public void testRun(){ - externalAppHelper.launch(); - - // Parse the results - tbf310InstrumentRunner.setTanitaData(tbf310InstrumentRunner.parseTanitaData("0,2,170,110.6,431,28.4,31.4,79.2,58.0,27,32.3,9771")); - - // Compare the values read with the ones from the input stream - Assert.assertEquals("STANDARD",tbf310InstrumentRunner.getBodyTypeTxt().getText()); - Assert.assertEquals("FEMALE",tbf310InstrumentRunner.getGenderTxt().getText()); - Assert.assertEquals(String.valueOf(170),tbf310InstrumentRunner.getHeightTxt().getText()); - Assert.assertEquals(String.valueOf(110.6),tbf310InstrumentRunner.getWeightTxt().getText()); - Assert.assertEquals(String.valueOf(431),tbf310InstrumentRunner.getImpedanceTxt().getText()); - Assert.assertEquals(String.valueOf(28.4),tbf310InstrumentRunner.getFatPctTxt().getText()); - Assert.assertEquals(String.valueOf(31.4),tbf310InstrumentRunner.getFatMassTxt().getText()); - Assert.assertEquals(String.valueOf(79.2),tbf310InstrumentRunner.getFfmTxt().getText()); - Assert.assertEquals(String.valueOf(58.0),tbf310InstrumentRunner.getTbwTxt().getText()); - Assert.assertEquals(String.valueOf(27),tbf310InstrumentRunner.getAgeTxt().getText()); - Assert.assertEquals(String.valueOf(32.3),tbf310InstrumentRunner.getBmiTxt().getText()); - Assert.assertEquals(String.valueOf(9771),tbf310InstrumentRunner.getBmrTxt().getText()); - - instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); - } - - @Test - public void testShutdown(){ - tbf310InstrumentRunner.shutdown(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.tanita; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createMock; + +import java.util.Map; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.util.data.Data; + +public class Tbf310InstrumentRunnerTest { + + private ExternalAppLauncherHelper externalAppHelper; + private Tbf310InstrumentRunner tbf310InstrumentRunner; + private InstrumentExecutionService instrumentExecutionServiceMock; + + @Before + public void setUp() throws Exception{ + + tbf310InstrumentRunner = new Tbf310InstrumentRunner(); + + // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), + // so for now, use the class itself with the launch method overridden to + // do nothing. + externalAppHelper = new ExternalAppLauncherHelper() { + public void launch() { + // do nothing + } + }; + tbf310InstrumentRunner.setExternalAppHelper(externalAppHelper); + + // Create a mock instrumentExecutionService for testing. + instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); + tbf310InstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); + } + + + /** + * Test the behaviour of the run method, when the instrument's output is + * successfully retrieved (normal case). + */ + @Test + public void testRun(){ + externalAppHelper.launch(); + + // Parse the results + tbf310InstrumentRunner.setTanitaData(tbf310InstrumentRunner.parseTanitaData("0,2,170,110.6,431,28.4,31.4,79.2,58.0,27,32.3,9771")); + + // Compare the values read with the ones from the input stream + Assert.assertEquals("STANDARD",tbf310InstrumentRunner.getBodyTypeTxt().getText()); + Assert.assertEquals("FEMALE",tbf310InstrumentRunner.getGenderTxt().getText()); + Assert.assertEquals(String.valueOf(170),tbf310InstrumentRunner.getHeightTxt().getText()); + Assert.assertEquals(String.valueOf(110.6),tbf310InstrumentRunner.getWeightTxt().getText()); + Assert.assertEquals(String.valueOf(431),tbf310InstrumentRunner.getImpedanceTxt().getText()); + Assert.assertEquals(String.valueOf(28.4),tbf310InstrumentRunner.getFatPctTxt().getText()); + Assert.assertEquals(String.valueOf(31.4),tbf310InstrumentRunner.getFatMassTxt().getText()); + Assert.assertEquals(String.valueOf(79.2),tbf310InstrumentRunner.getFfmTxt().getText()); + Assert.assertEquals(String.valueOf(58.0),tbf310InstrumentRunner.getTbwTxt().getText()); + Assert.assertEquals(String.valueOf(27),tbf310InstrumentRunner.getAgeTxt().getText()); + Assert.assertEquals(String.valueOf(32.3),tbf310InstrumentRunner.getBmiTxt().getText()); + Assert.assertEquals(String.valueOf(9771),tbf310InstrumentRunner.getBmrTxt().getText()); + + instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); + } + + @Test + public void testShutdown(){ + tbf310InstrumentRunner.shutdown(); + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-bonedensity-achillesexpress/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/AchillesExpressInstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-bonedensity-achillesexpress/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/AchillesExpressInstrumentRunner.java index fe71369e6..549c19199 100644 --- a/onyx-modules/jade/instrument-parent/interface-bonedensity-achillesexpress/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/AchillesExpressInstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-bonedensity-achillesexpress/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/AchillesExpressInstrumentRunner.java @@ -1,189 +1,198 @@ -package org.obiba.onyx.jade.instrument.gehealthcare; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.InstrumentRunner; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.ResultSetExtractor; - -public class AchillesExpressInstrumentRunner implements InstrumentRunner, InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(AchillesExpressInstrumentRunner.class); - - // Injected by spring. - protected InstrumentExecutionService instrumentExecutionService; - - protected ExternalAppLauncherHelper externalAppHelper; - - private JdbcTemplate achillesExpressDb; - - private String participantID; - private String participantFirstName; - private String participantLastName; - private Date participantBirthDate; - private String participantGender; - - public InstrumentExecutionService getInstrumentExecutionService() { - return instrumentExecutionService; - } - - public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { - this.instrumentExecutionService = instrumentExecutionService; - } - - public ExternalAppLauncherHelper getExternalAppHelper() { - return externalAppHelper; - } - - public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { - this.externalAppHelper = externalAppHelper; - } - - public JdbcTemplate getAchillesExpressDb() { - return achillesExpressDb; - } - - public void setAchillesExpressDb(JdbcTemplate achillesExpressDb) { - this.achillesExpressDb = achillesExpressDb; - } - - public void afterPropertiesSet() throws Exception { - participantFirstName = instrumentExecutionService.getParticipantFirstName(); - participantLastName = instrumentExecutionService.getParticipantLastName(); - participantID = instrumentExecutionService.getParticipantID(); - participantBirthDate = instrumentExecutionService.getParticipantBirthDate(); - participantGender = instrumentExecutionService.getParticipantGender(); - } - - public void setAchillesExpressConfig() { - - achillesExpressDb.update("update Configuration set CompressPrompt = ?, BackupPrompt = ?, TargetDevice = ? ", new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, 2); - ps.setInt(2, 2); - ps.setString(3, "Express"); - } - }); - - } - - public void setParticipantData() { - - achillesExpressDb.update("insert into Patients ( Chart_Num, FName, LName, DOB, Sex, Foot ) values( ?, ?, ?, ?, ?, ? )", new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, participantID); - ps.setString(2, participantFirstName); - ps.setString(3, participantLastName); - ps.setDate(4, new java.sql.Date(participantBirthDate.getTime())); - - if(participantGender.equals("MALE")) { - ps.setString(5, "M"); - } else { - ps.setString(5, "F"); - } - - ps.setString(6, (String) instrumentExecutionService.getInputParameterValue("foot_scanned").getValue()); - } - }); - - } - - protected void deleteLocalData() { - achillesExpressDb.update("delete from Results"); - achillesExpressDb.update("delete from Patients"); - } - - @SuppressWarnings("unchecked") - private Map retrieveDeviceData() { - - log.info("retrieveDeviceData"); - - return (Map) achillesExpressDb.query("select assessment, fxrisk, total, tscore, zscore, agematched, percentnormal, sidescanned, stiffnessindex, patients.chart_num, results.SOS, results.BUA, achillesbitmap, achillesbitmap2, appversion, roi_x, roi_y, roi_s, patients.Chart_Num, patients.FName, patients.LName, patients.Sex, patients.DOB from results, patients where results.chart_num = patients.chart_num and patients.chart_num = ?", new PreparedStatementSetter() { - - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, participantID); - } - - }, - - new ResultSetExtractor() { - - public Object extractData(ResultSet rs) throws SQLException { - - rs.next(); - - Map boneDensityData = new HashMap(); - boneDensityData.put("Participant Barcode", DataBuilder.buildText(rs.getString("Chart_Num"))); - boneDensityData.put("Participant First Name", DataBuilder.buildText(rs.getString("FName"))); - boneDensityData.put("Participant Last Name", DataBuilder.buildText(rs.getString("LName"))); - boneDensityData.put("Participant Date of Birth", DataBuilder.buildDate(rs.getDate("DOB"))); - - String gender = rs.getString("Sex").equals("M")?"MALE":"FEMALE"; - boneDensityData.put("Participant Gender", DataBuilder.buildText(gender)); - - boneDensityData.put("Assessment", DataBuilder.buildDecimal(rs.getDouble("assessment"))); - boneDensityData.put("Fracture Risk", DataBuilder.buildDecimal(rs.getDouble("fxrisk"))); - boneDensityData.put("Stiffness Index Result", DataBuilder.buildDecimal(rs.getDouble("total"))); - boneDensityData.put("T-Score", DataBuilder.buildDecimal(rs.getDouble("tscore"))); - boneDensityData.put("Z-Score", DataBuilder.buildDecimal(rs.getDouble("zscore"))); - boneDensityData.put("% Age Matched", DataBuilder.buildDecimal(rs.getDouble("agematched"))); - boneDensityData.put("% Young Adult", DataBuilder.buildDecimal(rs.getDouble("percentnormal"))); - boneDensityData.put("Foot Scanned", DataBuilder.buildText(rs.getString("sidescanned"))); - boneDensityData.put("Stiffness Index", DataBuilder.buildDecimal(rs.getDouble("stiffnessindex"))); - boneDensityData.put("Speed of Ultrasound", DataBuilder.buildDecimal( rs.getDouble("SOS"))); - boneDensityData.put("Broadband Ultrasound Attenuation",DataBuilder.buildDecimal( rs.getDouble("BUA"))); - boneDensityData.put("Achilles Software Version", DataBuilder.buildText( rs.getString("appversion"))); - boneDensityData.put("Region of Intersection X coordinate", DataBuilder.buildInteger(rs.getLong("roi_x"))); - boneDensityData.put("Region of Intersection Y coordinate",DataBuilder.buildInteger( rs.getLong("roi_y"))); - boneDensityData.put("Region of Intersection Z coordinate", DataBuilder.buildInteger(rs.getLong("roi_s"))); - boneDensityData.put("Stiffness Index graph", DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap"))); - boneDensityData.put("Ultrasound Graphic", DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap2"))); - - return boneDensityData; - } - - }); - - } - - public void sendDataToServer(Map data) { - instrumentExecutionService.addOutputParameterValues(data); - } - - public void initialize() { - log.info("Cleaning up local database"); - deleteLocalData(); - log.info("Setting Achilles Express configuration"); - setAchillesExpressConfig(); - log.info("Sending participant data"); - setParticipantData(); - } - - public void run() { - log.info("Launching Achilles Express software"); - externalAppHelper.launch(); - log.info("Retrieving measurements"); - Map data = retrieveDeviceData(); - log.info("Sending data to server"); - sendDataToServer(data); - } - - public void shutdown() { - log.info("Cleaning up local database"); - deleteLocalData(); - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.gehealthcare; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.InstrumentRunner; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementSetter; +import org.springframework.jdbc.core.ResultSetExtractor; + +public class AchillesExpressInstrumentRunner implements InstrumentRunner, InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(AchillesExpressInstrumentRunner.class); + + // Injected by spring. + protected InstrumentExecutionService instrumentExecutionService; + + protected ExternalAppLauncherHelper externalAppHelper; + + private JdbcTemplate achillesExpressDb; + + private String participantID; + private String participantFirstName; + private String participantLastName; + private Date participantBirthDate; + private String participantGender; + + public InstrumentExecutionService getInstrumentExecutionService() { + return instrumentExecutionService; + } + + public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { + this.instrumentExecutionService = instrumentExecutionService; + } + + public ExternalAppLauncherHelper getExternalAppHelper() { + return externalAppHelper; + } + + public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { + this.externalAppHelper = externalAppHelper; + } + + public JdbcTemplate getAchillesExpressDb() { + return achillesExpressDb; + } + + public void setAchillesExpressDb(JdbcTemplate achillesExpressDb) { + this.achillesExpressDb = achillesExpressDb; + } + + public void afterPropertiesSet() throws Exception { + participantFirstName = instrumentExecutionService.getParticipantFirstName(); + participantLastName = instrumentExecutionService.getParticipantLastName(); + participantID = instrumentExecutionService.getParticipantID(); + participantBirthDate = instrumentExecutionService.getParticipantBirthDate(); + participantGender = instrumentExecutionService.getParticipantGender(); + } + + public void setAchillesExpressConfig() { + + achillesExpressDb.update("update Configuration set CompressPrompt = ?, BackupPrompt = ?, TargetDevice = ? ", new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, 2); + ps.setInt(2, 2); + ps.setString(3, "Express"); + } + }); + + } + + public void setParticipantData() { + + achillesExpressDb.update("insert into Patients ( Chart_Num, FName, LName, DOB, Sex, Foot ) values( ?, ?, ?, ?, ?, ? )", new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setString(1, participantID); + ps.setString(2, participantFirstName); + ps.setString(3, participantLastName); + ps.setDate(4, new java.sql.Date(participantBirthDate.getTime())); + + if(participantGender.equals("MALE")) { + ps.setString(5, "M"); + } else { + ps.setString(5, "F"); + } + + ps.setString(6, (String) instrumentExecutionService.getInputParameterValue("foot_scanned").getValue()); + } + }); + + } + + protected void deleteLocalData() { + achillesExpressDb.update("delete from Results"); + achillesExpressDb.update("delete from Patients"); + } + + @SuppressWarnings("unchecked") + private Map retrieveDeviceData() { + + log.info("retrieveDeviceData"); + + return (Map) achillesExpressDb.query("select assessment, fxrisk, total, tscore, zscore, agematched, percentnormal, sidescanned, stiffnessindex, patients.chart_num, results.SOS, results.BUA, achillesbitmap, achillesbitmap2, appversion, roi_x, roi_y, roi_s, patients.Chart_Num, patients.FName, patients.LName, patients.Sex, patients.DOB from results, patients where results.chart_num = patients.chart_num and patients.chart_num = ?", new PreparedStatementSetter() { + + public void setValues(PreparedStatement ps) throws SQLException { + ps.setString(1, participantID); + } + + }, + + new ResultSetExtractor() { + + public Object extractData(ResultSet rs) throws SQLException { + + rs.next(); + + Map boneDensityData = new HashMap(); + boneDensityData.put("Participant Barcode", DataBuilder.buildText(rs.getString("Chart_Num"))); + boneDensityData.put("Participant First Name", DataBuilder.buildText(rs.getString("FName"))); + boneDensityData.put("Participant Last Name", DataBuilder.buildText(rs.getString("LName"))); + boneDensityData.put("Participant Date of Birth", DataBuilder.buildDate(rs.getDate("DOB"))); + + String gender = rs.getString("Sex").equals("M")?"MALE":"FEMALE"; + boneDensityData.put("Participant Gender", DataBuilder.buildText(gender)); + + boneDensityData.put("Assessment", DataBuilder.buildDecimal(rs.getDouble("assessment"))); + boneDensityData.put("Fracture Risk", DataBuilder.buildDecimal(rs.getDouble("fxrisk"))); + boneDensityData.put("Stiffness Index Result", DataBuilder.buildDecimal(rs.getDouble("total"))); + boneDensityData.put("T-Score", DataBuilder.buildDecimal(rs.getDouble("tscore"))); + boneDensityData.put("Z-Score", DataBuilder.buildDecimal(rs.getDouble("zscore"))); + boneDensityData.put("% Age Matched", DataBuilder.buildDecimal(rs.getDouble("agematched"))); + boneDensityData.put("% Young Adult", DataBuilder.buildDecimal(rs.getDouble("percentnormal"))); + boneDensityData.put("Foot Scanned", DataBuilder.buildText(rs.getString("sidescanned"))); + boneDensityData.put("Stiffness Index", DataBuilder.buildDecimal(rs.getDouble("stiffnessindex"))); + boneDensityData.put("Speed of Ultrasound", DataBuilder.buildDecimal( rs.getDouble("SOS"))); + boneDensityData.put("Broadband Ultrasound Attenuation",DataBuilder.buildDecimal( rs.getDouble("BUA"))); + boneDensityData.put("Achilles Software Version", DataBuilder.buildText( rs.getString("appversion"))); + boneDensityData.put("Region of Intersection X coordinate", DataBuilder.buildInteger(rs.getLong("roi_x"))); + boneDensityData.put("Region of Intersection Y coordinate",DataBuilder.buildInteger( rs.getLong("roi_y"))); + boneDensityData.put("Region of Intersection Z coordinate", DataBuilder.buildInteger(rs.getLong("roi_s"))); + boneDensityData.put("Stiffness Index graph", DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap"))); + boneDensityData.put("Ultrasound Graphic", DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap2"))); + + return boneDensityData; + } + + }); + + } + + public void sendDataToServer(Map data) { + instrumentExecutionService.addOutputParameterValues(data); + } + + public void initialize() { + log.info("Cleaning up local database"); + deleteLocalData(); + log.info("Setting Achilles Express configuration"); + setAchillesExpressConfig(); + log.info("Sending participant data"); + setParticipantData(); + } + + public void run() { + log.info("Launching Achilles Express software"); + externalAppHelper.launch(); + log.info("Retrieving measurements"); + Map data = retrieveDeviceData(); + log.info("Sending data to server"); + sendDataToServer(data); + } + + public void shutdown() { + log.info("Cleaning up local database"); + deleteLocalData(); + } + +} diff --git a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentResultParser.java b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentResultParser.java index 20e1e84a4..7c813b26e 100644 --- a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentResultParser.java +++ b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentResultParser.java @@ -1,305 +1,314 @@ -package org.obiba.onyx.jade.instrument.gehealthcare; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * Inspired from class Interface_CaG.EcgCollector by dbujold Parse ecg xml result file and return a object containing - * the data - * @author acarey - */ - -public class CardiosoftInstrumentResultParser { - - // The whole XML document - private String xmlDocument; - - private String time; - - private String date; - - private String diagnosis; - - private String filterSetting; - - // Resting ECG Measurements - private String diagnosisVersion; - - private Long ventricularRate; - - private Long pQInterval; - - private Long pDuration; - - private Long qRsDuration; - - private Long qTInterval; - - private Long qTCInterval; - - private Long rRInterval; - - private Long pPInterval; - - private Long pAxis; - - private Long rAxis; - - private Long tAxis; - - private Long qRSNum; - - private Long pOnset; - - private Long pOffset; - - private Long qOnset; - - private Long qOffset; - - private Long tOffset; - - private XPath xpath; - - private Document doc; - - /** - * Constructor parsing the xml file - * @param pFileStream - * @throws IOException - */ - @SuppressWarnings("deprecation") - public CardiosoftInstrumentResultParser(InputStream pFileStream) { - try { - // First read the whole file to keep a copy in the EcgCollector object. - BufferedReader fileReader = new BufferedReader(new InputStreamReader(pFileStream)); - StringBuilder xmlFileContent = new StringBuilder(); - String wOneLine; - int i = 0; - while((wOneLine = fileReader.readLine()) != null) { - xmlFileContent.append(wOneLine + "\n"); - i++; - } - xmlDocument = xmlFileContent.toString(); - - // Now create a stream using the copy of the XML file for the XPath analysis - InputStream xmlStream = new java.io.StringBufferInputStream(xmlDocument); - DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); - domFactory.setNamespaceAware(true); - DocumentBuilder builder = domFactory.newDocumentBuilder(); - doc = builder.parse(xmlStream); - - XPathFactory factory = XPathFactory.newInstance(); - xpath = factory.newXPath(); - - extractDateTime(); - extractInterpretation(); - extractFilterSetting(); - extractRestingEcgMeasurements(); - } catch(XPathExpressionException e) { - throw new RuntimeException("Invalid XPath expression. Stopping XML data extraction.", e); - } catch(ParserConfigurationException e) { - throw new RuntimeException("An error has occured while trying to initialize the XPath parser.", e); - } catch(SAXException e) { - throw new RuntimeException("An error has occured while trying to initialize the XPath parser.", e); - } catch(IOException ioEx) { - throw new RuntimeException("Error: CardiosoftInstrumentResultParser IOException ", ioEx); - } - } - - public String getXmlDocument() { - return xmlDocument; - } - - public String getTime() { - return time; - } - - public String getDate() { - return date; - } - - public String getDiagnosis() { - return diagnosis; - } - - public String getFilterSetting() { - return filterSetting; - } - - public String getDiagnosisVersion() { - return diagnosisVersion; - } - - public Long getVentricularRate() { - return ventricularRate; - } - - public Long getPQInterval() { - return pQInterval; - } - - public Long getPDuration() { - return pDuration; - } - - public Long getQRsDuration() { - return qRsDuration; - } - - public Long getQTInterval() { - return qTInterval; - } - - public Long getQTCInterval() { - return qTCInterval; - } - - public Long getRRInterval() { - return rRInterval; - } - - public Long getPPInterval() { - return pPInterval; - } - - public Long getPAxis() { - return pAxis; - } - - public Long getRAxis() { - return rAxis; - } - - public Long getTAxis() { - return tAxis; - } - - public Long getQRSNum() { - return qRSNum; - } - - public Long getPOnset() { - return pOnset; - } - - public Long getPOffset() { - return pOffset; - } - - public Long getQOnset() { - return qOnset; - } - - public Long getQOffset() { - return qOffset; - } - - public Long getTOffset() { - return tOffset; - } - - /** - * Extracts date and time of measurement. - * @throws XPathExpressionException - */ - private void extractDateTime() throws XPathExpressionException { - - time = xpath.evaluate("concat(//ObservationDateTime/Hour/text(), ':', //ObservationDateTime/Minute/text(), ':', //ObservationDateTime/Second/text())", doc, XPathConstants.STRING).toString(); - - date = xpath.evaluate("concat(//ObservationDateTime/Year/text(), '-', //ObservationDateTime/Month/text(), '-', //ObservationDateTime/Day/text())", doc, XPathConstants.STRING).toString(); - } - - /** - * Extracts software's data interpretation. - * @throws XPathExpressionException - */ - private void extractInterpretation() throws XPathExpressionException { - - // Extracting Diagnosis - Object diagnosisNode = xpath.evaluate("//Interpretation/Diagnosis/DiagnosisText/text()", doc, XPathConstants.NODESET); - StringBuilder diagnosisSb = new StringBuilder(); - NodeList nodes = (NodeList) diagnosisNode; - for(int i = 0; i < nodes.getLength(); i++) { - diagnosisSb.append(nodes.item(i).getNodeValue()); - if(i + 1 < nodes.getLength()) { - diagnosisSb.append("\n"); - } - } - diagnosis = diagnosisSb.toString(); - - // Extracting Conclusion - Object conclusionNode = xpath.evaluate("//Interpretation/Conclusion/ConclusionText/text()", doc, XPathConstants.NODESET); - StringBuilder conclusionSb = new StringBuilder(); - nodes = (NodeList) conclusionNode; - for(int i = 0; i < nodes.getLength(); i++) { - conclusionSb.append(nodes.item(i).getNodeValue()); - if(i + 1 < nodes.getLength()) { - conclusionSb.append("\n"); - } - } - - } - - /** - * Extracts filter data. - */ - private void extractFilterSetting() throws XPathExpressionException { - filterSetting = xpath.evaluate("concat('Cublic Spline: ', //FilterSetting/CubicSpline/text(), " + " '\nFilter50Hz: ', //FilterSetting/Filter50Hz/text(), " + " '\nFilter60Hz: ', //FilterSetting/Filter60Hz/text(), " + " '\nLowPass (', //FilterSetting/LowPass/attribute::units, '): ', //FilterSetting/LowPass/text(), " + " '\nHighPass (', //FilterSetting/HighPass/attribute::units, '): ', //FilterSetting/HighPass/text())", doc, XPathConstants.STRING).toString(); - } - - /** - * Extract all data located under the RestingEcgMeasurements tag. - * @throws XPathExpressionException - */ - private void extractRestingEcgMeasurements() throws XPathExpressionException { - diagnosisVersion = xpath.evaluate("//RestingECGMeasurements/DiagnosisVersion/text()", doc, XPathConstants.STRING).toString(); - ventricularRate = extractMeasurement("VentricularRate"); - pQInterval = extractMeasurement("PQInterval"); - pDuration = extractMeasurement("PDuration"); - qRsDuration = extractMeasurement("QRSDuration"); - qTInterval = extractMeasurement("QTInterval"); - qTCInterval = extractMeasurement("QTCInterval"); - rRInterval = extractMeasurement("RRInterval"); - pPInterval = extractMeasurement("PPInterval"); - pAxis = extractMeasurement("PAxis"); - rAxis = extractMeasurement("RAxis"); - tAxis = extractMeasurement("TAxis"); - qRSNum = Long.valueOf(xpath.evaluate("//RestingECGMeasurements/QRSNum/text()", doc, XPathConstants.STRING).toString()); - pOnset = extractMeasurement("POnset"); - pOffset = extractMeasurement("POffset"); - qOnset = extractMeasurement("QOnset"); - qOffset = extractMeasurement("QOffset"); - tOffset = extractMeasurement("TOffset"); - } - - /** - * Extracts data corresponding to the parameter - * @param tagName - * @return the result as a Long - * @throws XPathExpressionException - */ - private Long extractMeasurement(String tagName) throws XPathExpressionException { - String measurement = xpath.evaluate("//RestingECGMeasurements/" + tagName + "/text()", doc, XPathConstants.STRING).toString(); - - if(measurement.equals("")) { - return null; - } else { - return Long.valueOf(measurement); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.gehealthcare; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +/** + * Inspired from class Interface_CaG.EcgCollector by dbujold Parse ecg xml result file and return a object containing + * the data + * @author acarey + */ + +public class CardiosoftInstrumentResultParser { + + // The whole XML document + private String xmlDocument; + + private String time; + + private String date; + + private String diagnosis; + + private String filterSetting; + + // Resting ECG Measurements + private String diagnosisVersion; + + private Long ventricularRate; + + private Long pQInterval; + + private Long pDuration; + + private Long qRsDuration; + + private Long qTInterval; + + private Long qTCInterval; + + private Long rRInterval; + + private Long pPInterval; + + private Long pAxis; + + private Long rAxis; + + private Long tAxis; + + private Long qRSNum; + + private Long pOnset; + + private Long pOffset; + + private Long qOnset; + + private Long qOffset; + + private Long tOffset; + + private XPath xpath; + + private Document doc; + + /** + * Constructor parsing the xml file + * @param pFileStream + * @throws IOException + */ + @SuppressWarnings("deprecation") + public CardiosoftInstrumentResultParser(InputStream pFileStream) { + try { + // First read the whole file to keep a copy in the EcgCollector object. + BufferedReader fileReader = new BufferedReader(new InputStreamReader(pFileStream)); + StringBuilder xmlFileContent = new StringBuilder(); + String wOneLine; + int i = 0; + while((wOneLine = fileReader.readLine()) != null) { + xmlFileContent.append(wOneLine + "\n"); + i++; + } + xmlDocument = xmlFileContent.toString(); + + // Now create a stream using the copy of the XML file for the XPath analysis + InputStream xmlStream = new java.io.StringBufferInputStream(xmlDocument); + DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); + domFactory.setNamespaceAware(true); + DocumentBuilder builder = domFactory.newDocumentBuilder(); + doc = builder.parse(xmlStream); + + XPathFactory factory = XPathFactory.newInstance(); + xpath = factory.newXPath(); + + extractDateTime(); + extractInterpretation(); + extractFilterSetting(); + extractRestingEcgMeasurements(); + } catch(XPathExpressionException e) { + throw new RuntimeException("Invalid XPath expression. Stopping XML data extraction.", e); + } catch(ParserConfigurationException e) { + throw new RuntimeException("An error has occured while trying to initialize the XPath parser.", e); + } catch(SAXException e) { + throw new RuntimeException("An error has occured while trying to initialize the XPath parser.", e); + } catch(IOException ioEx) { + throw new RuntimeException("Error: CardiosoftInstrumentResultParser IOException ", ioEx); + } + } + + public String getXmlDocument() { + return xmlDocument; + } + + public String getTime() { + return time; + } + + public String getDate() { + return date; + } + + public String getDiagnosis() { + return diagnosis; + } + + public String getFilterSetting() { + return filterSetting; + } + + public String getDiagnosisVersion() { + return diagnosisVersion; + } + + public Long getVentricularRate() { + return ventricularRate; + } + + public Long getPQInterval() { + return pQInterval; + } + + public Long getPDuration() { + return pDuration; + } + + public Long getQRsDuration() { + return qRsDuration; + } + + public Long getQTInterval() { + return qTInterval; + } + + public Long getQTCInterval() { + return qTCInterval; + } + + public Long getRRInterval() { + return rRInterval; + } + + public Long getPPInterval() { + return pPInterval; + } + + public Long getPAxis() { + return pAxis; + } + + public Long getRAxis() { + return rAxis; + } + + public Long getTAxis() { + return tAxis; + } + + public Long getQRSNum() { + return qRSNum; + } + + public Long getPOnset() { + return pOnset; + } + + public Long getPOffset() { + return pOffset; + } + + public Long getQOnset() { + return qOnset; + } + + public Long getQOffset() { + return qOffset; + } + + public Long getTOffset() { + return tOffset; + } + + /** + * Extracts date and time of measurement. + * @throws XPathExpressionException + */ + private void extractDateTime() throws XPathExpressionException { + + time = xpath.evaluate("concat(//ObservationDateTime/Hour/text(), ':', //ObservationDateTime/Minute/text(), ':', //ObservationDateTime/Second/text())", doc, XPathConstants.STRING).toString(); + + date = xpath.evaluate("concat(//ObservationDateTime/Year/text(), '-', //ObservationDateTime/Month/text(), '-', //ObservationDateTime/Day/text())", doc, XPathConstants.STRING).toString(); + } + + /** + * Extracts software's data interpretation. + * @throws XPathExpressionException + */ + private void extractInterpretation() throws XPathExpressionException { + + // Extracting Diagnosis + Object diagnosisNode = xpath.evaluate("//Interpretation/Diagnosis/DiagnosisText/text()", doc, XPathConstants.NODESET); + StringBuilder diagnosisSb = new StringBuilder(); + NodeList nodes = (NodeList) diagnosisNode; + for(int i = 0; i < nodes.getLength(); i++) { + diagnosisSb.append(nodes.item(i).getNodeValue()); + if(i + 1 < nodes.getLength()) { + diagnosisSb.append("\n"); + } + } + diagnosis = diagnosisSb.toString(); + + // Extracting Conclusion + Object conclusionNode = xpath.evaluate("//Interpretation/Conclusion/ConclusionText/text()", doc, XPathConstants.NODESET); + StringBuilder conclusionSb = new StringBuilder(); + nodes = (NodeList) conclusionNode; + for(int i = 0; i < nodes.getLength(); i++) { + conclusionSb.append(nodes.item(i).getNodeValue()); + if(i + 1 < nodes.getLength()) { + conclusionSb.append("\n"); + } + } + + } + + /** + * Extracts filter data. + */ + private void extractFilterSetting() throws XPathExpressionException { + filterSetting = xpath.evaluate("concat('Cublic Spline: ', //FilterSetting/CubicSpline/text(), " + " '\nFilter50Hz: ', //FilterSetting/Filter50Hz/text(), " + " '\nFilter60Hz: ', //FilterSetting/Filter60Hz/text(), " + " '\nLowPass (', //FilterSetting/LowPass/attribute::units, '): ', //FilterSetting/LowPass/text(), " + " '\nHighPass (', //FilterSetting/HighPass/attribute::units, '): ', //FilterSetting/HighPass/text())", doc, XPathConstants.STRING).toString(); + } + + /** + * Extract all data located under the RestingEcgMeasurements tag. + * @throws XPathExpressionException + */ + private void extractRestingEcgMeasurements() throws XPathExpressionException { + diagnosisVersion = xpath.evaluate("//RestingECGMeasurements/DiagnosisVersion/text()", doc, XPathConstants.STRING).toString(); + ventricularRate = extractMeasurement("VentricularRate"); + pQInterval = extractMeasurement("PQInterval"); + pDuration = extractMeasurement("PDuration"); + qRsDuration = extractMeasurement("QRSDuration"); + qTInterval = extractMeasurement("QTInterval"); + qTCInterval = extractMeasurement("QTCInterval"); + rRInterval = extractMeasurement("RRInterval"); + pPInterval = extractMeasurement("PPInterval"); + pAxis = extractMeasurement("PAxis"); + rAxis = extractMeasurement("RAxis"); + tAxis = extractMeasurement("TAxis"); + qRSNum = Long.valueOf(xpath.evaluate("//RestingECGMeasurements/QRSNum/text()", doc, XPathConstants.STRING).toString()); + pOnset = extractMeasurement("POnset"); + pOffset = extractMeasurement("POffset"); + qOnset = extractMeasurement("QOnset"); + qOffset = extractMeasurement("QOffset"); + tOffset = extractMeasurement("TOffset"); + } + + /** + * Extracts data corresponding to the parameter + * @param tagName + * @return the result as a Long + * @throws XPathExpressionException + */ + private Long extractMeasurement(String tagName) throws XPathExpressionException { + String measurement = xpath.evaluate("//RestingECGMeasurements/" + tagName + "/text()", doc, XPathConstants.STRING).toString(); + + if(measurement.equals("")) { + return null; + } else { + return Long.valueOf(measurement); + } + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunner.java index 134a30986..0c4e40137 100644 --- a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunner.java @@ -1,239 +1,248 @@ -package org.obiba.onyx.jade.instrument.gehealthcare; - -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FilenameFilter; -import java.util.HashMap; -import java.util.Map; - -import org.obiba.onyx.jade.client.JnlpClient; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.InstrumentRunner; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.jade.util.FileUtil; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Specified instrument runner for the ECG - * @author acarey - */ - -public class CardiosoftInstrumentRunner implements InstrumentRunner { - - private static final Logger log = LoggerFactory.getLogger(JnlpClient.class); - - // Injected by spring. - protected InstrumentExecutionService instrumentExecutionService; - - protected ExternalAppLauncherHelper externalAppHelper; - - private String cardioPath; - - private String initPath; - - private String databasePath; - - private String exportPath; - - private String settingsFileName; - - private String xmlFileName; - - private String pdfFileName; - - public InstrumentExecutionService getInstrumentExecutionService() { - return instrumentExecutionService; - } - - public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { - this.instrumentExecutionService = instrumentExecutionService; - } - - public ExternalAppLauncherHelper getExternalAppHelper() { - return externalAppHelper; - } - - public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { - this.externalAppHelper = externalAppHelper; - } - - public String getCardioPath() { - return cardioPath; - } - - public void setCardioPath(String cardioPath) { - this.cardioPath = cardioPath; - } - - public String getInitPath() { - return initPath; - } - - public void setInitPath(String initPath) { - this.initPath = initPath; - } - - public String getDatabasePath() { - return databasePath; - } - - public void setDatabasePath(String databasePath) { - this.databasePath = databasePath; - } - - public String getExportPath() { - return exportPath; - } - - public void setExportPath(String exportPath) { - this.exportPath = exportPath; - } - - public String getSettingsFileName() { - return settingsFileName; - } - - public void setSettingsFileName(String settingsFileName) { - this.settingsFileName = settingsFileName; - } - - public String getXmlFileName() { - return xmlFileName; - } - - public void setXmlFileName(String xmlFileName) { - this.xmlFileName = xmlFileName; - } - - public String getPdfFileName() { - return pdfFileName; - } - - public void setPdfFileName(String pdfFileName) { - this.pdfFileName = pdfFileName; - } - - /** - * Replace the instrument configuration file if needed Delete the result database and files - * @throws Exception - */ - protected void deleteDeviceData() { - - // Overwrite the CardioSoft configuration file - File backupSettingsFile = new File(getInitPath(), getSettingsFileName()); - File currentSettingsFile = new File(getCardioPath(), getSettingsFileName()); - try { - if(backupSettingsFile.exists()) { - FileUtil.copyFile(backupSettingsFile, currentSettingsFile); - } else { - new File(getInitPath()).mkdir(); - FileUtil.copyFile(currentSettingsFile, backupSettingsFile); - } - } catch(Exception ex) { - throw new RuntimeException("Error initializing ECG cardio.ini file", ex); - } - - // Initialize the CardioSoft database - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File dir, String name) { - return (name.endsWith(".BTR")); - } - }; - - try { - File[] backupDatabaseFiles = new File(getInitPath()).listFiles(filter); - if(backupDatabaseFiles.length > 0) { - for(int i = 0; i < backupDatabaseFiles.length; i++) { - FileUtil.copyFile(backupDatabaseFiles[i], new File(getDatabasePath(), backupDatabaseFiles[i].getName())); - } - } else { - File[] databaseFiles = new File(getDatabasePath()).listFiles(filter); - for(int i = 0; i < databaseFiles.length; i++) { - FileUtil.copyFile(databaseFiles[i], new File(getInitPath(), databaseFiles[i].getName())); - } - } - } catch(Exception couldNotInitDbs) { - throw new RuntimeException("Error initializing ECG database files", couldNotInitDbs); - } - - // Delete generated reports - File reportFile = new File(getExportPath(), getXmlFileName()); - reportFile.delete(); - reportFile = new File(getExportPath(), getPdfFileName()); - reportFile.delete(); - } - - /** - * Place the results and xml and pdf files into a map object to send them to the server for persistence - * @param resultParser - * @throws Exception - */ - public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) { - Map ouputToSend = new HashMap(); - - try { - for(PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class).getPropertyDescriptors()) { - if(!pd.getName().equalsIgnoreCase("doc") & !pd.getName().equalsIgnoreCase("xpath") & !pd.getName().equalsIgnoreCase("xmldocument") & !pd.getName().equalsIgnoreCase("class")) { - Object value = pd.getReadMethod().invoke(resultParser); - if(value == null) continue; - if(value instanceof Long) { - ouputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value)); - } else { - ouputToSend.put(pd.getName(), DataBuilder.buildText(value.toString())); - } - } - } - - // Save the xml and pdf files - File xmlFile = new File(getExportPath(), getXmlFileName()); - ouputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile)); - - File pdfFile = new File(getExportPath(), getPdfFileName()); - ouputToSend.put("pdfFile", DataBuilder.buildBinary(pdfFile)); - - instrumentExecutionService.addOutputParameterValues(ouputToSend); - - } catch(Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Implements parent method initialize from InstrumentRunner Delete results from previous measurement - */ - public void initialize() { - deleteDeviceData(); - } - - /** - * Implements parent method run from InstrumentRunner Launch the external application, retrieve and send the data - */ - public void run() { - externalAppHelper.launch(); - FileInputStream resultInputStream; - - // Get data from external app - try { - resultInputStream = new FileInputStream(new File(getExportPath(), getXmlFileName())); - CardiosoftInstrumentResultParser resultParser = new CardiosoftInstrumentResultParser(resultInputStream); - sendDataToServer(resultParser); - } catch(FileNotFoundException fnfEx) { - log.error("Cardiosoft output data file not found"); - } - - } - - /** - * Implements parent method shutdown from InstrumentRunner Delete results from current measurement - */ - public void shutdown() { - deleteDeviceData(); - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.gehealthcare; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.util.HashMap; +import java.util.Map; + +import org.obiba.onyx.jade.client.JnlpClient; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.InstrumentRunner; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.jade.util.FileUtil; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Specified instrument runner for the ECG + * @author acarey + */ + +public class CardiosoftInstrumentRunner implements InstrumentRunner { + + private static final Logger log = LoggerFactory.getLogger(JnlpClient.class); + + // Injected by spring. + protected InstrumentExecutionService instrumentExecutionService; + + protected ExternalAppLauncherHelper externalAppHelper; + + private String cardioPath; + + private String initPath; + + private String databasePath; + + private String exportPath; + + private String settingsFileName; + + private String xmlFileName; + + private String pdfFileName; + + public InstrumentExecutionService getInstrumentExecutionService() { + return instrumentExecutionService; + } + + public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { + this.instrumentExecutionService = instrumentExecutionService; + } + + public ExternalAppLauncherHelper getExternalAppHelper() { + return externalAppHelper; + } + + public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { + this.externalAppHelper = externalAppHelper; + } + + public String getCardioPath() { + return cardioPath; + } + + public void setCardioPath(String cardioPath) { + this.cardioPath = cardioPath; + } + + public String getInitPath() { + return initPath; + } + + public void setInitPath(String initPath) { + this.initPath = initPath; + } + + public String getDatabasePath() { + return databasePath; + } + + public void setDatabasePath(String databasePath) { + this.databasePath = databasePath; + } + + public String getExportPath() { + return exportPath; + } + + public void setExportPath(String exportPath) { + this.exportPath = exportPath; + } + + public String getSettingsFileName() { + return settingsFileName; + } + + public void setSettingsFileName(String settingsFileName) { + this.settingsFileName = settingsFileName; + } + + public String getXmlFileName() { + return xmlFileName; + } + + public void setXmlFileName(String xmlFileName) { + this.xmlFileName = xmlFileName; + } + + public String getPdfFileName() { + return pdfFileName; + } + + public void setPdfFileName(String pdfFileName) { + this.pdfFileName = pdfFileName; + } + + /** + * Replace the instrument configuration file if needed Delete the result database and files + * @throws Exception + */ + protected void deleteDeviceData() { + + // Overwrite the CardioSoft configuration file + File backupSettingsFile = new File(getInitPath(), getSettingsFileName()); + File currentSettingsFile = new File(getCardioPath(), getSettingsFileName()); + try { + if(backupSettingsFile.exists()) { + FileUtil.copyFile(backupSettingsFile, currentSettingsFile); + } else { + new File(getInitPath()).mkdir(); + FileUtil.copyFile(currentSettingsFile, backupSettingsFile); + } + } catch(Exception ex) { + throw new RuntimeException("Error initializing ECG cardio.ini file", ex); + } + + // Initialize the CardioSoft database + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return (name.endsWith(".BTR")); + } + }; + + try { + File[] backupDatabaseFiles = new File(getInitPath()).listFiles(filter); + if(backupDatabaseFiles.length > 0) { + for(int i = 0; i < backupDatabaseFiles.length; i++) { + FileUtil.copyFile(backupDatabaseFiles[i], new File(getDatabasePath(), backupDatabaseFiles[i].getName())); + } + } else { + File[] databaseFiles = new File(getDatabasePath()).listFiles(filter); + for(int i = 0; i < databaseFiles.length; i++) { + FileUtil.copyFile(databaseFiles[i], new File(getInitPath(), databaseFiles[i].getName())); + } + } + } catch(Exception couldNotInitDbs) { + throw new RuntimeException("Error initializing ECG database files", couldNotInitDbs); + } + + // Delete generated reports + File reportFile = new File(getExportPath(), getXmlFileName()); + reportFile.delete(); + reportFile = new File(getExportPath(), getPdfFileName()); + reportFile.delete(); + } + + /** + * Place the results and xml and pdf files into a map object to send them to the server for persistence + * @param resultParser + * @throws Exception + */ + public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) { + Map ouputToSend = new HashMap(); + + try { + for(PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class).getPropertyDescriptors()) { + if(!pd.getName().equalsIgnoreCase("doc") & !pd.getName().equalsIgnoreCase("xpath") & !pd.getName().equalsIgnoreCase("xmldocument") & !pd.getName().equalsIgnoreCase("class")) { + Object value = pd.getReadMethod().invoke(resultParser); + if(value == null) continue; + if(value instanceof Long) { + ouputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value)); + } else { + ouputToSend.put(pd.getName(), DataBuilder.buildText(value.toString())); + } + } + } + + // Save the xml and pdf files + File xmlFile = new File(getExportPath(), getXmlFileName()); + ouputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile)); + + File pdfFile = new File(getExportPath(), getPdfFileName()); + ouputToSend.put("pdfFile", DataBuilder.buildBinary(pdfFile)); + + instrumentExecutionService.addOutputParameterValues(ouputToSend); + + } catch(Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Implements parent method initialize from InstrumentRunner Delete results from previous measurement + */ + public void initialize() { + deleteDeviceData(); + } + + /** + * Implements parent method run from InstrumentRunner Launch the external application, retrieve and send the data + */ + public void run() { + externalAppHelper.launch(); + FileInputStream resultInputStream; + + // Get data from external app + try { + resultInputStream = new FileInputStream(new File(getExportPath(), getXmlFileName())); + CardiosoftInstrumentResultParser resultParser = new CardiosoftInstrumentResultParser(resultInputStream); + sendDataToServer(resultParser); + } catch(FileNotFoundException fnfEx) { + log.error("Cardiosoft output data file not found"); + } + + } + + /** + * Implements parent method shutdown from InstrumentRunner Delete results from current measurement + */ + public void shutdown() { + deleteDeviceData(); + + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/test/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunnerTest.java b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/test/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunnerTest.java index c16fe59ab..356951c5b 100644 --- a/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/test/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunnerTest.java +++ b/onyx-modules/jade/instrument-parent/interface-ecg-cardiosoft/src/test/java/org/obiba/onyx/jade/instrument/gehealthcare/CardiosoftInstrumentRunnerTest.java @@ -1,172 +1,181 @@ -package org.obiba.onyx.jade.instrument.gehealthcare; - -import static org.easymock.EasyMock.*; - -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.Properties; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.jade.util.FileUtil; -import org.obiba.onyx.util.data.Data; - -public class CardiosoftInstrumentRunnerTest { - - private ExternalAppLauncherHelper externalAppHelper; - - private CardiosoftInstrumentRunner cardiosoftInstrumentRunner; - - private InstrumentExecutionService instrumentExecutionServiceMock; - - @Before - public void setUp() throws URISyntaxException { - - cardiosoftInstrumentRunner = new CardiosoftInstrumentRunner(); - - // Create a test directory to simulate Cardiosoft software installation path. - String cardioSoftSimulatedPath = new File( "target", "test-cardiosoft").getPath(); - (new File(cardioSoftSimulatedPath)).mkdir(); - cardiosoftInstrumentRunner.setCardioPath(cardioSoftSimulatedPath); - - // Cardiosoft database path. - File databasePath = new File( cardioSoftSimulatedPath, "DATABASE"); - databasePath.mkdir(); - cardiosoftInstrumentRunner.setDatabasePath(databasePath.getPath()); - - // Cardiosoft output path. - File exportPath = new File( cardioSoftSimulatedPath, "EXPORT"); - exportPath.mkdir(); - cardiosoftInstrumentRunner.setExportPath(exportPath.getPath()); - - cardiosoftInstrumentRunner.setPdfFileName("Cartagene.pdf"); - cardiosoftInstrumentRunner.setSettingsFileName("CARDIO.INI"); - cardiosoftInstrumentRunner.setXmlFileName("Cartagene.XML"); - - String resourcesParentDir = new File(getClass().getResource("/initecg/CARDIO.INI").toURI().getPath()).getParent(); - cardiosoftInstrumentRunner.setInitPath(new File( resourcesParentDir).getPath()); - - // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), - // so for now, use the class itself with the launch method overridden to - // do nothing. - externalAppHelper = new ExternalAppLauncherHelper() { - public void launch() { - // do nothing - } - }; - - cardiosoftInstrumentRunner.setExternalAppHelper(externalAppHelper); - - // Create a mock instrumentExecutionService for testing. - instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); - cardiosoftInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); - - } - - - @Test - public void testInitialize() throws FileNotFoundException, IOException, URISyntaxException { - - simulateResults(); - - cardiosoftInstrumentRunner.initialize(); - - verifyInitialization(); - - } - - @Test - public void testShutdown() throws FileNotFoundException, IOException, URISyntaxException { - - simulateResults(); - - cardiosoftInstrumentRunner.shutdown(); - - verifyInitialization(); - - } - - @SuppressWarnings("unchecked") - @Test - public void testRun() throws Exception { - - simulateResults(); - - externalAppHelper.launch(); - - FileInputStream resultInputStream = new FileInputStream(new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getXmlFileName())); - CardiosoftInstrumentResultParser resultParser = new CardiosoftInstrumentResultParser(resultInputStream); - - Object value; - String paramName; - - // Load results properties file for testing. - Properties testResults = new Properties(); - testResults.load(getClass().getResourceAsStream("/testResults.properties")); - - // Compare the test results file to the values extracted from the XML result file to make sure they match. - for(PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class).getPropertyDescriptors()) { - - paramName = pd.getName(); - value = pd.getReadMethod().invoke(resultParser); - - if (!paramName.equalsIgnoreCase("doc") && !paramName.equalsIgnoreCase("xpath") && !paramName.equalsIgnoreCase("xmldocument") && !paramName.equalsIgnoreCase("class")) { - Assert.assertTrue(value.toString().equals(testResults.getProperty(paramName))); - } - - } - - instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); - replay(instrumentExecutionServiceMock); - - // Make sure that the results are sent to the server. - cardiosoftInstrumentRunner.sendDataToServer(resultParser); - verify(instrumentExecutionServiceMock); - - } - - private void simulateResults() throws FileNotFoundException, IOException, URISyntaxException { - - // Write some arbitrary data to simulate database access by Cardiosoft. - (new FileOutputStream(new File(cardiosoftInstrumentRunner.getDatabasePath(),"PATIENT.BTR"))).write((byte) 234432141); - (new FileOutputStream(new File(cardiosoftInstrumentRunner.getDatabasePath(),"EXAMINA.BTR"))).write((byte) 234432141); - (new FileOutputStream(new File(cardiosoftInstrumentRunner.getCardioPath(),cardiosoftInstrumentRunner.getSettingsFileName()))).write((byte) 234432141); - - // Copy the results file + PDF file to test directory. - FileUtil.copyFile(new File(getClass().getResource("/Cartagene.pdf").toURI()), new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getPdfFileName())); - FileUtil.copyFile(new File(getClass().getResource("/Cartagene.XML").toURI()), new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getXmlFileName())); - - } - - - private void verifyInitialization() { - - // Verify that the Cardiosoft database content has been cleared successfully. - Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),"PATIENT.BTR").length(), new File(cardiosoftInstrumentRunner.getDatabasePath(),"PATIENT.BTR").length()); - Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),"EXAMINA.BTR").length(), new File(cardiosoftInstrumentRunner.getDatabasePath(),"EXAMINA.BTR").length()); - - // Make sure that Cardiosoft settings have been overwritten (cardio.ini). - Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),cardiosoftInstrumentRunner.getSettingsFileName()).length(), new File(cardiosoftInstrumentRunner.getCardioPath(),"CARDIO.INI").length()); - - // Make sure result files have been deleted. - Assert.assertFalse(new File(cardiosoftInstrumentRunner.getExportPath(),cardiosoftInstrumentRunner.getXmlFileName()).exists()); - Assert.assertFalse(new File(cardiosoftInstrumentRunner.getExportPath(),cardiosoftInstrumentRunner.getPdfFileName()).exists()); - - } - - - - - - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.gehealthcare; + +import static org.easymock.EasyMock.*; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Map; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.jade.util.FileUtil; +import org.obiba.onyx.util.data.Data; + +public class CardiosoftInstrumentRunnerTest { + + private ExternalAppLauncherHelper externalAppHelper; + + private CardiosoftInstrumentRunner cardiosoftInstrumentRunner; + + private InstrumentExecutionService instrumentExecutionServiceMock; + + @Before + public void setUp() throws URISyntaxException { + + cardiosoftInstrumentRunner = new CardiosoftInstrumentRunner(); + + // Create a test directory to simulate Cardiosoft software installation path. + String cardioSoftSimulatedPath = new File( "target", "test-cardiosoft").getPath(); + (new File(cardioSoftSimulatedPath)).mkdir(); + cardiosoftInstrumentRunner.setCardioPath(cardioSoftSimulatedPath); + + // Cardiosoft database path. + File databasePath = new File( cardioSoftSimulatedPath, "DATABASE"); + databasePath.mkdir(); + cardiosoftInstrumentRunner.setDatabasePath(databasePath.getPath()); + + // Cardiosoft output path. + File exportPath = new File( cardioSoftSimulatedPath, "EXPORT"); + exportPath.mkdir(); + cardiosoftInstrumentRunner.setExportPath(exportPath.getPath()); + + cardiosoftInstrumentRunner.setPdfFileName("Cartagene.pdf"); + cardiosoftInstrumentRunner.setSettingsFileName("CARDIO.INI"); + cardiosoftInstrumentRunner.setXmlFileName("Cartagene.XML"); + + String resourcesParentDir = new File(getClass().getResource("/initecg/CARDIO.INI").toURI().getPath()).getParent(); + cardiosoftInstrumentRunner.setInitPath(new File( resourcesParentDir).getPath()); + + // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), + // so for now, use the class itself with the launch method overridden to + // do nothing. + externalAppHelper = new ExternalAppLauncherHelper() { + public void launch() { + // do nothing + } + }; + + cardiosoftInstrumentRunner.setExternalAppHelper(externalAppHelper); + + // Create a mock instrumentExecutionService for testing. + instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); + cardiosoftInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); + + } + + + @Test + public void testInitialize() throws FileNotFoundException, IOException, URISyntaxException { + + simulateResults(); + + cardiosoftInstrumentRunner.initialize(); + + verifyInitialization(); + + } + + @Test + public void testShutdown() throws FileNotFoundException, IOException, URISyntaxException { + + simulateResults(); + + cardiosoftInstrumentRunner.shutdown(); + + verifyInitialization(); + + } + + @SuppressWarnings("unchecked") + @Test + public void testRun() throws Exception { + + simulateResults(); + + externalAppHelper.launch(); + + FileInputStream resultInputStream = new FileInputStream(new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getXmlFileName())); + CardiosoftInstrumentResultParser resultParser = new CardiosoftInstrumentResultParser(resultInputStream); + + Object value; + String paramName; + + // Load results properties file for testing. + Properties testResults = new Properties(); + testResults.load(getClass().getResourceAsStream("/testResults.properties")); + + // Compare the test results file to the values extracted from the XML result file to make sure they match. + for(PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class).getPropertyDescriptors()) { + + paramName = pd.getName(); + value = pd.getReadMethod().invoke(resultParser); + + if (!paramName.equalsIgnoreCase("doc") && !paramName.equalsIgnoreCase("xpath") && !paramName.equalsIgnoreCase("xmldocument") && !paramName.equalsIgnoreCase("class")) { + Assert.assertTrue(value.toString().equals(testResults.getProperty(paramName))); + } + + } + + instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); + replay(instrumentExecutionServiceMock); + + // Make sure that the results are sent to the server. + cardiosoftInstrumentRunner.sendDataToServer(resultParser); + verify(instrumentExecutionServiceMock); + + } + + private void simulateResults() throws FileNotFoundException, IOException, URISyntaxException { + + // Write some arbitrary data to simulate database access by Cardiosoft. + (new FileOutputStream(new File(cardiosoftInstrumentRunner.getDatabasePath(),"PATIENT.BTR"))).write((byte) 234432141); + (new FileOutputStream(new File(cardiosoftInstrumentRunner.getDatabasePath(),"EXAMINA.BTR"))).write((byte) 234432141); + (new FileOutputStream(new File(cardiosoftInstrumentRunner.getCardioPath(),cardiosoftInstrumentRunner.getSettingsFileName()))).write((byte) 234432141); + + // Copy the results file + PDF file to test directory. + FileUtil.copyFile(new File(getClass().getResource("/Cartagene.pdf").toURI()), new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getPdfFileName())); + FileUtil.copyFile(new File(getClass().getResource("/Cartagene.XML").toURI()), new File(cardiosoftInstrumentRunner.getExportPath(), cardiosoftInstrumentRunner.getXmlFileName())); + + } + + + private void verifyInitialization() { + + // Verify that the Cardiosoft database content has been cleared successfully. + Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),"PATIENT.BTR").length(), new File(cardiosoftInstrumentRunner.getDatabasePath(),"PATIENT.BTR").length()); + Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),"EXAMINA.BTR").length(), new File(cardiosoftInstrumentRunner.getDatabasePath(),"EXAMINA.BTR").length()); + + // Make sure that Cardiosoft settings have been overwritten (cardio.ini). + Assert.assertEquals(new File(cardiosoftInstrumentRunner.getInitPath(),cardiosoftInstrumentRunner.getSettingsFileName()).length(), new File(cardiosoftInstrumentRunner.getCardioPath(),"CARDIO.INI").length()); + + // Make sure result files have been deleted. + Assert.assertFalse(new File(cardiosoftInstrumentRunner.getExportPath(),cardiosoftInstrumentRunner.getXmlFileName()).exists()); + Assert.assertFalse(new File(cardiosoftInstrumentRunner.getExportPath(),cardiosoftInstrumentRunner.getPdfFileName()).exists()); + + } + + + + + + +} diff --git a/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/main/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunner.java b/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/main/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunner.java index 8f873cde7..3b840eb9a 100644 --- a/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/main/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunner.java +++ b/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/main/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunner.java @@ -1,295 +1,304 @@ -package org.obiba.onyx.jade.instrument.mir; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.swing.JOptionPane; - -import org.obiba.onyx.jade.client.JnlpClient; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.InstrumentRunner; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.jade.util.FileUtil; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Specified instrument runner for the Spirometer - * @author acarey - */ - -public class MiniSpirInstrumentRunner implements InstrumentRunner { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(JnlpClient.class); - - // Injected by spring. - protected InstrumentExecutionService instrumentExecutionService; - - protected ExternalAppLauncherHelper externalAppHelper; - - private Set expectedOutputParameterNames; - - private String mirPath; - - private String initdbPath; - - private String externalDbName; - - private String externalInputName; - - private String externalOutputName; - - private String externalImageName; - - public InstrumentExecutionService getInstrumentExecutionService() { - return instrumentExecutionService; - } - - public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { - this.instrumentExecutionService = instrumentExecutionService; - } - - public ExternalAppLauncherHelper getExternalAppHelper() { - return externalAppHelper; - } - - public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { - this.externalAppHelper = externalAppHelper; - } - - public String getMirPath() { - return mirPath; - } - - public void setMirPath(String mirPath) { - this.mirPath = mirPath; - } - - public String getInitdbPath() { - return initdbPath; - } - - public void setInitdbPath(String initdbPath) { - this.initdbPath = initdbPath; - } - - public String getExternalDbName() { - return externalDbName; - } - - public void setExternalDbName(String externalDbName) { - this.externalDbName = externalDbName; - } - - public String getExternalInputName() { - return externalInputName; - } - - public void setExternalInputName(String externalInputName) { - this.externalInputName = externalInputName; - } - - public String getExternalOutputName() { - return externalOutputName; - } - - public void setExternalOutputName(String externalOutputName) { - this.externalOutputName = externalOutputName; - } - - public String getExternalImageName() { - return externalImageName; - } - - public void setExternalImageName(String externalImageName) { - this.externalImageName = externalImageName; - } - - /** - * Retrieve participant data from the database and write them in the spirometer input file - * @throws Exception - */ - public void initParticipantData() { - File externalAppInputFile = new File(getMirPath() + getExternalInputName()); - try { - Map inputData = instrumentExecutionService.getInputParametersValue("ID", "LastName", "FirstName", "Gender", "Height", "Weight", "EthnicGroup", "BirthDate"); - BufferedWriter inputFileWriter = new BufferedWriter(new FileWriter(externalAppInputFile)); - inputFileWriter.write("[Identification]\n"); - for(Map.Entry entry : inputData.entrySet()) { - if(entry.getKey().equals("BirthDate")) { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - inputFileWriter.write(entry.getKey() + "=" + formatter.format(entry.getValue().getValue()) + "\n"); - } else - inputFileWriter.write(entry.getKey() + "=" + ((entry.getKey().equals("Gender")) ? getGenderConverter(entry.getValue()) : entry.getValue().getValueAsString()) + "\n"); - } - inputFileWriter.close(); - } catch(Exception ex) { - throw new RuntimeException("Error writing spirometer input file: ", ex); - } - } - - /** - * Replace the result database with a backup version - * @throws Exception - */ - protected void deleteDeviceData() { - File backupDbFile = new File(getInitdbPath() + getExternalDbName()); - File currentDbFile = new File(getMirPath() + getExternalDbName()); - - try { - if(backupDbFile.exists()) { - FileUtil.copyFile(backupDbFile, currentDbFile); - } else { - new File(getInitdbPath()).mkdir(); - FileUtil.copyFile(currentDbFile, backupDbFile); - } - } catch(Exception ex) { - throw new RuntimeException("Error in MiniSpirInstrumentRunner deleteDeviceData: ", ex); - } - } - - /** - * Retrieve the data from the result file - * @return a map with the result data - * @throws Exception - */ - LinkedHashMap retrieveDeviceData() { - - InputStream resultFileStrm = null; - InputStreamReader resultReader = null; - BufferedReader fileReader = null; - - LinkedHashMap outputData = new LinkedHashMap(); - try { - resultFileStrm = new FileInputStream(getMirPath() + getExternalOutputName()); - resultReader = new InputStreamReader(resultFileStrm); - fileReader = new BufferedReader(resultReader); - - StringBuffer results = new StringBuffer(); - String line; - Boolean lastParam = false; - while((line = fileReader.readLine()) != null) { - results.append(line + "\n"); - if(line.indexOf("PIF") == 0) lastParam = true; - } - - if(lastParam == false) JOptionPane.showMessageDialog(null, "Data is incomplete", "Could not complete process", JOptionPane.ERROR_MESSAGE); - - Pattern pattern = Pattern.compile("(.*)\t(.*)\t(.*)\t(.*)\t(.*)"); - Matcher matcher = pattern.matcher(results.toString().replace(",", ".").replace("/", "_")); - String description = null; - Double[] data = null; - - while(matcher.find()) { - description = matcher.group(1); - data = new Double[2]; - data[0] = Double.valueOf(matcher.group(3)); - data[1] = Double.valueOf(matcher.group(4)); - outputData.put(description, data); - } - - resultFileStrm.close(); - fileReader.close(); - resultReader.close(); - - } catch(FileNotFoundException fnfEx) { - log.warn("No device output found"); - - } catch(IOException ioEx) { - throw new RuntimeException("Error: retrieve spirometry data IOException", ioEx); - } catch(Exception ex) { - throw new RuntimeException("Error: retrieve spirometry data", ex); - } - - return outputData; - } - - /** - * Send the results to the server for persistence - * @param results - * @throws Exception - */ - public void sendDataToServer(LinkedHashMap results) { - Map ouputToSend = new HashMap(); - - for(Map.Entry entry : results.entrySet()) { - if (!expectedOutputParameterNames.contains(entry.getKey())) { - log.info("Output parameter {} is not expected but has an entry in result file.", entry.getKey()); - continue; - } - if(entry.getKey().indexOf("ELA") == 0) { - ouputToSend.put(entry.getKey(), DataBuilder.buildInteger(Math.round(entry.getValue()[0]))); - ouputToSend.put(entry.getKey() + "_pred", DataBuilder.buildInteger(Math.round(entry.getValue()[1]))); - } else { - ouputToSend.put(entry.getKey(), DataBuilder.buildDecimal(entry.getValue()[0])); - ouputToSend.put(entry.getKey() + "_pred", DataBuilder.buildDecimal(entry.getValue()[1])); - } - } - - // Save the FVC image - try{ - File FVCFile = new File(getMirPath() + getExternalImageName()); - ouputToSend.put("FVCImage", DataBuilder.buildBinary(FVCFile)); - } - catch (Exception e){ - log.warn("No device output image found"); - } - instrumentExecutionService.addOutputParameterValues(ouputToSend); - } - - private int getGenderConverter(Data data) { - if(data.getValueAsString().equals("MALE")) return 0; - else - return 1; - } - - /** - * Implements parent method initialize from InstrumentRunner Delete results from previous measurement and initiate the - * input file to be read by the external application - */ - public void initialize() { - deleteDeviceData(); - initParticipantData(); - } - - /** - * Implements parent method run from InstrumentRunner Launch the external application, retrieve and send the data - */ - public void run() { - externalAppHelper.launch(); - LinkedHashMap results = retrieveDeviceData(); - sendDataToServer(results); - } - - /** - * Implements parent method shutdown from InstrumentRunner Delete results from current measurement - */ - public void shutdown() { - deleteDeviceData(); - } - - public Set getExpectedOutputParameterNames() { - return expectedOutputParameterNames; - } - - public void setExpectedOutputParameterNames(Set expectedOutputParameterNames) { - this.expectedOutputParameterNames = expectedOutputParameterNames; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.mir; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JOptionPane; + +import org.obiba.onyx.jade.client.JnlpClient; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.InstrumentRunner; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.jade.util.FileUtil; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Specified instrument runner for the Spirometer + * @author acarey + */ + +public class MiniSpirInstrumentRunner implements InstrumentRunner { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(JnlpClient.class); + + // Injected by spring. + protected InstrumentExecutionService instrumentExecutionService; + + protected ExternalAppLauncherHelper externalAppHelper; + + private Set expectedOutputParameterNames; + + private String mirPath; + + private String initdbPath; + + private String externalDbName; + + private String externalInputName; + + private String externalOutputName; + + private String externalImageName; + + public InstrumentExecutionService getInstrumentExecutionService() { + return instrumentExecutionService; + } + + public void setInstrumentExecutionService(InstrumentExecutionService instrumentExecutionService) { + this.instrumentExecutionService = instrumentExecutionService; + } + + public ExternalAppLauncherHelper getExternalAppHelper() { + return externalAppHelper; + } + + public void setExternalAppHelper(ExternalAppLauncherHelper externalAppHelper) { + this.externalAppHelper = externalAppHelper; + } + + public String getMirPath() { + return mirPath; + } + + public void setMirPath(String mirPath) { + this.mirPath = mirPath; + } + + public String getInitdbPath() { + return initdbPath; + } + + public void setInitdbPath(String initdbPath) { + this.initdbPath = initdbPath; + } + + public String getExternalDbName() { + return externalDbName; + } + + public void setExternalDbName(String externalDbName) { + this.externalDbName = externalDbName; + } + + public String getExternalInputName() { + return externalInputName; + } + + public void setExternalInputName(String externalInputName) { + this.externalInputName = externalInputName; + } + + public String getExternalOutputName() { + return externalOutputName; + } + + public void setExternalOutputName(String externalOutputName) { + this.externalOutputName = externalOutputName; + } + + public String getExternalImageName() { + return externalImageName; + } + + public void setExternalImageName(String externalImageName) { + this.externalImageName = externalImageName; + } + + /** + * Retrieve participant data from the database and write them in the spirometer input file + * @throws Exception + */ + public void initParticipantData() { + File externalAppInputFile = new File(getMirPath() + getExternalInputName()); + try { + Map inputData = instrumentExecutionService.getInputParametersValue("ID", "LastName", "FirstName", "Gender", "Height", "Weight", "EthnicGroup", "BirthDate"); + BufferedWriter inputFileWriter = new BufferedWriter(new FileWriter(externalAppInputFile)); + inputFileWriter.write("[Identification]\n"); + for(Map.Entry entry : inputData.entrySet()) { + if(entry.getKey().equals("BirthDate")) { + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + inputFileWriter.write(entry.getKey() + "=" + formatter.format(entry.getValue().getValue()) + "\n"); + } else + inputFileWriter.write(entry.getKey() + "=" + ((entry.getKey().equals("Gender")) ? getGenderConverter(entry.getValue()) : entry.getValue().getValueAsString()) + "\n"); + } + inputFileWriter.close(); + } catch(Exception ex) { + throw new RuntimeException("Error writing spirometer input file: ", ex); + } + } + + /** + * Replace the result database with a backup version + * @throws Exception + */ + protected void deleteDeviceData() { + File backupDbFile = new File(getInitdbPath() + getExternalDbName()); + File currentDbFile = new File(getMirPath() + getExternalDbName()); + + try { + if(backupDbFile.exists()) { + FileUtil.copyFile(backupDbFile, currentDbFile); + } else { + new File(getInitdbPath()).mkdir(); + FileUtil.copyFile(currentDbFile, backupDbFile); + } + } catch(Exception ex) { + throw new RuntimeException("Error in MiniSpirInstrumentRunner deleteDeviceData: ", ex); + } + } + + /** + * Retrieve the data from the result file + * @return a map with the result data + * @throws Exception + */ + LinkedHashMap retrieveDeviceData() { + + InputStream resultFileStrm = null; + InputStreamReader resultReader = null; + BufferedReader fileReader = null; + + LinkedHashMap outputData = new LinkedHashMap(); + try { + resultFileStrm = new FileInputStream(getMirPath() + getExternalOutputName()); + resultReader = new InputStreamReader(resultFileStrm); + fileReader = new BufferedReader(resultReader); + + StringBuffer results = new StringBuffer(); + String line; + Boolean lastParam = false; + while((line = fileReader.readLine()) != null) { + results.append(line + "\n"); + if(line.indexOf("PIF") == 0) lastParam = true; + } + + if(lastParam == false) JOptionPane.showMessageDialog(null, "Data is incomplete", "Could not complete process", JOptionPane.ERROR_MESSAGE); + + Pattern pattern = Pattern.compile("(.*)\t(.*)\t(.*)\t(.*)\t(.*)"); + Matcher matcher = pattern.matcher(results.toString().replace(",", ".").replace("/", "_")); + String description = null; + Double[] data = null; + + while(matcher.find()) { + description = matcher.group(1); + data = new Double[2]; + data[0] = Double.valueOf(matcher.group(3)); + data[1] = Double.valueOf(matcher.group(4)); + outputData.put(description, data); + } + + resultFileStrm.close(); + fileReader.close(); + resultReader.close(); + + } catch(FileNotFoundException fnfEx) { + log.warn("No device output found"); + + } catch(IOException ioEx) { + throw new RuntimeException("Error: retrieve spirometry data IOException", ioEx); + } catch(Exception ex) { + throw new RuntimeException("Error: retrieve spirometry data", ex); + } + + return outputData; + } + + /** + * Send the results to the server for persistence + * @param results + * @throws Exception + */ + public void sendDataToServer(LinkedHashMap results) { + Map ouputToSend = new HashMap(); + + for(Map.Entry entry : results.entrySet()) { + if (!expectedOutputParameterNames.contains(entry.getKey())) { + log.info("Output parameter {} is not expected but has an entry in result file.", entry.getKey()); + continue; + } + if(entry.getKey().indexOf("ELA") == 0) { + ouputToSend.put(entry.getKey(), DataBuilder.buildInteger(Math.round(entry.getValue()[0]))); + ouputToSend.put(entry.getKey() + "_pred", DataBuilder.buildInteger(Math.round(entry.getValue()[1]))); + } else { + ouputToSend.put(entry.getKey(), DataBuilder.buildDecimal(entry.getValue()[0])); + ouputToSend.put(entry.getKey() + "_pred", DataBuilder.buildDecimal(entry.getValue()[1])); + } + } + + // Save the FVC image + try{ + File FVCFile = new File(getMirPath() + getExternalImageName()); + ouputToSend.put("FVCImage", DataBuilder.buildBinary(FVCFile)); + } + catch (Exception e){ + log.warn("No device output image found"); + } + instrumentExecutionService.addOutputParameterValues(ouputToSend); + } + + private int getGenderConverter(Data data) { + if(data.getValueAsString().equals("MALE")) return 0; + else + return 1; + } + + /** + * Implements parent method initialize from InstrumentRunner Delete results from previous measurement and initiate the + * input file to be read by the external application + */ + public void initialize() { + deleteDeviceData(); + initParticipantData(); + } + + /** + * Implements parent method run from InstrumentRunner Launch the external application, retrieve and send the data + */ + public void run() { + externalAppHelper.launch(); + LinkedHashMap results = retrieveDeviceData(); + sendDataToServer(results); + } + + /** + * Implements parent method shutdown from InstrumentRunner Delete results from current measurement + */ + public void shutdown() { + deleteDeviceData(); + } + + public Set getExpectedOutputParameterNames() { + return expectedOutputParameterNames; + } + + public void setExpectedOutputParameterNames(Set expectedOutputParameterNames) { + this.expectedOutputParameterNames = expectedOutputParameterNames; + } +} diff --git a/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/test/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunnerTest.java b/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/test/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunnerTest.java index 26fde38e1..53f9048a2 100644 --- a/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/test/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunnerTest.java +++ b/onyx-modules/jade/instrument-parent/interface-spirometry-minispir/src/test/java/org/obiba/onyx/jade/instrument/mir/MiniSpirInstrumentRunnerTest.java @@ -1,247 +1,256 @@ -package org.obiba.onyx.jade.instrument.mir; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; -import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; -import org.obiba.onyx.jade.util.FileUtil; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; - -public class MiniSpirInstrumentRunnerTest { - - private ExternalAppLauncherHelper externalAppHelper; - - private MiniSpirInstrumentRunner minispirInstrumentRunner; - - private InstrumentExecutionService instrumentExecutionServiceMock; - - private Set expectedOutputParameterNamesSet = new HashSet(); - - File initDbFile; - - File miniSpirDbFile; - - @Before - public void setUp() throws URISyntaxException { - - minispirInstrumentRunner = new MiniSpirInstrumentRunner(); - minispirInstrumentRunner.setExternalDbName("WinSpiroPRO.wdb"); - minispirInstrumentRunner.setExternalImageName("FVC.jpg"); - minispirInstrumentRunner.setExternalInputName("patient.srv"); - minispirInstrumentRunner.setExternalOutputName("Results.wsp"); - - String resourcesParentDir = new File(getClass().getResource("/WinSpiroPRO.wdb").toURI().getPath()).getParent(); - minispirInstrumentRunner.setInitdbPath(new File(resourcesParentDir, File.separator).getPath()); - - // Create a test directory to simulate WinSpiro software installation path. - String winSpiroSimulatedPath = "target" + File.separator + "test-spirometry" + File.separator; - (new File(winSpiroSimulatedPath)).mkdir(); - minispirInstrumentRunner.setMirPath(winSpiroSimulatedPath); - - // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), - // so for now, use the class itself with the launch method overridden to - // do nothing. - externalAppHelper = new ExternalAppLauncherHelper() { - public void launch() { - // do nothing - } - }; - minispirInstrumentRunner.setExternalAppHelper(externalAppHelper); - - // Create a mock instrumentExecutionService for testing. - instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); - minispirInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); - - // Create the outputParameterNamesExpected set - setExpectedOutputParameterNames(); - minispirInstrumentRunner.setExpectedOutputParameterNames(expectedOutputParameterNamesSet); - - initDbFile = new File(minispirInstrumentRunner.getInitdbPath(), minispirInstrumentRunner.getExternalDbName()); - miniSpirDbFile = new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalDbName()); - - } - - @Test - public void testInitialize() throws FileNotFoundException, IOException { - - // Write some arbitrary data to simulate database access by external software. - (new FileOutputStream(miniSpirDbFile)).write((byte) 234432141); - - // Insure that the previous participant data is deleted. - minispirInstrumentRunner.deleteDeviceData(); - - // Verify that the WinSpiro database content has been cleared successfully. - Assert.assertEquals(initDbFile.length(), miniSpirDbFile.length()); - - // Set arbitrary inputs for testing. - Map inputData = new HashMap(); - inputData.put("ID", DataBuilder.buildText("123456789")); - inputData.put("LastName", DataBuilder.buildText("Tremblay")); - inputData.put("FirstName", DataBuilder.buildText("Chantal")); - inputData.put("Gender", DataBuilder.buildText("Chantal")); - inputData.put("Height", DataBuilder.buildInteger(178)); - inputData.put("Weight", DataBuilder.buildDecimal(76.4)); - inputData.put("EthnicGroup", DataBuilder.buildInteger(1)); - inputData.put("BirthDate", DataBuilder.buildDate(getBirthDate())); - - expect(instrumentExecutionServiceMock.getInputParametersValue("ID", "LastName", "FirstName", "Gender", "Height", "Weight", "EthnicGroup", "BirthDate")).andReturn(inputData); - replay(instrumentExecutionServiceMock); - - // Generate the input file for WinSpiro. - minispirInstrumentRunner.initParticipantData(); - verify(instrumentExecutionServiceMock); - - // Verify that input file has been created. - File inputFile = new File(minispirInstrumentRunner.getMirPath() + minispirInstrumentRunner.getExternalInputName()); - Assert.assertTrue(inputFile.exists()); - - } - - private java.util.Date getBirthDate() { - Calendar c = Calendar.getInstance(); - c.set(Calendar.YEAR, 1964); - c.set(Calendar.MONTH, 2); - c.set(Calendar.DAY_OF_MONTH, 12); - - return c.getTime(); - } - - @SuppressWarnings("unchecked") - @Test - public void testRun() throws FileNotFoundException, IOException, URISyntaxException { - externalAppHelper.launch(); - - // Copy the result file + image file to test directory. - FileUtil.copyFile(new File(getClass().getResource("/Results.wsp").toURI()), new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalOutputName())); - FileUtil.copyFile(new File(getClass().getResource("/FVC.jpg").toURI()), new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalImageName())); - - // Read the results file. - LinkedHashMap results = minispirInstrumentRunner.retrieveDeviceData(); - - // Compare the values read with the ones from the result file. - Assert.assertEquals(10.94, results.get("FVC")[0].doubleValue(), 0); - Assert.assertEquals(4.36, results.get("FVC")[1].doubleValue(), 0); - Assert.assertEquals(4.22, results.get("FEV1")[0].doubleValue(), 0); - Assert.assertEquals(3.58, results.get("FEV1")[1].doubleValue(), 0); - Assert.assertEquals(38.6, results.get("FEV1_FVC")[0].doubleValue(), 0); - Assert.assertEquals(78.81, results.get("FEV1_FVC")[1].doubleValue(), 0); - Assert.assertEquals(4.65, results.get("PEF")[0].doubleValue(), 0); - Assert.assertEquals(7.36, results.get("PEF")[1].doubleValue(), 0); - Assert.assertEquals(2.63, results.get("FEF2575")[0].doubleValue(), 0); - Assert.assertEquals(3.94, results.get("FEF2575")[1].doubleValue(), 0); - Assert.assertEquals(8.59, results.get("FEV3")[0].doubleValue(), 0); - Assert.assertEquals(3.94, results.get("FEV3")[1].doubleValue(), 0); - Assert.assertEquals(78.5, results.get("FEV3_FVC")[0].doubleValue(), 0); - Assert.assertEquals(90.48, results.get("FEV3_FVC")[1].doubleValue(), 0); - Assert.assertEquals(39, results.get("ELA")[0].doubleValue(), 0); - Assert.assertEquals(39, results.get("ELA")[1].doubleValue(), 0); - Assert.assertEquals(5.62, results.get("FET")[0].doubleValue(), 0); - Assert.assertEquals(6, results.get("FET")[1].doubleValue(), 0); - Assert.assertEquals(4.15, results.get("FEF25")[0].doubleValue(), 0); - Assert.assertEquals(6.85, results.get("FEF25")[1].doubleValue(), 0); - Assert.assertEquals(2.75, results.get("FEF50")[0].doubleValue(), 0); - Assert.assertEquals(4.57, results.get("FEF50")[1].doubleValue(), 0); - Assert.assertEquals(1.49, results.get("FEF75")[0].doubleValue(), 0); - Assert.assertEquals(2.05, results.get("FEF75")[1].doubleValue(), 0); - Assert.assertEquals(180, results.get("EVol")[0].doubleValue(), 0); - Assert.assertEquals(0, results.get("EVol")[1].doubleValue(), 0); - Assert.assertEquals(0, results.get("FIVC")[0].doubleValue(), 0); - Assert.assertEquals(4.36, results.get("FIVC")[1].doubleValue(), 0); - Assert.assertEquals(0, results.get("FIV1")[0].doubleValue(), 0); - Assert.assertEquals(3.58, results.get("FIV1")[1].doubleValue(), 0); - Assert.assertEquals(0, results.get("FIV1_FIVC")[0].doubleValue(), 0); - Assert.assertEquals(78.81, results.get("FIV1_FIVC")[1].doubleValue(), 0); - Assert.assertEquals(0, results.get("PIF")[0].doubleValue(), 0); - Assert.assertEquals(7.36, results.get("PIF")[1].doubleValue(), 0); - - instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); - replay(instrumentExecutionServiceMock); - - // Make sure that the results are sent to the server. - minispirInstrumentRunner.sendDataToServer(results); - verify(instrumentExecutionServiceMock); - - } - - @Test - public void testShutdown() throws FileNotFoundException, IOException { - - // Write some arbitrary data to simulate database access by external software. - (new FileOutputStream(miniSpirDbFile)).write((byte) 234432141); - - minispirInstrumentRunner.shutdown(); - - // Verify that the WinSpiro database content has been cleared successfully. - Assert.assertEquals(initDbFile.length(), miniSpirDbFile.length()); - - } - - private void setExpectedOutputParameterNames() { - String elements[] = { "last_name", - "first_name", - "birth_date", - "gender", - "fvc", - "fev1", - "fev1_fvc", - "fev6", - "fev1_fev6", - "pef", - "fef2575", - "fev3", - "fev3_fvc", - "ela", - "fet", - "fef25", - "fef50", - "fef75", - "evol", - "fivc", - "fiv1", - "fiv1_fivc", - "pif", - "fvc_pred", - "fev1_pred", - "fev1_fvc_pred", - "fev6_pred", - "fev1_fev6_pred", - "pef_pred", - "fef2575_pred", - "fev3_pred", - "fev3_fvc_pred", - "ela_pred", - "fet_pred", - "fef25_pred", - "fef50_pred", - "fef75_pred", - "evol_pred", - "fivc_pred", - "fiv1_pred", - "fiv1_fivc_pred", - "pif_pred", - "fvc_image"}; - - expectedOutputParameterNamesSet.addAll(new HashSet(Arrays.asList(elements))); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.mir; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Calendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.instrument.ExternalAppLauncherHelper; +import org.obiba.onyx.jade.instrument.service.InstrumentExecutionService; +import org.obiba.onyx.jade.util.FileUtil; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; + +public class MiniSpirInstrumentRunnerTest { + + private ExternalAppLauncherHelper externalAppHelper; + + private MiniSpirInstrumentRunner minispirInstrumentRunner; + + private InstrumentExecutionService instrumentExecutionServiceMock; + + private Set expectedOutputParameterNamesSet = new HashSet(); + + File initDbFile; + + File miniSpirDbFile; + + @Before + public void setUp() throws URISyntaxException { + + minispirInstrumentRunner = new MiniSpirInstrumentRunner(); + minispirInstrumentRunner.setExternalDbName("WinSpiroPRO.wdb"); + minispirInstrumentRunner.setExternalImageName("FVC.jpg"); + minispirInstrumentRunner.setExternalInputName("patient.srv"); + minispirInstrumentRunner.setExternalOutputName("Results.wsp"); + + String resourcesParentDir = new File(getClass().getResource("/WinSpiroPRO.wdb").toURI().getPath()).getParent(); + minispirInstrumentRunner.setInitdbPath(new File(resourcesParentDir, File.separator).getPath()); + + // Create a test directory to simulate WinSpiro software installation path. + String winSpiroSimulatedPath = "target" + File.separator + "test-spirometry" + File.separator; + (new File(winSpiroSimulatedPath)).mkdir(); + minispirInstrumentRunner.setMirPath(winSpiroSimulatedPath); + + // Cannot mock ExternalAppLauncherHelper (without EasyMock extension!), + // so for now, use the class itself with the launch method overridden to + // do nothing. + externalAppHelper = new ExternalAppLauncherHelper() { + public void launch() { + // do nothing + } + }; + minispirInstrumentRunner.setExternalAppHelper(externalAppHelper); + + // Create a mock instrumentExecutionService for testing. + instrumentExecutionServiceMock = createMock(InstrumentExecutionService.class); + minispirInstrumentRunner.setInstrumentExecutionService(instrumentExecutionServiceMock); + + // Create the outputParameterNamesExpected set + setExpectedOutputParameterNames(); + minispirInstrumentRunner.setExpectedOutputParameterNames(expectedOutputParameterNamesSet); + + initDbFile = new File(minispirInstrumentRunner.getInitdbPath(), minispirInstrumentRunner.getExternalDbName()); + miniSpirDbFile = new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalDbName()); + + } + + @Test + public void testInitialize() throws FileNotFoundException, IOException { + + // Write some arbitrary data to simulate database access by external software. + (new FileOutputStream(miniSpirDbFile)).write((byte) 234432141); + + // Insure that the previous participant data is deleted. + minispirInstrumentRunner.deleteDeviceData(); + + // Verify that the WinSpiro database content has been cleared successfully. + Assert.assertEquals(initDbFile.length(), miniSpirDbFile.length()); + + // Set arbitrary inputs for testing. + Map inputData = new HashMap(); + inputData.put("ID", DataBuilder.buildText("123456789")); + inputData.put("LastName", DataBuilder.buildText("Tremblay")); + inputData.put("FirstName", DataBuilder.buildText("Chantal")); + inputData.put("Gender", DataBuilder.buildText("Chantal")); + inputData.put("Height", DataBuilder.buildInteger(178)); + inputData.put("Weight", DataBuilder.buildDecimal(76.4)); + inputData.put("EthnicGroup", DataBuilder.buildInteger(1)); + inputData.put("BirthDate", DataBuilder.buildDate(getBirthDate())); + + expect(instrumentExecutionServiceMock.getInputParametersValue("ID", "LastName", "FirstName", "Gender", "Height", "Weight", "EthnicGroup", "BirthDate")).andReturn(inputData); + replay(instrumentExecutionServiceMock); + + // Generate the input file for WinSpiro. + minispirInstrumentRunner.initParticipantData(); + verify(instrumentExecutionServiceMock); + + // Verify that input file has been created. + File inputFile = new File(minispirInstrumentRunner.getMirPath() + minispirInstrumentRunner.getExternalInputName()); + Assert.assertTrue(inputFile.exists()); + + } + + private java.util.Date getBirthDate() { + Calendar c = Calendar.getInstance(); + c.set(Calendar.YEAR, 1964); + c.set(Calendar.MONTH, 2); + c.set(Calendar.DAY_OF_MONTH, 12); + + return c.getTime(); + } + + @SuppressWarnings("unchecked") + @Test + public void testRun() throws FileNotFoundException, IOException, URISyntaxException { + externalAppHelper.launch(); + + // Copy the result file + image file to test directory. + FileUtil.copyFile(new File(getClass().getResource("/Results.wsp").toURI()), new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalOutputName())); + FileUtil.copyFile(new File(getClass().getResource("/FVC.jpg").toURI()), new File(minispirInstrumentRunner.getMirPath(), minispirInstrumentRunner.getExternalImageName())); + + // Read the results file. + LinkedHashMap results = minispirInstrumentRunner.retrieveDeviceData(); + + // Compare the values read with the ones from the result file. + Assert.assertEquals(10.94, results.get("FVC")[0].doubleValue(), 0); + Assert.assertEquals(4.36, results.get("FVC")[1].doubleValue(), 0); + Assert.assertEquals(4.22, results.get("FEV1")[0].doubleValue(), 0); + Assert.assertEquals(3.58, results.get("FEV1")[1].doubleValue(), 0); + Assert.assertEquals(38.6, results.get("FEV1_FVC")[0].doubleValue(), 0); + Assert.assertEquals(78.81, results.get("FEV1_FVC")[1].doubleValue(), 0); + Assert.assertEquals(4.65, results.get("PEF")[0].doubleValue(), 0); + Assert.assertEquals(7.36, results.get("PEF")[1].doubleValue(), 0); + Assert.assertEquals(2.63, results.get("FEF2575")[0].doubleValue(), 0); + Assert.assertEquals(3.94, results.get("FEF2575")[1].doubleValue(), 0); + Assert.assertEquals(8.59, results.get("FEV3")[0].doubleValue(), 0); + Assert.assertEquals(3.94, results.get("FEV3")[1].doubleValue(), 0); + Assert.assertEquals(78.5, results.get("FEV3_FVC")[0].doubleValue(), 0); + Assert.assertEquals(90.48, results.get("FEV3_FVC")[1].doubleValue(), 0); + Assert.assertEquals(39, results.get("ELA")[0].doubleValue(), 0); + Assert.assertEquals(39, results.get("ELA")[1].doubleValue(), 0); + Assert.assertEquals(5.62, results.get("FET")[0].doubleValue(), 0); + Assert.assertEquals(6, results.get("FET")[1].doubleValue(), 0); + Assert.assertEquals(4.15, results.get("FEF25")[0].doubleValue(), 0); + Assert.assertEquals(6.85, results.get("FEF25")[1].doubleValue(), 0); + Assert.assertEquals(2.75, results.get("FEF50")[0].doubleValue(), 0); + Assert.assertEquals(4.57, results.get("FEF50")[1].doubleValue(), 0); + Assert.assertEquals(1.49, results.get("FEF75")[0].doubleValue(), 0); + Assert.assertEquals(2.05, results.get("FEF75")[1].doubleValue(), 0); + Assert.assertEquals(180, results.get("EVol")[0].doubleValue(), 0); + Assert.assertEquals(0, results.get("EVol")[1].doubleValue(), 0); + Assert.assertEquals(0, results.get("FIVC")[0].doubleValue(), 0); + Assert.assertEquals(4.36, results.get("FIVC")[1].doubleValue(), 0); + Assert.assertEquals(0, results.get("FIV1")[0].doubleValue(), 0); + Assert.assertEquals(3.58, results.get("FIV1")[1].doubleValue(), 0); + Assert.assertEquals(0, results.get("FIV1_FIVC")[0].doubleValue(), 0); + Assert.assertEquals(78.81, results.get("FIV1_FIVC")[1].doubleValue(), 0); + Assert.assertEquals(0, results.get("PIF")[0].doubleValue(), 0); + Assert.assertEquals(7.36, results.get("PIF")[1].doubleValue(), 0); + + instrumentExecutionServiceMock.addOutputParameterValues((Map) anyObject()); + replay(instrumentExecutionServiceMock); + + // Make sure that the results are sent to the server. + minispirInstrumentRunner.sendDataToServer(results); + verify(instrumentExecutionServiceMock); + + } + + @Test + public void testShutdown() throws FileNotFoundException, IOException { + + // Write some arbitrary data to simulate database access by external software. + (new FileOutputStream(miniSpirDbFile)).write((byte) 234432141); + + minispirInstrumentRunner.shutdown(); + + // Verify that the WinSpiro database content has been cleared successfully. + Assert.assertEquals(initDbFile.length(), miniSpirDbFile.length()); + + } + + private void setExpectedOutputParameterNames() { + String elements[] = { "last_name", + "first_name", + "birth_date", + "gender", + "fvc", + "fev1", + "fev1_fvc", + "fev6", + "fev1_fev6", + "pef", + "fef2575", + "fev3", + "fev3_fvc", + "ela", + "fet", + "fef25", + "fef50", + "fef75", + "evol", + "fivc", + "fiv1", + "fiv1_fivc", + "pif", + "fvc_pred", + "fev1_pred", + "fev1_fvc_pred", + "fev6_pred", + "fev1_fev6_pred", + "pef_pred", + "fef2575_pred", + "fev3_pred", + "fev3_fvc_pred", + "ela_pred", + "fet_pred", + "fef25_pred", + "fef50_pred", + "fef75_pred", + "evol_pred", + "fivc_pred", + "fiv1_pred", + "fiv1_fivc_pred", + "pif_pred", + "fvc_image"}; + + expectedOutputParameterNamesSet.addAll(new HashSet(Arrays.asList(elements))); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ContraIndication.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ContraIndication.java index 31c18e6b2..9056e5c6f 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ContraIndication.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ContraIndication.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.core.domain.instrument; import javax.persistence.Column; diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/DateParameterValueConverter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/DateParameterValueConverter.java index c658a94b5..8ad7e3454 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/DateParameterValueConverter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/DateParameterValueConverter.java @@ -1,34 +1,43 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.Calendar; -import java.util.Date; - -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -/** - * Data converter from date (DataType.DATE) to duration (DataType.INTEGER) - * @author acarey - */ - -public class DateParameterValueConverter implements InstrumentParameterValueConverter { - - /** - * Convert a date to a duration in milliseconds - * @param targetInstrumentRunValue - * @param sourceInstrumentRunValue - */ - public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue) { - - InstrumentParameter sourceInsrumentParameter = sourceInstrumentRunValue.getInstrumentParameter(); - - if(!sourceInsrumentParameter.getDataType().equals(DataType.DATE) && !targetInstrumentRunValue.getDataType().equals(DataType.INTEGER)) return; - - Calendar todayCal = Calendar.getInstance(); - Calendar birthCal = Calendar.getInstance(); - birthCal.setTime((Date) sourceInstrumentRunValue.getValue()); - targetInstrumentRunValue.setData(DataBuilder.buildInteger(todayCal.getTimeInMillis() - birthCal.getTimeInMillis())); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.Calendar; +import java.util.Date; + +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +/** + * Data converter from date (DataType.DATE) to duration (DataType.INTEGER) + * @author acarey + */ + +public class DateParameterValueConverter implements InstrumentParameterValueConverter { + + /** + * Convert a date to a duration in milliseconds + * @param targetInstrumentRunValue + * @param sourceInstrumentRunValue + */ + public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue) { + + InstrumentParameter sourceInsrumentParameter = sourceInstrumentRunValue.getInstrumentParameter(); + + if(!sourceInsrumentParameter.getDataType().equals(DataType.DATE) && !targetInstrumentRunValue.getDataType().equals(DataType.INTEGER)) return; + + Calendar todayCal = Calendar.getInstance(); + Calendar birthCal = Calendar.getInstance(); + birthCal.setTime((Date) sourceInstrumentRunValue.getValue()); + targetInstrumentRunValue.setData(DataBuilder.buildInteger(todayCal.getTimeInMillis() - birthCal.getTimeInMillis())); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/FixedSource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/FixedSource.java index 3ba03880b..a557ee046 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/FixedSource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/FixedSource.java @@ -1,40 +1,49 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; - -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@DiscriminatorValue("FixedSource") -public class FixedSource extends InputSource { - - private static final long serialVersionUID = -55114802454360982L; - - @Column(length = 200) - private String value; - - public FixedSource() { - super(); - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public void accept(InputSourceVisitor visitor) { - visitor.visit(this); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@DiscriminatorValue("FixedSource") +public class FixedSource extends InputSource { + + private static final long serialVersionUID = -55114802454360982L; + + @Column(length = 200) + private String value; + + public FixedSource() { + super(); + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean isReadOnly() { + return true; + } + + @Override + public void accept(InputSourceVisitor visitor) { + visitor.visit(this); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InputSource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InputSource.java index 831558563..9072898af 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InputSource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InputSource.java @@ -1,43 +1,52 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.OneToMany; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@DiscriminatorColumn(name = "input_source_type", discriminatorType = DiscriminatorType.STRING) -@DiscriminatorValue("InputSource") -public abstract class InputSource extends AbstractEntity { - - private static final long serialVersionUID = -2701979694735615418L; - - @OneToMany(mappedBy = "inputSource") - private List instrumentInputParameters; - - public List getInstrumentInputParameters() { - return instrumentInputParameters != null ? instrumentInputParameters : (instrumentInputParameters = new ArrayList()); - } - - public void addInstrumentInputParameter(InstrumentInputParameter parameter) { - if(parameter != null) { - getInstrumentInputParameters().add(parameter); - parameter.setInputSource(this); - } - } - - public abstract void accept(InputSourceVisitor visitor); - - public abstract boolean isReadOnly(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.OneToMany; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "input_source_type", discriminatorType = DiscriminatorType.STRING) +@DiscriminatorValue("InputSource") +public abstract class InputSource extends AbstractEntity { + + private static final long serialVersionUID = -2701979694735615418L; + + @OneToMany(mappedBy = "inputSource") + private List instrumentInputParameters; + + public List getInstrumentInputParameters() { + return instrumentInputParameters != null ? instrumentInputParameters : (instrumentInputParameters = new ArrayList()); + } + + public void addInstrumentInputParameter(InstrumentInputParameter parameter) { + if(parameter != null) { + getInstrumentInputParameters().add(parameter); + parameter.setInputSource(this); + } + } + + public abstract void accept(InputSourceVisitor visitor); + + public abstract boolean isReadOnly(); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/Instrument.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/Instrument.java index 35e651133..45576237f 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/Instrument.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/Instrument.java @@ -1,149 +1,158 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -import org.hibernate.annotations.Index; -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; - -@Entity -@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "barcode" }) }) -public class Instrument extends AbstractEntity { - - private static final long serialVersionUID = 14533453L; - - @Column(length = 200) - @Index(name = "name_index") - private String name; - - @Column(length = 200) - private String vendor; - - @Column(length = 200) - private String model; - - @Column(length = 200) - private String serialNumber; - - @Column(length = 200) - private String barcode; - - @Enumerated(EnumType.STRING) - private InstrumentStatus status; - - @ManyToOne - @JoinColumn(name = "instrument_type_id") - private InstrumentType instrumentType; - - @OneToMany(mappedBy = "instrument") - private List instrumentParameters; - - @OneToMany(mappedBy = "instrument") - private List instrumentRuns; - - @OneToMany(mappedBy = "instrument") - private List contraIndications; - - public Instrument() { - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getVendor() { - return vendor; - } - - public void setVendor(String vendor) { - this.vendor = vendor; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public String getSerialNumber() { - return serialNumber; - } - - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } - - public String getBarcode() { - return barcode; - } - - public void setBarcode(String barcode) { - this.barcode = barcode; - } - - public InstrumentStatus getStatus() { - return status; - } - - public void setStatus(InstrumentStatus status) { - this.status = status; - } - - public InstrumentType getInstrumentType() { - return instrumentType; - } - - public void setInstrumentType(InstrumentType instrumentType) { - this.instrumentType = instrumentType; - } - - public List getInstrumentParameters() { - return instrumentParameters != null ? instrumentParameters : (instrumentParameters = new ArrayList()); - } - - public void addInstrumentParameter(InstrumentParameter instrumentParameter) { - if(instrumentParameter != null) { - getInstrumentParameters().add(instrumentParameter); - instrumentParameter.setInstrument(this); - } - } - - public List getInstrumentRuns() { - return instrumentRuns != null ? instrumentRuns : (instrumentRuns = new ArrayList()); - } - - public void addInstrumentRun(InstrumentRun instrumentRun) { - if(instrumentRun != null) { - getInstrumentRuns().add(instrumentRun); - instrumentRun.setInstrument(this); - } - } - - public List getContraIndications() { - return contraIndications != null ? contraIndications : (contraIndications = new ArrayList()); - } - - public void addContraIndication(ContraIndication contraIndication) { - if(contraIndication != null) { - getContraIndications().add(contraIndication); - contraIndication.setInstrument(this); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +import org.hibernate.annotations.Index; +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; + +@Entity +@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "barcode" }) }) +public class Instrument extends AbstractEntity { + + private static final long serialVersionUID = 14533453L; + + @Column(length = 200) + @Index(name = "name_index") + private String name; + + @Column(length = 200) + private String vendor; + + @Column(length = 200) + private String model; + + @Column(length = 200) + private String serialNumber; + + @Column(length = 200) + private String barcode; + + @Enumerated(EnumType.STRING) + private InstrumentStatus status; + + @ManyToOne + @JoinColumn(name = "instrument_type_id") + private InstrumentType instrumentType; + + @OneToMany(mappedBy = "instrument") + private List instrumentParameters; + + @OneToMany(mappedBy = "instrument") + private List instrumentRuns; + + @OneToMany(mappedBy = "instrument") + private List contraIndications; + + public Instrument() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public String getSerialNumber() { + return serialNumber; + } + + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } + + public String getBarcode() { + return barcode; + } + + public void setBarcode(String barcode) { + this.barcode = barcode; + } + + public InstrumentStatus getStatus() { + return status; + } + + public void setStatus(InstrumentStatus status) { + this.status = status; + } + + public InstrumentType getInstrumentType() { + return instrumentType; + } + + public void setInstrumentType(InstrumentType instrumentType) { + this.instrumentType = instrumentType; + } + + public List getInstrumentParameters() { + return instrumentParameters != null ? instrumentParameters : (instrumentParameters = new ArrayList()); + } + + public void addInstrumentParameter(InstrumentParameter instrumentParameter) { + if(instrumentParameter != null) { + getInstrumentParameters().add(instrumentParameter); + instrumentParameter.setInstrument(this); + } + } + + public List getInstrumentRuns() { + return instrumentRuns != null ? instrumentRuns : (instrumentRuns = new ArrayList()); + } + + public void addInstrumentRun(InstrumentRun instrumentRun) { + if(instrumentRun != null) { + getInstrumentRuns().add(instrumentRun); + instrumentRun.setInstrument(this); + } + } + + public List getContraIndications() { + return contraIndications != null ? contraIndications : (contraIndications = new ArrayList()); + } + + public void addContraIndication(ContraIndication contraIndication) { + if(contraIndication != null) { + getContraIndications().add(contraIndication); + contraIndication.setInstrument(this); + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentComputedOutputParameter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentComputedOutputParameter.java index fe3a2b5d4..cb84a1861 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentComputedOutputParameter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentComputedOutputParameter.java @@ -1,49 +1,58 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -@Entity -@DiscriminatorValue("InstrumentComputedOutputParameter") -public class InstrumentComputedOutputParameter extends InstrumentOutputParameter { - - private static final long serialVersionUID = -4217317349036043214L; - - @ManyToMany - @JoinTable(name = "instrument_computed_output", joinColumns = @JoinColumn(name = "instrument_computed_output_parameter_id"), inverseJoinColumns = @JoinColumn(name = "instrument_output_parameter_id")) - private List outputs; - - @Enumerated(EnumType.STRING) - private InstrumentOutputParameterAlgorithm algorithm; - - public InstrumentComputedOutputParameter() { - super(); - } - - public List getInstrumentOutputParameters() { - return outputs != null ? outputs : (outputs = new ArrayList()); - } - - public void addInstrumentOutputParameter(InstrumentOutputParameter instrumentOutputParameter) { - if(instrumentOutputParameter != null) { - getInstrumentOutputParameters().add(instrumentOutputParameter); - } - } - - public InstrumentOutputParameterAlgorithm getAlgorithm() { - return algorithm; - } - - public void setAlgorithm(InstrumentOutputParameterAlgorithm algorithm) { - this.algorithm = algorithm; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +@DiscriminatorValue("InstrumentComputedOutputParameter") +public class InstrumentComputedOutputParameter extends InstrumentOutputParameter { + + private static final long serialVersionUID = -4217317349036043214L; + + @ManyToMany + @JoinTable(name = "instrument_computed_output", joinColumns = @JoinColumn(name = "instrument_computed_output_parameter_id"), inverseJoinColumns = @JoinColumn(name = "instrument_output_parameter_id")) + private List outputs; + + @Enumerated(EnumType.STRING) + private InstrumentOutputParameterAlgorithm algorithm; + + public InstrumentComputedOutputParameter() { + super(); + } + + public List getInstrumentOutputParameters() { + return outputs != null ? outputs : (outputs = new ArrayList()); + } + + public void addInstrumentOutputParameter(InstrumentOutputParameter instrumentOutputParameter) { + if(instrumentOutputParameter != null) { + getInstrumentOutputParameters().add(instrumentOutputParameter); + } + } + + public InstrumentOutputParameterAlgorithm getAlgorithm() { + return algorithm; + } + + public void setAlgorithm(InstrumentOutputParameterAlgorithm algorithm) { + this.algorithm = algorithm; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentDescriptor.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentDescriptor.java index b4f8e7271..22f8945a4 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentDescriptor.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentDescriptor.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -/** - * Instrument descriptor holds instrument specific configuration information. - * @author Yannick Marcon - * - */ -public class InstrumentDescriptor { - - /** - * The barcod of the instrument it is associated with. - */ - private String instrumentBarCode; - - private String codeBase; - - public InstrumentDescriptor(String instrumentBarCode) { - this.instrumentBarCode = instrumentBarCode; - } - - public String getCodeBase() { - return codeBase; - } - - public void setCodeBase(String codeBase) { - this.codeBase = codeBase; - } - - public String getInstrumentBarCode() { - return instrumentBarCode; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +/** + * Instrument descriptor holds instrument specific configuration information. + * @author Yannick Marcon + * + */ +public class InstrumentDescriptor { + + /** + * The barcod of the instrument it is associated with. + */ + private String instrumentBarCode; + + private String codeBase; + + public InstrumentDescriptor(String instrumentBarCode) { + this.instrumentBarCode = instrumentBarCode; + } + + public String getCodeBase() { + return codeBase; + } + + public void setCodeBase(String codeBase) { + this.codeBase = codeBase; + } + + public String getInstrumentBarCode() { + return instrumentBarCode; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentInputParameter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentInputParameter.java index c38de15bb..f5394a181 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentInputParameter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentInputParameter.java @@ -1,30 +1,39 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -@Entity -@DiscriminatorValue("InstrumentInputParameter") -public class InstrumentInputParameter extends InstrumentParameter { - - private static final long serialVersionUID = -5035544856948727535L; - - @ManyToOne - @JoinColumn(name = "input_source_id") - private InputSource inputSource; - - public InstrumentInputParameter() { - super(); - } - - public InputSource getInputSource() { - return inputSource; - } - - public void setInputSource(InputSource inputSource) { - this.inputSource = inputSource; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +@DiscriminatorValue("InstrumentInputParameter") +public class InstrumentInputParameter extends InstrumentParameter { + + private static final long serialVersionUID = -5035544856948727535L; + + @ManyToOne + @JoinColumn(name = "input_source_id") + private InputSource inputSource; + + public InstrumentInputParameter() { + super(); + } + + public InputSource getInputSource() { + return inputSource; + } + + public void setInputSource(InputSource inputSource) { + this.inputSource = inputSource; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameter.java index 61bfd653e..7aa1996ec 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameter.java @@ -1,15 +1,24 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; - -@Entity -@DiscriminatorValue("InstrumentOutputParameter") -public class InstrumentOutputParameter extends InstrumentParameter { - - private static final long serialVersionUID = 1070862021923112847L; - - public InstrumentOutputParameter() { - super(); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("InstrumentOutputParameter") +public class InstrumentOutputParameter extends InstrumentParameter { + + private static final long serialVersionUID = 1070862021923112847L; + + public InstrumentOutputParameter() { + super(); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameterAlgorithm.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameterAlgorithm.java index f62430fce..1e43ad800 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameterAlgorithm.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentOutputParameterAlgorithm.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -public enum InstrumentOutputParameterAlgorithm { - AVERAGE -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +public enum InstrumentOutputParameterAlgorithm { + AVERAGE +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameter.java index 5804bd64f..d34492618 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameter.java @@ -1,155 +1,164 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Transient; - -import org.hibernate.annotations.Index; -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.util.data.DataType; -import org.springframework.context.ApplicationContext; -import org.springframework.context.NoSuchMessageException; - -@Entity -@Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@DiscriminatorColumn(name = "instrument_parameter_type", discriminatorType = DiscriminatorType.STRING, length = 100) -@DiscriminatorValue("InstrumentParameter") -public abstract class InstrumentParameter extends AbstractEntity { - - @Column(length = 200) - @Index(name = "name_index") - private String name; - - @Column(length = 200) - private String description; - - @Column(length = 20) - private String measurementUnit; - - @Enumerated(EnumType.STRING) - private DataType dataType; - - @Enumerated(EnumType.STRING) - private InstrumentParameterCaptureMethod captureMethod; - - @ManyToOne - @JoinColumn(name = "instrument_id") - private Instrument instrument; - - @OneToMany(mappedBy = "instrumentParameter") - private List instrumentRunValues; - - @OneToMany(mappedBy = "targetParameter", cascade = CascadeType.ALL) - private List integrityChecks; - - @Transient - private transient ApplicationContext context; - - @Transient - private transient UserSessionService userSessionService; - - public void setApplicationContext(ApplicationContext context) { - this.context = context; - } - - public void setUserSessionService(UserSessionService userSessionService) { - this.userSessionService = userSessionService; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - String retVal = description; - - if(context != null && userSessionService != null) { - try { - retVal = context.getMessage(description, null, userSessionService.getLocale()); - } catch(NoSuchMessageException ex) { - ; // return non-localized description - } - } - - return retVal; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getMeasurementUnit() { - return measurementUnit; - } - - public void setMeasurementUnit(String measurementUnit) { - this.measurementUnit = measurementUnit; - } - - public DataType getDataType() { - return dataType; - } - - public void setDataType(DataType dataType) { - this.dataType = dataType; - } - - public InstrumentParameterCaptureMethod getCaptureMethod() { - return captureMethod; - } - - public void setCaptureMethod(InstrumentParameterCaptureMethod captureMethod) { - this.captureMethod = captureMethod; - } - - public Instrument getInstrument() { - return instrument; - } - - public void setInstrument(Instrument instrument) { - this.instrument = instrument; - } - - public List getInstrumentRunValues() { - return instrumentRunValues != null ? instrumentRunValues : (instrumentRunValues = new ArrayList()); - } - - public void addInstrumentRunValue(InstrumentRunValue value) { - if(value != null) { - getInstrumentRunValues().add(value); - value.setInstrumentParameter(this); - } - } - - public List getIntegrityChecks() { - return integrityChecks != null ? integrityChecks : (integrityChecks = new ArrayList()); - } - - public void addIntegrityChecks(AbstractIntegrityCheck integrityCheck) { - if(integrityCheck != null) { - getIntegrityChecks().add(integrityCheck); - integrityCheck.setTargetParameter(this); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Transient; + +import org.hibernate.annotations.Index; +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.util.data.DataType; +import org.springframework.context.ApplicationContext; +import org.springframework.context.NoSuchMessageException; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "instrument_parameter_type", discriminatorType = DiscriminatorType.STRING, length = 100) +@DiscriminatorValue("InstrumentParameter") +public abstract class InstrumentParameter extends AbstractEntity { + + @Column(length = 200) + @Index(name = "name_index") + private String name; + + @Column(length = 200) + private String description; + + @Column(length = 20) + private String measurementUnit; + + @Enumerated(EnumType.STRING) + private DataType dataType; + + @Enumerated(EnumType.STRING) + private InstrumentParameterCaptureMethod captureMethod; + + @ManyToOne + @JoinColumn(name = "instrument_id") + private Instrument instrument; + + @OneToMany(mappedBy = "instrumentParameter") + private List instrumentRunValues; + + @OneToMany(mappedBy = "targetParameter", cascade = CascadeType.ALL) + private List integrityChecks; + + @Transient + private transient ApplicationContext context; + + @Transient + private transient UserSessionService userSessionService; + + public void setApplicationContext(ApplicationContext context) { + this.context = context; + } + + public void setUserSessionService(UserSessionService userSessionService) { + this.userSessionService = userSessionService; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + String retVal = description; + + if(context != null && userSessionService != null) { + try { + retVal = context.getMessage(description, null, userSessionService.getLocale()); + } catch(NoSuchMessageException ex) { + ; // return non-localized description + } + } + + return retVal; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getMeasurementUnit() { + return measurementUnit; + } + + public void setMeasurementUnit(String measurementUnit) { + this.measurementUnit = measurementUnit; + } + + public DataType getDataType() { + return dataType; + } + + public void setDataType(DataType dataType) { + this.dataType = dataType; + } + + public InstrumentParameterCaptureMethod getCaptureMethod() { + return captureMethod; + } + + public void setCaptureMethod(InstrumentParameterCaptureMethod captureMethod) { + this.captureMethod = captureMethod; + } + + public Instrument getInstrument() { + return instrument; + } + + public void setInstrument(Instrument instrument) { + this.instrument = instrument; + } + + public List getInstrumentRunValues() { + return instrumentRunValues != null ? instrumentRunValues : (instrumentRunValues = new ArrayList()); + } + + public void addInstrumentRunValue(InstrumentRunValue value) { + if(value != null) { + getInstrumentRunValues().add(value); + value.setInstrumentParameter(this); + } + } + + public List getIntegrityChecks() { + return integrityChecks != null ? integrityChecks : (integrityChecks = new ArrayList()); + } + + public void addIntegrityChecks(AbstractIntegrityCheck integrityCheck) { + if(integrityCheck != null) { + getIntegrityChecks().add(integrityCheck); + integrityCheck.setTargetParameter(this); + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterCaptureMethod.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterCaptureMethod.java index a2f97be56..28b2896af 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterCaptureMethod.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterCaptureMethod.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -public enum InstrumentParameterCaptureMethod { - MANUAL, AUTOMATIC, COMPUTED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +public enum InstrumentParameterCaptureMethod { + MANUAL, AUTOMATIC, COMPUTED +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterValueConverter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterValueConverter.java index d3b9ca055..c5727bae1 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterValueConverter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterValueConverter.java @@ -1,14 +1,23 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; - -/** - * Interface for the InstrumentParameter converters - * @author acarey - */ - -public interface InstrumentParameterValueConverter { - - public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; + +/** + * Interface for the InstrumentParameter converters + * @author acarey + */ + +public interface InstrumentParameterValueConverter { + + public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentStatus.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentStatus.java index 55ee25ad7..0f599c5a9 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentStatus.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentStatus.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -public enum InstrumentStatus { - ACTIVE, INACTIVE, UNINSTALLED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +public enum InstrumentStatus { + ACTIVE, INACTIVE, UNINSTALLED +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentType.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentType.java index 47bccaaef..4489ed86e 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentType.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentType.java @@ -1,95 +1,104 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -import org.hibernate.annotations.Index; -import org.obiba.core.domain.AbstractEntity; - -@Entity -@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }) }) -public class InstrumentType extends AbstractEntity { - - private static final long serialVersionUID = 23414234L; - - @Column(length = 200) - @Index(name = "name_index") - private String name; - - @Column(length = 200) - private String description; - - @OneToMany(mappedBy = "instrumentType") - private List instruments; - - @ManyToMany - @JoinTable(name = "instrument_type_dependencies", joinColumns = @JoinColumn(name = "instrument_type_id"), inverseJoinColumns = @JoinColumn(name = "depends_on_instrument_type_id")) - private List dependsOnTypes; - - @ManyToMany(mappedBy = "dependsOnTypes") - private List dependentTypes; - - public InstrumentType() { - } - - public InstrumentType(String name, String description) { - this.name = name; - this.description = description; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getInstruments() { - return instruments != null ? instruments : (instruments = new ArrayList()); - } - - public void addInstrument(Instrument instrument) { - if(instrument != null) { - getInstruments().add(instrument); - instrument.setInstrumentType(this); - } - } - - public List getDependsOnTypes() { - return dependsOnTypes != null ? dependsOnTypes : (dependsOnTypes = new ArrayList()); - } - - public List getDependentTypes() { - return dependentTypes != null ? dependentTypes : (dependentTypes = new ArrayList()); - } - - public void addDependentType(InstrumentType instrumentType) { - if(!this.equals(instrumentType)) { - getDependentTypes().add(instrumentType); - instrumentType.getDependsOnTypes().add(this); - } - } - - @Override - public String toString() { - return name; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +import org.hibernate.annotations.Index; +import org.obiba.core.domain.AbstractEntity; + +@Entity +@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }) }) +public class InstrumentType extends AbstractEntity { + + private static final long serialVersionUID = 23414234L; + + @Column(length = 200) + @Index(name = "name_index") + private String name; + + @Column(length = 200) + private String description; + + @OneToMany(mappedBy = "instrumentType") + private List instruments; + + @ManyToMany + @JoinTable(name = "instrument_type_dependencies", joinColumns = @JoinColumn(name = "instrument_type_id"), inverseJoinColumns = @JoinColumn(name = "depends_on_instrument_type_id")) + private List dependsOnTypes; + + @ManyToMany(mappedBy = "dependsOnTypes") + private List dependentTypes; + + public InstrumentType() { + } + + public InstrumentType(String name, String description) { + this.name = name; + this.description = description; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getInstruments() { + return instruments != null ? instruments : (instruments = new ArrayList()); + } + + public void addInstrument(Instrument instrument) { + if(instrument != null) { + getInstruments().add(instrument); + instrument.setInstrumentType(this); + } + } + + public List getDependsOnTypes() { + return dependsOnTypes != null ? dependsOnTypes : (dependsOnTypes = new ArrayList()); + } + + public List getDependentTypes() { + return dependentTypes != null ? dependentTypes : (dependentTypes = new ArrayList()); + } + + public void addDependentType(InstrumentType instrumentType) { + if(!this.equals(instrumentType)) { + getDependentTypes().add(instrumentType); + instrumentType.getDependsOnTypes().add(this); + } + } + + @Override + public String toString() { + return name; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InterpretativeParameter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InterpretativeParameter.java index fbc0be29f..29d8f3659 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InterpretativeParameter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/InterpretativeParameter.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; - -import org.obiba.onyx.util.data.DataType; - -@Entity -@DiscriminatorValue("InterpretativeParameter") -public class InterpretativeParameter extends InstrumentParameter { - - private static final long serialVersionUID = -5035544856948727535L; - - @Enumerated(EnumType.STRING) - private ParticipantInteractionType type; - - public InterpretativeParameter() { - super(); - setDataType(DataType.TEXT); - setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); - } - - public ParticipantInteractionType getType() { - return type; - } - - public void setType(ParticipantInteractionType type) { - this.type = type; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; + +import org.obiba.onyx.util.data.DataType; + +@Entity +@DiscriminatorValue("InterpretativeParameter") +public class InterpretativeParameter extends InstrumentParameter { + + private static final long serialVersionUID = -5035544856948727535L; + + @Enumerated(EnumType.STRING) + private ParticipantInteractionType type; + + public InterpretativeParameter() { + super(); + setDataType(DataType.TEXT); + setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); + } + + public ParticipantInteractionType getType() { + return type; + } + + public void setType(ParticipantInteractionType type) { + this.type = type; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/MultipleOutputParameterSource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/MultipleOutputParameterSource.java index 29c3e03a8..d04e2bba1 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/MultipleOutputParameterSource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/MultipleOutputParameterSource.java @@ -1,49 +1,58 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.List; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@DiscriminatorValue("MultipleOutputParameterSource") -public class MultipleOutputParameterSource extends InputSource { - - private static final long serialVersionUID = 1L; - - @ManyToMany - @JoinTable( - name="multiple_output_parameters", - joinColumns = { @JoinColumn(name="multiple_output_parameter_source_id") }, - inverseJoinColumns = @JoinColumn(name="output_parameter_source_id") - ) - - private List outputParameterSourceList; - - public MultipleOutputParameterSource() { - } - - @Override - public void accept(InputSourceVisitor visitor) { - visitor.visit(this); - } - - @Override - public boolean isReadOnly() { - return true; - } - - public List getOutputParameterSourceList() { - return outputParameterSourceList; - } - - public void setOutputParameterSourceList(List outputParameterSourceList) { - this.outputParameterSourceList = outputParameterSourceList; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.List; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@DiscriminatorValue("MultipleOutputParameterSource") +public class MultipleOutputParameterSource extends InputSource { + + private static final long serialVersionUID = 1L; + + @ManyToMany + @JoinTable( + name="multiple_output_parameters", + joinColumns = { @JoinColumn(name="multiple_output_parameter_source_id") }, + inverseJoinColumns = @JoinColumn(name="output_parameter_source_id") + ) + + private List outputParameterSourceList; + + public MultipleOutputParameterSource() { + } + + @Override + public void accept(InputSourceVisitor visitor) { + visitor.visit(this); + } + + @Override + public boolean isReadOnly() { + return true; + } + + public List getOutputParameterSourceList() { + return outputParameterSourceList; + } + + public void setOutputParameterSourceList(List outputParameterSourceList) { + this.outputParameterSourceList = outputParameterSourceList; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OperatorSource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OperatorSource.java index 6a204c1e0..3a078ce72 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OperatorSource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OperatorSource.java @@ -1,41 +1,50 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; - -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@DiscriminatorValue("OperatorSource") -public class OperatorSource extends InputSource { - - private static final long serialVersionUID = -5502454360982L; - - /** - * CSV style separated default values. - */ - private String choices; - - public OperatorSource() { - super(); - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public void accept(InputSourceVisitor visitor) { - visitor.visit(this); - } - - public String getChoices() { - return choices; - } - - public void setChoices(String choices) { - this.choices = choices; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@DiscriminatorValue("OperatorSource") +public class OperatorSource extends InputSource { + + private static final long serialVersionUID = -5502454360982L; + + /** + * CSV style separated default values. + */ + private String choices; + + public OperatorSource() { + super(); + } + + @Override + public boolean isReadOnly() { + return false; + } + + @Override + public void accept(InputSourceVisitor visitor) { + visitor.visit(this); + } + + public String getChoices() { + return choices; + } + + public void setChoices(String choices) { + this.choices = choices; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OutputParameterSource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OutputParameterSource.java index 2704ecce2..0fb3b0242 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OutputParameterSource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/OutputParameterSource.java @@ -1,54 +1,63 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@DiscriminatorValue("OutputParameterSource") -public class OutputParameterSource extends InputSource { - - private static final long serialVersionUID = 79789789454360982L; - - @ManyToOne - @JoinColumn(name = "instrument_type_id") - private InstrumentType instrumentType; - - @Column(length = 200) - private String parameterName; - - public OutputParameterSource() { - super(); - } - - @Override - public boolean isReadOnly() { - return true; - } - - public InstrumentType getInstrumentType() { - return instrumentType; - } - - public void setInstrumentType(InstrumentType instrumentType) { - this.instrumentType = instrumentType; - } - - public String getParameterName() { - return parameterName; - } - - public void setParameterName(String parameterName) { - this.parameterName = parameterName; - } - - @Override - public void accept(InputSourceVisitor visitor) { - visitor.visit(this); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@DiscriminatorValue("OutputParameterSource") +public class OutputParameterSource extends InputSource { + + private static final long serialVersionUID = 79789789454360982L; + + @ManyToOne + @JoinColumn(name = "instrument_type_id") + private InstrumentType instrumentType; + + @Column(length = 200) + private String parameterName; + + public OutputParameterSource() { + super(); + } + + @Override + public boolean isReadOnly() { + return true; + } + + public InstrumentType getInstrumentType() { + return instrumentType; + } + + public void setInstrumentType(InstrumentType instrumentType) { + this.instrumentType = instrumentType; + } + + public String getParameterName() { + return parameterName; + } + + public void setParameterName(String parameterName) { + this.parameterName = parameterName; + } + + @Override + public void accept(InputSourceVisitor visitor) { + visitor.visit(this); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantInteractionType.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantInteractionType.java index b9f4ac838..c6b42ea10 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantInteractionType.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantInteractionType.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -public enum ParticipantInteractionType { - ASKED, OBSERVED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +public enum ParticipantInteractionType { + ASKED, OBSERVED +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantPropertySource.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantPropertySource.java index 0f77d556c..74a638ced 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantPropertySource.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/ParticipantPropertySource.java @@ -1,39 +1,48 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; - -import org.obiba.onyx.jade.core.service.InputSourceVisitor; - -@Entity -@DiscriminatorValue("ParticipantPropertySource") -public class ParticipantPropertySource extends InputSource { - - private static final long serialVersionUID = -5505114802454360982L; - - @Column(length = 200) - private String property; - - public ParticipantPropertySource() { - super(); - } - - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public void accept(InputSourceVisitor visitor) { - visitor.visit(this); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +import org.obiba.onyx.jade.core.service.InputSourceVisitor; + +@Entity +@DiscriminatorValue("ParticipantPropertySource") +public class ParticipantPropertySource extends InputSource { + + private static final long serialVersionUID = -5505114802454360982L; + + @Column(length = 200) + private String property; + + public ParticipantPropertySource() { + super(); + } + + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + @Override + public boolean isReadOnly() { + return true; + } + + @Override + public void accept(InputSourceVisitor visitor) { + visitor.visit(this); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/UnitParameterValueConverter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/UnitParameterValueConverter.java index f0f60059d..898aea85d 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/UnitParameterValueConverter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/UnitParameterValueConverter.java @@ -1,60 +1,69 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import javax.measure.unit.Unit; - -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Unit converter - * @author acarey - */ - -public final class UnitParameterValueConverter implements InstrumentParameterValueConverter { - - private static final Logger log = LoggerFactory.getLogger(UnitParameterValueConverter.class); - - /** - * Convert the value from a source unit to a target unit Note: if the value is an age, the method adjusts the value to - * return the right age - * @param targetInstrumentRunValue - * @param sourceInstrumentRunValue - */ - @SuppressWarnings("unchecked") - public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue) { - - log.debug("Converting parameters from source {} to target {}", sourceInstrumentRunValue.getInstrumentParameter().getName(), targetInstrumentRunValue.getInstrumentParameter().getName()); - - Unit sourceUnit = Unit.valueOf(sourceInstrumentRunValue.getInstrumentParameter().getMeasurementUnit()); - Unit targetUnit = Unit.valueOf(targetInstrumentRunValue.getInstrumentParameter().getMeasurementUnit()); - - log.debug("Converting units from source {} to target {}", sourceUnit.toString(), targetUnit.toString()); - - double sourceValue; - // Extract the source value and convert it to a double - try { - sourceValue = Double.parseDouble(sourceInstrumentRunValue.getData().getValueAsString()); - } catch(NumberFormatException e) { - Data sourceData = sourceInstrumentRunValue.getData(); - log.error("Error converting between measurement units. Original value {} of type {} cannot be converted to a double, which is required to convert between measurement units.", sourceData.getValueAsString(), sourceData.getType()); - throw e; - } - - double newValue = sourceUnit.getConverterTo(targetUnit).convert(sourceValue); - - switch(targetInstrumentRunValue.getInstrumentParameter().getDataType()) { - case DECIMAL: - targetInstrumentRunValue.setData(DataBuilder.buildDecimal(newValue)); - break; - - case INTEGER: - if(targetUnit.toString().equalsIgnoreCase("year")) newValue = Math.floor(newValue); - targetInstrumentRunValue.setData(DataBuilder.buildInteger(Math.round(newValue))); - break; - } - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import javax.measure.unit.Unit; + +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Unit converter + * @author acarey + */ + +public final class UnitParameterValueConverter implements InstrumentParameterValueConverter { + + private static final Logger log = LoggerFactory.getLogger(UnitParameterValueConverter.class); + + /** + * Convert the value from a source unit to a target unit Note: if the value is an age, the method adjusts the value to + * return the right age + * @param targetInstrumentRunValue + * @param sourceInstrumentRunValue + */ + @SuppressWarnings("unchecked") + public void convert(InstrumentRunValue targetInstrumentRunValue, InstrumentRunValue sourceInstrumentRunValue) { + + log.debug("Converting parameters from source {} to target {}", sourceInstrumentRunValue.getInstrumentParameter().getName(), targetInstrumentRunValue.getInstrumentParameter().getName()); + + Unit sourceUnit = Unit.valueOf(sourceInstrumentRunValue.getInstrumentParameter().getMeasurementUnit()); + Unit targetUnit = Unit.valueOf(targetInstrumentRunValue.getInstrumentParameter().getMeasurementUnit()); + + log.debug("Converting units from source {} to target {}", sourceUnit.toString(), targetUnit.toString()); + + double sourceValue; + // Extract the source value and convert it to a double + try { + sourceValue = Double.parseDouble(sourceInstrumentRunValue.getData().getValueAsString()); + } catch(NumberFormatException e) { + Data sourceData = sourceInstrumentRunValue.getData(); + log.error("Error converting between measurement units. Original value {} of type {} cannot be converted to a double, which is required to convert between measurement units.", sourceData.getValueAsString(), sourceData.getType()); + throw e; + } + + double newValue = sourceUnit.getConverterTo(targetUnit).convert(sourceValue); + + switch(targetInstrumentRunValue.getInstrumentParameter().getDataType()) { + case DECIMAL: + targetInstrumentRunValue.setData(DataBuilder.buildDecimal(newValue)); + break; + + case INTEGER: + if(targetUnit.toString().equalsIgnoreCase("year")) newValue = Math.floor(newValue); + targetInstrumentRunValue.setData(DataBuilder.buildInteger(Math.round(newValue))); + break; + } + + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/AbstractIntegrityCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/AbstractIntegrityCheck.java index 27e53db23..a388f3285 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/AbstractIntegrityCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/AbstractIntegrityCheck.java @@ -1,110 +1,119 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Transient; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.springframework.context.ApplicationContext; - -@Entity(name = "IntegrityCheck") -@Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@DiscriminatorColumn(name = "integrity_check_type", discriminatorType = DiscriminatorType.STRING, length = 100) -public abstract class AbstractIntegrityCheck extends AbstractEntity implements IntegrityCheck { - - @Enumerated(EnumType.STRING) - private IntegrityCheckType type; - - @ManyToOne - @JoinColumn(name = "instrument_parameter_id") - private InstrumentParameter targetParameter; - - private String customizedDescription; - - @Transient - protected transient ApplicationContext context; - - @Transient - protected transient UserSessionService userSessionService; - - public void setApplicationContext(ApplicationContext context) { - this.context = context; - } - - public void setUserSessionService(UserSessionService userSessionService) { - this.userSessionService = userSessionService; - } - - public void setType(IntegrityCheckType type) { - this.type = type; - } - - public IntegrityCheckType getType() { - if (type == null) { - type = IntegrityCheckType.ERROR; - } - - return type; - } - - public void setTargetParameter(InstrumentParameter targetParameter) { - this.targetParameter = targetParameter; - } - - public InstrumentParameter getTargetParameter() { - return targetParameter; - } - - public void setCustomizedDescription(String customizedDescription) { - this.customizedDescription = customizedDescription; - } - - public String getCustomizedDescription() { - return customizedDescription; - } - - // - // IntegrityCheck Methods - // - - public abstract boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService); - - public String getDescription(ActiveInstrumentRunService activeRunService) { - String retVal = getClass().getSimpleName(); - - if(context != null && userSessionService != null) { - // Set the target parameter's context and user session service to ensure - // proper localization. - targetParameter.setApplicationContext(context); - targetParameter.setUserSessionService(userSessionService); - - retVal = context.getMessage(getDescriptionKey(activeRunService), getDescriptionArgs(activeRunService), userSessionService.getLocale()); - } - - return retVal; - } - - protected String getDescriptionKey(ActiveInstrumentRunService activeRunService) { - String descriptionKey = getCustomizedDescription(); - - if (descriptionKey == null) { - descriptionKey = getClass().getSimpleName(); - } - - return descriptionKey; - } - - protected abstract Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Transient; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.springframework.context.ApplicationContext; + +@Entity(name = "IntegrityCheck") +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "integrity_check_type", discriminatorType = DiscriminatorType.STRING, length = 100) +public abstract class AbstractIntegrityCheck extends AbstractEntity implements IntegrityCheck { + + @Enumerated(EnumType.STRING) + private IntegrityCheckType type; + + @ManyToOne + @JoinColumn(name = "instrument_parameter_id") + private InstrumentParameter targetParameter; + + private String customizedDescription; + + @Transient + protected transient ApplicationContext context; + + @Transient + protected transient UserSessionService userSessionService; + + public void setApplicationContext(ApplicationContext context) { + this.context = context; + } + + public void setUserSessionService(UserSessionService userSessionService) { + this.userSessionService = userSessionService; + } + + public void setType(IntegrityCheckType type) { + this.type = type; + } + + public IntegrityCheckType getType() { + if (type == null) { + type = IntegrityCheckType.ERROR; + } + + return type; + } + + public void setTargetParameter(InstrumentParameter targetParameter) { + this.targetParameter = targetParameter; + } + + public InstrumentParameter getTargetParameter() { + return targetParameter; + } + + public void setCustomizedDescription(String customizedDescription) { + this.customizedDescription = customizedDescription; + } + + public String getCustomizedDescription() { + return customizedDescription; + } + + // + // IntegrityCheck Methods + // + + public abstract boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService); + + public String getDescription(ActiveInstrumentRunService activeRunService) { + String retVal = getClass().getSimpleName(); + + if(context != null && userSessionService != null) { + // Set the target parameter's context and user session service to ensure + // proper localization. + targetParameter.setApplicationContext(context); + targetParameter.setUserSessionService(userSessionService); + + retVal = context.getMessage(getDescriptionKey(activeRunService), getDescriptionArgs(activeRunService), userSessionService.getLocale()); + } + + return retVal; + } + + protected String getDescriptionKey(ActiveInstrumentRunService activeRunService) { + String descriptionKey = getCustomizedDescription(); + + if (descriptionKey == null) { + descriptionKey = getClass().getSimpleName(); + } + + return descriptionKey; + } + + protected abstract Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService); +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheck.java index 3df1a770b..6956fbca1 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheck.java @@ -1,100 +1,109 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import java.util.Map; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Transient; - -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; - -/** - * Integrity check to verify that an instrument run value is equal to the value of another parameter. - * - * The check fails (returns false) if the values are not equal. - * - * @author cag-dspathis - * - */ -@Entity -@DiscriminatorValue("EqualsParameterCheck") -public class EqualsParameterCheck extends AbstractIntegrityCheck implements IntegrityCheck { - - private static final long serialVersionUID = 1L; - - @Transient - private EqualsValueCheck equalsValueCheck; - - @ManyToOne - private InstrumentParameter parameter; - - public EqualsParameterCheck() { - equalsValueCheck = new EqualsValueCheck(); - } - - public void setParameter(InstrumentParameter param) { - this.parameter = param; - } - - public InstrumentParameter getParameter() { - return this.parameter; - } - - // - // IntegrityCheck Methods - // - - /** - * Returns true if the specified instrument run value is equal to the value of the configured other - * parameter. - * - * @param runValue instrument run value - * @param runService instrument run service - * @return true if instrument run value equals value of configured other parameter - */ - public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { - // If the other parameter has not been specified, there is nothing to check! - if (parameter == null) { - return true; - } - - // - // Get the other parameter's value. - // - InstrumentRunValue otherRunValue = null; - Data otherData = null; - - if (parameter instanceof InstrumentInputParameter) { - otherRunValue = activeRunService.getInputInstrumentRunValue(parameter.getName()); - } - else if (parameter instanceof InstrumentOutputParameter) { - otherRunValue = activeRunService.getOutputInstrumentRunValue(parameter.getName()); - } - - if (otherRunValue != null) { - otherData = otherRunValue.getData(); - } - - // Update the equalsValueCheck accordingly. - equalsValueCheck.setTargetParameter(getTargetParameter()); - equalsValueCheck.setData(otherData); - - return equalsValueCheck.checkParameterValue(paramData, null, null); - } - - protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { - // Set the parameter's context and user session service to ensure - // proper localization. - parameter.setApplicationContext(context); - parameter.setUserSessionService(userSessionService); - - return new Object[] { getTargetParameter().getDescription(), parameter.getDescription() }; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import java.util.Map; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.Transient; + +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; + +/** + * Integrity check to verify that an instrument run value is equal to the value of another parameter. + * + * The check fails (returns false) if the values are not equal. + * + * @author cag-dspathis + * + */ +@Entity +@DiscriminatorValue("EqualsParameterCheck") +public class EqualsParameterCheck extends AbstractIntegrityCheck implements IntegrityCheck { + + private static final long serialVersionUID = 1L; + + @Transient + private EqualsValueCheck equalsValueCheck; + + @ManyToOne + private InstrumentParameter parameter; + + public EqualsParameterCheck() { + equalsValueCheck = new EqualsValueCheck(); + } + + public void setParameter(InstrumentParameter param) { + this.parameter = param; + } + + public InstrumentParameter getParameter() { + return this.parameter; + } + + // + // IntegrityCheck Methods + // + + /** + * Returns true if the specified instrument run value is equal to the value of the configured other + * parameter. + * + * @param runValue instrument run value + * @param runService instrument run service + * @return true if instrument run value equals value of configured other parameter + */ + public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { + // If the other parameter has not been specified, there is nothing to check! + if (parameter == null) { + return true; + } + + // + // Get the other parameter's value. + // + InstrumentRunValue otherRunValue = null; + Data otherData = null; + + if (parameter instanceof InstrumentInputParameter) { + otherRunValue = activeRunService.getInputInstrumentRunValue(parameter.getName()); + } + else if (parameter instanceof InstrumentOutputParameter) { + otherRunValue = activeRunService.getOutputInstrumentRunValue(parameter.getName()); + } + + if (otherRunValue != null) { + otherData = otherRunValue.getData(); + } + + // Update the equalsValueCheck accordingly. + equalsValueCheck.setTargetParameter(getTargetParameter()); + equalsValueCheck.setData(otherData); + + return equalsValueCheck.checkParameterValue(paramData, null, null); + } + + protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { + // Set the parameter's context and user session service to ensure + // proper localization. + parameter.setApplicationContext(context); + parameter.setUserSessionService(userSessionService); + + return new Object[] { getTargetParameter().getDescription(), parameter.getDescription() }; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheck.java index be6d67cce..0f0cf14e7 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheck.java @@ -1,161 +1,170 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import org.apache.wicket.Application; -import org.apache.wicket.spring.SpringWebApplication; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; -import org.springframework.context.ApplicationContext; - -/** - * Integrity check to verify that an instrument run value is equal to a given (fixed) value. - * - * The check fails (returns false) if the values are not equal. - * - * @author cag-dspathis - * - */ -@Entity -@DiscriminatorValue("EqualsValueCheck") -public class EqualsValueCheck extends AbstractIntegrityCheck implements IntegrityCheck { - - private static final long serialVersionUID = 1L; - - private Boolean booleanValue; - - private Long integerValue; - - private Double decimalValue; - - private String textValue; - - @Temporal(TemporalType.TIMESTAMP) - private Date dateValue; - - public EqualsValueCheck() { - super(); - } - - public DataType getValueType() { - return getTargetParameter().getDataType(); - } - - public void setBooleanValue(boolean value) { - booleanValue = Boolean.valueOf(value); - } - - public void setIntegerValue(long value) { - integerValue = Long.valueOf(value); - } - - public void setDecimalValue(double value) { - decimalValue = Double.valueOf(value); - } - - public void setTextValue(String value) { - textValue = value; - } - - public void setDateValue(Date value) { - dateValue = value; - } - - public void setData(Data data) { - if(data != null) { - if(data.getType().equals(getValueType())) { - - switch(getValueType()) { - case BOOLEAN: - booleanValue = data.getValue(); - break; - - case INTEGER: - integerValue = data.getValue(); - break; - - case DECIMAL: - decimalValue = data.getValue(); - break; - - case TEXT: - textValue = data.getValue(); - break; - - case DATE: - dateValue = data.getValue(); - break; - } - } else { - throw new IllegalArgumentException("DataType " + getValueType() + " expected, " + data.getType() + " received."); - } - } - } - - public Data getData() { - Data data = null; - - switch(getValueType()) { - case BOOLEAN: - data = DataBuilder.buildBoolean(booleanValue); - break; - - case INTEGER: - data = DataBuilder.buildInteger(integerValue); - break; - - case DECIMAL: - data = DataBuilder.buildDecimal(decimalValue); - break; - - case TEXT: - data = DataBuilder.buildText(textValue); - break; - - case DATE: - data = DataBuilder.buildDate(dateValue); - } - - return data; - } - - // - // IntegrityCheck Methods - // - - /** - * Returns true if the specified instrument run value is equal to the configured value. - * - * @param runValue instrument run value - * @param runService instrument run service (not used by this check) - * @return true if instrument run value equals configured value - */ - public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { - - boolean isEqual = false; - - if(paramData != null) { - isEqual = paramData.equals(getData()); - } else { - isEqual = (getData() == null); - } - - return isEqual; - } - - protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { - return new Object[] { getTargetParameter().getDescription(), getData().getValue() }; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.apache.wicket.Application; +import org.apache.wicket.spring.SpringWebApplication; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; +import org.springframework.context.ApplicationContext; + +/** + * Integrity check to verify that an instrument run value is equal to a given (fixed) value. + * + * The check fails (returns false) if the values are not equal. + * + * @author cag-dspathis + * + */ +@Entity +@DiscriminatorValue("EqualsValueCheck") +public class EqualsValueCheck extends AbstractIntegrityCheck implements IntegrityCheck { + + private static final long serialVersionUID = 1L; + + private Boolean booleanValue; + + private Long integerValue; + + private Double decimalValue; + + private String textValue; + + @Temporal(TemporalType.TIMESTAMP) + private Date dateValue; + + public EqualsValueCheck() { + super(); + } + + public DataType getValueType() { + return getTargetParameter().getDataType(); + } + + public void setBooleanValue(boolean value) { + booleanValue = Boolean.valueOf(value); + } + + public void setIntegerValue(long value) { + integerValue = Long.valueOf(value); + } + + public void setDecimalValue(double value) { + decimalValue = Double.valueOf(value); + } + + public void setTextValue(String value) { + textValue = value; + } + + public void setDateValue(Date value) { + dateValue = value; + } + + public void setData(Data data) { + if(data != null) { + if(data.getType().equals(getValueType())) { + + switch(getValueType()) { + case BOOLEAN: + booleanValue = data.getValue(); + break; + + case INTEGER: + integerValue = data.getValue(); + break; + + case DECIMAL: + decimalValue = data.getValue(); + break; + + case TEXT: + textValue = data.getValue(); + break; + + case DATE: + dateValue = data.getValue(); + break; + } + } else { + throw new IllegalArgumentException("DataType " + getValueType() + " expected, " + data.getType() + " received."); + } + } + } + + public Data getData() { + Data data = null; + + switch(getValueType()) { + case BOOLEAN: + data = DataBuilder.buildBoolean(booleanValue); + break; + + case INTEGER: + data = DataBuilder.buildInteger(integerValue); + break; + + case DECIMAL: + data = DataBuilder.buildDecimal(decimalValue); + break; + + case TEXT: + data = DataBuilder.buildText(textValue); + break; + + case DATE: + data = DataBuilder.buildDate(dateValue); + } + + return data; + } + + // + // IntegrityCheck Methods + // + + /** + * Returns true if the specified instrument run value is equal to the configured value. + * + * @param runValue instrument run value + * @param runService instrument run service (not used by this check) + * @return true if instrument run value equals configured value + */ + public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { + + boolean isEqual = false; + + if(paramData != null) { + isEqual = paramData.equals(getData()); + } else { + isEqual = (getData() == null); + } + + return isEqual; + } + + protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { + return new Object[] { getTargetParameter().getDescription(), getData().getValue() }; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheck.java index c3fff197b..6dfb4c577 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheck.java @@ -1,71 +1,80 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import java.util.Map; - -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.springframework.context.ApplicationContext; - -/** - * Interface for instrument parameter integrity checks. - * - * @author cag-dspathis - * - */ -public interface IntegrityCheck { - - /** - * Returns the type of check. - * - * @return check type - */ - public IntegrityCheckType getType(); - - /** - * Sets the parameter to which this check is applied. - * - * @param targetParameter parameter to which this check is applied - */ - public void setTargetParameter(InstrumentParameter targetParameter); - - /** - * Returns the parameter to which this check is applied. - * - * @return parameter to which this check is applied - */ - public InstrumentParameter getTargetParameter(); - - /** - * Checks the specified instrument run value. - * - * The nature of the "check" is specific to implementing classes. - * - * @param paramData the instrument run value to check - * @param runService service used to query other parameter values if needed by the check (null if not - * used) - * @param activeRunService service used to query the active instrument run (null if not used) - * @return true if the value passes the check - */ - public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService); - - /** - * Returns a (localized) description of the check performed. - * - * If a check's behaviour varies based on features of the measurement context, the - * check's description may also be different in different contexts. For example, a - * range check that specifies different ranges for male and female participants may - * return one description when the current participant is male and another when the - * current participant is female. - * - * @param activeRunService service used to query the measurement context - * @return localized description - */ - public String getDescription(ActiveInstrumentRunService activeRunService); - - public void setApplicationContext(ApplicationContext context); - - public void setUserSessionService(UserSessionService userSessionService); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import java.util.Map; + +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.springframework.context.ApplicationContext; + +/** + * Interface for instrument parameter integrity checks. + * + * @author cag-dspathis + * + */ +public interface IntegrityCheck { + + /** + * Returns the type of check. + * + * @return check type + */ + public IntegrityCheckType getType(); + + /** + * Sets the parameter to which this check is applied. + * + * @param targetParameter parameter to which this check is applied + */ + public void setTargetParameter(InstrumentParameter targetParameter); + + /** + * Returns the parameter to which this check is applied. + * + * @return parameter to which this check is applied + */ + public InstrumentParameter getTargetParameter(); + + /** + * Checks the specified instrument run value. + * + * The nature of the "check" is specific to implementing classes. + * + * @param paramData the instrument run value to check + * @param runService service used to query other parameter values if needed by the check (null if not + * used) + * @param activeRunService service used to query the active instrument run (null if not used) + * @return true if the value passes the check + */ + public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService); + + /** + * Returns a (localized) description of the check performed. + * + * If a check's behaviour varies based on features of the measurement context, the + * check's description may also be different in different contexts. For example, a + * range check that specifies different ranges for male and female participants may + * return one description when the current participant is male and another when the + * current participant is female. + * + * @param activeRunService service used to query the measurement context + * @return localized description + */ + public String getDescription(ActiveInstrumentRunService activeRunService); + + public void setApplicationContext(ApplicationContext context); + + public void setUserSessionService(UserSessionService userSessionService); +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheckType.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheckType.java index 99d191915..eef0ebc9d 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheckType.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/IntegrityCheckType.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -public enum IntegrityCheckType { - ERROR, WARNING -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +public enum IntegrityCheckType { + ERROR, WARNING +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheck.java index a0096a99b..010d97954 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheck.java @@ -1,202 +1,211 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import java.util.Map; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Transient; - -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; - -@Entity -@DiscriminatorValue("ParameterSpreadCheck") -public class ParameterSpreadCheck extends AbstractIntegrityCheck implements IntegrityCheck { - - private static final long serialVersionUID = 1L; - - @Transient - private RangeCheck rangeCheck; - - @ManyToOne - private InstrumentParameter parameter; - - private Integer percent; - - private Integer offset; - - public ParameterSpreadCheck() { - rangeCheck = new RangeCheck(); - } - - public void setParameter(InstrumentParameter param) { - this.parameter = param; - } - - public InstrumentParameter getParameter() { - return parameter; - } - - public DataType getValueType() { - return getTargetParameter().getDataType(); - } - - public void setPercent(Integer percent) { - this.percent = percent; - } - - public Integer getPercent() { - return percent; - } - - public void setOffset(Integer offset) { - this.offset = offset; - } - - public Integer getOffset() { - return offset; - } - - // - // IntegrityCheck Methods - // - - @Override - public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { - if (parameter != null && (percent != null || offset != null)) { - // - // Get the other parameter's value. - // - InstrumentRunValue otherRunValue = null; - Data otherData = null; - - if (parameter instanceof InstrumentInputParameter) { - otherRunValue = activeRunService.getInputInstrumentRunValue(parameter.getName()); - } - else if (parameter instanceof InstrumentOutputParameter) { - otherRunValue = activeRunService.getOutputInstrumentRunValue(parameter.getName()); - } - - if (otherRunValue != null) { - otherData = otherRunValue.getData(); - } - - if (otherData != null && otherData.getValue() != null) { - // Update the rangeCheck accordingly. - rangeCheck.setTargetParameter(getTargetParameter()); - - if(getValueType().equals(DataType.INTEGER)) { - initIntegerRangeCheck(paramData, otherData); - } else if(getValueType().equals(DataType.DECIMAL)) { - initDecimalRangeCheck(paramData, otherData); - } else { - return false; - } - - return rangeCheck.checkParameterValue(paramData, null, activeRunService); - } - else { // no need to check the spread if the other parameter does not yet have a value - return true; - } - } - else { // nothing to check! - return true; - } - } - - @Override - protected String getDescriptionKey(ActiveInstrumentRunService activeRunService) { - String descriptionKey = super.getDescriptionKey(activeRunService); - - if (percent != null && offset == null) { - descriptionKey += "_PercentOnly"; - } - else if (percent == null && offset != null) { - descriptionKey += "_OffsetOnly"; - } - - return descriptionKey; - } - - protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { - // Set the parameter's context and user session service to ensure - // proper localization. - parameter.setApplicationContext(context); - parameter.setUserSessionService(userSessionService); - - if (percent != null && offset == null) { - return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), percent }; - } - else if (percent == null && offset != null) { - return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), offset, getTargetParameter().getMeasurementUnit() }; - } - else { - return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), percent, offset, getTargetParameter().getMeasurementUnit() }; - } - } - - private void initIntegerRangeCheck(Data checkedData, Data otherData) { - Long otherValue = otherData.getValue(); - - Long minCheckedValue = otherValue; - Long maxCheckedValue = otherValue; - - if (percent != null) { - double percentValue = percent / 100.0; - - minCheckedValue = new Double(Math.ceil((1.0 - percentValue) * otherValue.longValue())).longValue(); - maxCheckedValue = new Double(Math.floor((1.0 + percentValue) * otherValue.longValue())).longValue(); - } - - if (offset != null) { - minCheckedValue = minCheckedValue - offset; - maxCheckedValue = maxCheckedValue + offset; - } - - if (percent == null && offset == null) { - minCheckedValue = null; - maxCheckedValue = null; - } - - rangeCheck.setIntegerMinValueMale(minCheckedValue); - rangeCheck.setIntegerMaxValueMale(maxCheckedValue); - rangeCheck.setIntegerMinValueFemale(minCheckedValue); - rangeCheck.setIntegerMaxValueFemale(maxCheckedValue); - } - - private void initDecimalRangeCheck(Data checkedData, Data otherData) { - Double otherValue = otherData.getValue(); - - Double minCheckedValue = otherValue.doubleValue(); - Double maxCheckedValue = otherValue.doubleValue(); - - if (percent != null) { - double percentValue = percent / 100.0; - - minCheckedValue = (1.0 - percentValue) * otherValue; - maxCheckedValue = (1.0 + percentValue) * otherValue; - } - - if (offset != null) { - minCheckedValue = minCheckedValue - offset.longValue(); - maxCheckedValue = maxCheckedValue + offset.longValue(); - } - - if (percent == null && offset == null) { - minCheckedValue = null; - maxCheckedValue = null; - } - - rangeCheck.setDecimalMinValueMale(minCheckedValue); - rangeCheck.setDecimalMaxValueMale(maxCheckedValue); - rangeCheck.setDecimalMinValueFemale(minCheckedValue); - rangeCheck.setDecimalMaxValueFemale(maxCheckedValue); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import java.util.Map; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.Transient; + +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; + +@Entity +@DiscriminatorValue("ParameterSpreadCheck") +public class ParameterSpreadCheck extends AbstractIntegrityCheck implements IntegrityCheck { + + private static final long serialVersionUID = 1L; + + @Transient + private RangeCheck rangeCheck; + + @ManyToOne + private InstrumentParameter parameter; + + private Integer percent; + + private Integer offset; + + public ParameterSpreadCheck() { + rangeCheck = new RangeCheck(); + } + + public void setParameter(InstrumentParameter param) { + this.parameter = param; + } + + public InstrumentParameter getParameter() { + return parameter; + } + + public DataType getValueType() { + return getTargetParameter().getDataType(); + } + + public void setPercent(Integer percent) { + this.percent = percent; + } + + public Integer getPercent() { + return percent; + } + + public void setOffset(Integer offset) { + this.offset = offset; + } + + public Integer getOffset() { + return offset; + } + + // + // IntegrityCheck Methods + // + + @Override + public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { + if (parameter != null && (percent != null || offset != null)) { + // + // Get the other parameter's value. + // + InstrumentRunValue otherRunValue = null; + Data otherData = null; + + if (parameter instanceof InstrumentInputParameter) { + otherRunValue = activeRunService.getInputInstrumentRunValue(parameter.getName()); + } + else if (parameter instanceof InstrumentOutputParameter) { + otherRunValue = activeRunService.getOutputInstrumentRunValue(parameter.getName()); + } + + if (otherRunValue != null) { + otherData = otherRunValue.getData(); + } + + if (otherData != null && otherData.getValue() != null) { + // Update the rangeCheck accordingly. + rangeCheck.setTargetParameter(getTargetParameter()); + + if(getValueType().equals(DataType.INTEGER)) { + initIntegerRangeCheck(paramData, otherData); + } else if(getValueType().equals(DataType.DECIMAL)) { + initDecimalRangeCheck(paramData, otherData); + } else { + return false; + } + + return rangeCheck.checkParameterValue(paramData, null, activeRunService); + } + else { // no need to check the spread if the other parameter does not yet have a value + return true; + } + } + else { // nothing to check! + return true; + } + } + + @Override + protected String getDescriptionKey(ActiveInstrumentRunService activeRunService) { + String descriptionKey = super.getDescriptionKey(activeRunService); + + if (percent != null && offset == null) { + descriptionKey += "_PercentOnly"; + } + else if (percent == null && offset != null) { + descriptionKey += "_OffsetOnly"; + } + + return descriptionKey; + } + + protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { + // Set the parameter's context and user session service to ensure + // proper localization. + parameter.setApplicationContext(context); + parameter.setUserSessionService(userSessionService); + + if (percent != null && offset == null) { + return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), percent }; + } + else if (percent == null && offset != null) { + return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), offset, getTargetParameter().getMeasurementUnit() }; + } + else { + return new Object[] { getTargetParameter().getDescription(), parameter.getDescription(), percent, offset, getTargetParameter().getMeasurementUnit() }; + } + } + + private void initIntegerRangeCheck(Data checkedData, Data otherData) { + Long otherValue = otherData.getValue(); + + Long minCheckedValue = otherValue; + Long maxCheckedValue = otherValue; + + if (percent != null) { + double percentValue = percent / 100.0; + + minCheckedValue = new Double(Math.ceil((1.0 - percentValue) * otherValue.longValue())).longValue(); + maxCheckedValue = new Double(Math.floor((1.0 + percentValue) * otherValue.longValue())).longValue(); + } + + if (offset != null) { + minCheckedValue = minCheckedValue - offset; + maxCheckedValue = maxCheckedValue + offset; + } + + if (percent == null && offset == null) { + minCheckedValue = null; + maxCheckedValue = null; + } + + rangeCheck.setIntegerMinValueMale(minCheckedValue); + rangeCheck.setIntegerMaxValueMale(maxCheckedValue); + rangeCheck.setIntegerMinValueFemale(minCheckedValue); + rangeCheck.setIntegerMaxValueFemale(maxCheckedValue); + } + + private void initDecimalRangeCheck(Data checkedData, Data otherData) { + Double otherValue = otherData.getValue(); + + Double minCheckedValue = otherValue.doubleValue(); + Double maxCheckedValue = otherValue.doubleValue(); + + if (percent != null) { + double percentValue = percent / 100.0; + + minCheckedValue = (1.0 - percentValue) * otherValue; + maxCheckedValue = (1.0 + percentValue) * otherValue; + } + + if (offset != null) { + minCheckedValue = minCheckedValue - offset.longValue(); + maxCheckedValue = maxCheckedValue + offset.longValue(); + } + + if (percent == null && offset == null) { + minCheckedValue = null; + maxCheckedValue = null; + } + + rangeCheck.setDecimalMinValueMale(minCheckedValue); + rangeCheck.setDecimalMaxValueMale(maxCheckedValue); + rangeCheck.setDecimalMinValueFemale(minCheckedValue); + rangeCheck.setDecimalMaxValueFemale(maxCheckedValue); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheck.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheck.java index 8b98b6569..6f273522a 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheck.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheck.java @@ -1,173 +1,182 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import java.util.Map; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; - -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.InstrumentInputParameterPanel; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Entity -@DiscriminatorValue("RangeCheck") -public class RangeCheck extends AbstractIntegrityCheck implements IntegrityCheck { - - private static final long serialVersionUID = 1L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(RangeCheck.class); - - private Long integerMinValueMale; - - private Long integerMaxValueMale; - - private Long integerMinValueFemale; - - private Long integerMaxValueFemale; - - private Double decimalMinValueMale; - - private Double decimalMaxValueMale; - - private Double decimalMinValueFemale; - - private Double decimalMaxValueFemale; - - public RangeCheck() { - super(); - } - - public DataType getValueType() { - return getTargetParameter().getDataType(); - } - - public void setIntegerMinValueMale(Long value) { - integerMinValueMale = value; - } - - public void setIntegerMaxValueMale(Long value) { - integerMaxValueMale = value; - } - - public void setIntegerMinValueFemale(Long value) { - integerMinValueFemale = value; - } - - public void setIntegerMaxValueFemale(Long value) { - integerMaxValueFemale = value; - } - - public void setDecimalMinValueMale(Double value) { - decimalMinValueMale = value; - } - - public void setDecimalMaxValueMale(Double value) { - decimalMaxValueMale = value; - } - - public void setDecimalMinValueFemale(Double value) { - decimalMinValueFemale = value; - } - - public void setDecimalMaxValueFemale(Double value) { - decimalMaxValueFemale = value; - } - - // - // IntegrityCheck Methods - // - - @Override - public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { - // Get the participant's gender (range is gender-dependent). - Gender gender = activeRunService.getParticipant().getGender(); - - if(getValueType().equals(DataType.INTEGER)) { - return checkIntegerParameterValue(paramData, gender); - } else if(getValueType().equals(DataType.DECIMAL)) { - return checkDecimalParameterValue(paramData, gender); - } - - return false; - } - - protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { - Object[] args = null; - - // For male participants, return the min/max values for males; for female participants, - // return the min/max values for females. - Participant participant = activeRunService.getParticipant(); - - if (getValueType().equals(DataType.INTEGER)) { - if (participant.getGender().equals(Gender.MALE)) { - args = new Object[] { getTargetParameter().getDescription(), integerMinValueMale, integerMaxValueMale }; - } - else if (participant.getGender().equals(Gender.FEMALE)) { - args = new Object[] { getTargetParameter().getDescription(), integerMinValueFemale, integerMaxValueFemale }; - } - } - else if (getValueType().equals(DataType.DECIMAL)) { - if (participant.getGender().equals(Gender.MALE)) { - args = new Object[] { getTargetParameter().getDescription(), decimalMinValueMale, decimalMaxValueMale }; - } - else if (participant.getGender().equals(Gender.FEMALE)) { - args = new Object[] { getTargetParameter().getDescription(), decimalMinValueFemale, decimalMaxValueFemale }; - } - } - - return args; - } - - private boolean checkIntegerParameterValue(Data paramData, Gender gender) { - boolean withinRange = true; - - Long minValue = gender.equals(Gender.MALE) ? integerMinValueMale : integerMinValueFemale; - Long maxValue = gender.equals(Gender.MALE) ? integerMaxValueMale : integerMaxValueFemale; - - if(minValue != null) { - if(minValue.compareTo((Long) paramData.getValue()) > 0) { - withinRange = false; - } - } - - if(withinRange) { - if(maxValue != null) { - if(maxValue.compareTo((Long) paramData.getValue()) < 0) { - withinRange = false; - } - } - } - - return withinRange; - } - - private boolean checkDecimalParameterValue(Data paramData, Gender gender) { - boolean withinRange = true; - - Double minValue = gender.equals(Gender.MALE) ? decimalMinValueMale : decimalMinValueFemale; - Double maxValue = gender.equals(Gender.MALE) ? decimalMaxValueMale : decimalMaxValueFemale; - - if(minValue != null) { - if(minValue.compareTo((Double) paramData.getValue()) > 0) { - withinRange = false; - } - } - - if(withinRange) { - if(maxValue != null) { - if(maxValue.compareTo((Double) paramData.getValue()) < 0) { - withinRange = false; - } - } - } - - return withinRange; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import java.util.Map; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.InstrumentInputParameterPanel; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Entity +@DiscriminatorValue("RangeCheck") +public class RangeCheck extends AbstractIntegrityCheck implements IntegrityCheck { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(RangeCheck.class); + + private Long integerMinValueMale; + + private Long integerMaxValueMale; + + private Long integerMinValueFemale; + + private Long integerMaxValueFemale; + + private Double decimalMinValueMale; + + private Double decimalMaxValueMale; + + private Double decimalMinValueFemale; + + private Double decimalMaxValueFemale; + + public RangeCheck() { + super(); + } + + public DataType getValueType() { + return getTargetParameter().getDataType(); + } + + public void setIntegerMinValueMale(Long value) { + integerMinValueMale = value; + } + + public void setIntegerMaxValueMale(Long value) { + integerMaxValueMale = value; + } + + public void setIntegerMinValueFemale(Long value) { + integerMinValueFemale = value; + } + + public void setIntegerMaxValueFemale(Long value) { + integerMaxValueFemale = value; + } + + public void setDecimalMinValueMale(Double value) { + decimalMinValueMale = value; + } + + public void setDecimalMaxValueMale(Double value) { + decimalMaxValueMale = value; + } + + public void setDecimalMinValueFemale(Double value) { + decimalMinValueFemale = value; + } + + public void setDecimalMaxValueFemale(Double value) { + decimalMaxValueFemale = value; + } + + // + // IntegrityCheck Methods + // + + @Override + public boolean checkParameterValue(Data paramData, InstrumentRunService runService, ActiveInstrumentRunService activeRunService) { + // Get the participant's gender (range is gender-dependent). + Gender gender = activeRunService.getParticipant().getGender(); + + if(getValueType().equals(DataType.INTEGER)) { + return checkIntegerParameterValue(paramData, gender); + } else if(getValueType().equals(DataType.DECIMAL)) { + return checkDecimalParameterValue(paramData, gender); + } + + return false; + } + + protected Object[] getDescriptionArgs(ActiveInstrumentRunService activeRunService) { + Object[] args = null; + + // For male participants, return the min/max values for males; for female participants, + // return the min/max values for females. + Participant participant = activeRunService.getParticipant(); + + if (getValueType().equals(DataType.INTEGER)) { + if (participant.getGender().equals(Gender.MALE)) { + args = new Object[] { getTargetParameter().getDescription(), integerMinValueMale, integerMaxValueMale }; + } + else if (participant.getGender().equals(Gender.FEMALE)) { + args = new Object[] { getTargetParameter().getDescription(), integerMinValueFemale, integerMaxValueFemale }; + } + } + else if (getValueType().equals(DataType.DECIMAL)) { + if (participant.getGender().equals(Gender.MALE)) { + args = new Object[] { getTargetParameter().getDescription(), decimalMinValueMale, decimalMaxValueMale }; + } + else if (participant.getGender().equals(Gender.FEMALE)) { + args = new Object[] { getTargetParameter().getDescription(), decimalMinValueFemale, decimalMaxValueFemale }; + } + } + + return args; + } + + private boolean checkIntegerParameterValue(Data paramData, Gender gender) { + boolean withinRange = true; + + Long minValue = gender.equals(Gender.MALE) ? integerMinValueMale : integerMinValueFemale; + Long maxValue = gender.equals(Gender.MALE) ? integerMaxValueMale : integerMaxValueFemale; + + if(minValue != null) { + if(minValue.compareTo((Long) paramData.getValue()) > 0) { + withinRange = false; + } + } + + if(withinRange) { + if(maxValue != null) { + if(maxValue.compareTo((Long) paramData.getValue()) < 0) { + withinRange = false; + } + } + } + + return withinRange; + } + + private boolean checkDecimalParameterValue(Data paramData, Gender gender) { + boolean withinRange = true; + + Double minValue = gender.equals(Gender.MALE) ? decimalMinValueMale : decimalMinValueFemale; + Double maxValue = gender.equals(Gender.MALE) ? decimalMaxValueMale : decimalMaxValueFemale; + + if(minValue != null) { + if(minValue.compareTo((Double) paramData.getValue()) > 0) { + withinRange = false; + } + } + + if(withinRange) { + if(maxValue != null) { + if(maxValue.compareTo((Double) paramData.getValue()) < 0) { + withinRange = false; + } + } + } + + return withinRange; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ContraIndicationAnswer.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ContraIndicationAnswer.java index 9ea089f3c..4470d50f6 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ContraIndicationAnswer.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ContraIndicationAnswer.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.core.domain.run; import javax.persistence.Entity; diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRun.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRun.java index d01c274af..92f173fa0 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRun.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRun.java @@ -1,170 +1,179 @@ -package org.obiba.onyx.jade.core.domain.run; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; - -@Entity -public class InstrumentRun extends AbstractEntity { - - private static final long serialVersionUID = -2756620040202577411L; - - @ManyToOne - @JoinColumn(name = "participant_interview_id") - private ParticipantInterview participantInterview; - - @OneToMany(mappedBy = "instrumentRun") - private List instrumentRunValues; - - @ManyToOne - @JoinColumn(name = "instrument_id") - private Instrument instrument; - - @ManyToOne - @JoinColumn(name = "user_id") - private User user; - - @Enumerated(EnumType.STRING) - private InstrumentRunStatus status; - - @Temporal(TemporalType.TIMESTAMP) - private Date timeStart; - - @Temporal(TemporalType.TIMESTAMP) - private Date timeEnd; - - @Enumerated(EnumType.STRING) - private InstrumentRunRefusalReason refusalReason; - - @Column(length = 2000) - private String refusalReasonComment; - - @ManyToOne - @JoinColumn(name = "contra_indication_id") - private ContraIndication contraIndication; - - private String otherContraIndication; - - public InstrumentRun() { - super(); - } - - public ParticipantInterview getParticipantInterview() { - return participantInterview; - } - - public void setParticipantInterview(ParticipantInterview participantInterview) { - this.participantInterview = participantInterview; - } - - public List getInstrumentRunValues() { - return instrumentRunValues != null ? instrumentRunValues : (instrumentRunValues = new ArrayList()); - } - - public void addInstrumentRunValue(InstrumentRunValue value) { - if(value != null) { - getInstrumentRunValues().add(value); - value.setInstrumentRun(this); - } - } - - public InstrumentRunValue getInstrumentRunValue(InstrumentParameter instrumentParameter) { - for(InstrumentRunValue runValue : getInstrumentRunValues()) { - if(runValue.getInstrumentParameter().getId().equals(instrumentParameter.getId())) return runValue; - } - return null; - } - - public Instrument getInstrument() { - return instrument; - } - - public void setInstrument(Instrument instrument) { - this.instrument = instrument; - } - - public InstrumentRunStatus getStatus() { - return status; - } - - public void setStatus(InstrumentRunStatus status) { - this.status = status; - } - - public Date getTimeStart() { - return timeStart; - } - - public void setTimeStart(Date timeStart) { - this.timeStart = timeStart; - } - - public Date getTimeEnd() { - return timeEnd; - } - - public void setTimeEnd(Date timeEnd) { - this.timeEnd = timeEnd; - } - - public InstrumentRunRefusalReason getRefusalReason() { - return refusalReason; - } - - public boolean isRefused() { - return refusalReason != null; - } - - public void setRefusalReason(InstrumentRunRefusalReason refusalReason) { - this.refusalReason = refusalReason; - } - - public String getRefusalReasonComment() { - return refusalReasonComment; - } - - public void setRefusalReasonComment(String refusalReasonComment) { - this.refusalReasonComment = refusalReasonComment; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public ContraIndication getContraIndication() { - return contraIndication; - } - - public void setContraIndication(ContraIndication contraIndication) { - this.contraIndication = contraIndication; - } - - public String getOtherContraIndication() { - return otherContraIndication; - } - - public void setOtherContraIndication(String otherContraIndication) { - this.otherContraIndication = otherContraIndication; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; + +@Entity +public class InstrumentRun extends AbstractEntity { + + private static final long serialVersionUID = -2756620040202577411L; + + @ManyToOne + @JoinColumn(name = "participant_interview_id") + private ParticipantInterview participantInterview; + + @OneToMany(mappedBy = "instrumentRun") + private List instrumentRunValues; + + @ManyToOne + @JoinColumn(name = "instrument_id") + private Instrument instrument; + + @ManyToOne + @JoinColumn(name = "user_id") + private User user; + + @Enumerated(EnumType.STRING) + private InstrumentRunStatus status; + + @Temporal(TemporalType.TIMESTAMP) + private Date timeStart; + + @Temporal(TemporalType.TIMESTAMP) + private Date timeEnd; + + @Enumerated(EnumType.STRING) + private InstrumentRunRefusalReason refusalReason; + + @Column(length = 2000) + private String refusalReasonComment; + + @ManyToOne + @JoinColumn(name = "contra_indication_id") + private ContraIndication contraIndication; + + private String otherContraIndication; + + public InstrumentRun() { + super(); + } + + public ParticipantInterview getParticipantInterview() { + return participantInterview; + } + + public void setParticipantInterview(ParticipantInterview participantInterview) { + this.participantInterview = participantInterview; + } + + public List getInstrumentRunValues() { + return instrumentRunValues != null ? instrumentRunValues : (instrumentRunValues = new ArrayList()); + } + + public void addInstrumentRunValue(InstrumentRunValue value) { + if(value != null) { + getInstrumentRunValues().add(value); + value.setInstrumentRun(this); + } + } + + public InstrumentRunValue getInstrumentRunValue(InstrumentParameter instrumentParameter) { + for(InstrumentRunValue runValue : getInstrumentRunValues()) { + if(runValue.getInstrumentParameter().getId().equals(instrumentParameter.getId())) return runValue; + } + return null; + } + + public Instrument getInstrument() { + return instrument; + } + + public void setInstrument(Instrument instrument) { + this.instrument = instrument; + } + + public InstrumentRunStatus getStatus() { + return status; + } + + public void setStatus(InstrumentRunStatus status) { + this.status = status; + } + + public Date getTimeStart() { + return timeStart; + } + + public void setTimeStart(Date timeStart) { + this.timeStart = timeStart; + } + + public Date getTimeEnd() { + return timeEnd; + } + + public void setTimeEnd(Date timeEnd) { + this.timeEnd = timeEnd; + } + + public InstrumentRunRefusalReason getRefusalReason() { + return refusalReason; + } + + public boolean isRefused() { + return refusalReason != null; + } + + public void setRefusalReason(InstrumentRunRefusalReason refusalReason) { + this.refusalReason = refusalReason; + } + + public String getRefusalReasonComment() { + return refusalReasonComment; + } + + public void setRefusalReasonComment(String refusalReasonComment) { + this.refusalReasonComment = refusalReasonComment; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public ContraIndication getContraIndication() { + return contraIndication; + } + + public void setContraIndication(ContraIndication contraIndication) { + this.contraIndication = contraIndication; + } + + public String getOtherContraIndication() { + return otherContraIndication; + } + + public void setOtherContraIndication(String otherContraIndication) { + this.otherContraIndication = otherContraIndication; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunRefusalReason.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunRefusalReason.java index 4a04ce4d9..37201d6a4 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunRefusalReason.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunRefusalReason.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.run; - -public enum InstrumentRunRefusalReason { - DEFECTIVE_INSTRUMENT, PARTICIPANT_REFUSAL, MEDICAL_REASON, OTHER -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +public enum InstrumentRunRefusalReason { + DEFECTIVE_INSTRUMENT, PARTICIPANT_REFUSAL, MEDICAL_REASON, OTHER +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunStatus.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunStatus.java index 37ef218d8..9df93420f 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunStatus.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunStatus.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.run; - -public enum InstrumentRunStatus { - IN_PROGRESS, IN_ERROR, COMPLETED, CANCELED, CONTRA_INDICATED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +public enum InstrumentRunStatus { + IN_PROGRESS, IN_ERROR, COMPLETED, CANCELED, CONTRA_INDICATED +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunValue.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunValue.java index 3c183d176..f25375df7 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunValue.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/InstrumentRunValue.java @@ -1,171 +1,180 @@ -package org.obiba.onyx.jade.core.domain.run; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -@Entity -public class InstrumentRunValue extends AbstractEntity { - - private static final long serialVersionUID = 267079755213810737L; - - @ManyToOne - @JoinColumn(name = "instrument_run_id") - private InstrumentRun instrumentRun; - - @ManyToOne - @JoinColumn(name = "instrument_parameter_id") - private InstrumentParameter instrumentParameter; - - private Boolean booleanValue; - - @Temporal(TemporalType.TIMESTAMP) - private Date dateValue; - - private Double decimalValue; - - private Long integerValue; - - @Column(length = 2000) - private String textValue; - - @Lob - @Column(length = Integer.MAX_VALUE) - private byte[] dataValue; - - @Enumerated(EnumType.STRING) - private InstrumentParameterCaptureMethod captureMethod; - - @Enumerated(EnumType.STRING) - private ValueIntegrity valueIntegrity; - - public InstrumentRunValue() { - } - - public InstrumentRun getInstrumentRun() { - return instrumentRun; - } - - public void setInstrumentRun(InstrumentRun instrumentRun) { - this.instrumentRun = instrumentRun; - } - - public InstrumentParameter getInstrumentParameter() { - return instrumentParameter; - } - - public void setInstrumentParameter(InstrumentParameter instrumentParameter) { - this.instrumentParameter = instrumentParameter; - } - - public InstrumentParameterCaptureMethod getCaptureMethod() { - return captureMethod; - } - - public void setCaptureMethod(InstrumentParameterCaptureMethod captureMethod) { - this.captureMethod = captureMethod; - } - - public ValueIntegrity getValueIntegrity() { - return valueIntegrity; - } - - public void setValueIntegrity(ValueIntegrity valueIntegrity) { - this.valueIntegrity = valueIntegrity; - } - - public DataType getDataType() { - return instrumentParameter.getDataType(); - } - - public void setData(Data data) { - - if(data != null) { - if(data.getType() == getDataType()) { - - switch(getDataType()) { - case BOOLEAN: - booleanValue = data.getValue(); - break; - - case DATE: - dateValue = data.getValue(); - break; - - case DECIMAL: - decimalValue = data.getValue(); - break; - - case INTEGER: - integerValue = data.getValue(); - break; - - case TEXT: - textValue = data.getValue(); - break; - - case DATA: - dataValue = data.getValue(); - break; - } - } else { - throw new IllegalArgumentException("DataType " + getDataType() + " expected, " + data.getType() + " received."); - } - } - } - - @Transient - @SuppressWarnings("unchecked") - public T getValue() { - return (T)getData().getValue(); - } - - public Data getData() { - Data data = null; - - switch(getDataType()) { - case BOOLEAN: - data = DataBuilder.buildBoolean(booleanValue); - break; - - case DATE: - data = DataBuilder.buildDate(dateValue); - break; - - case DECIMAL: - data = DataBuilder.buildDecimal(decimalValue); - break; - - case INTEGER: - data = DataBuilder.buildInteger(integerValue); - break; - - case TEXT: - data = DataBuilder.buildText(textValue); - break; - - case DATA: - data = new Data(getDataType(), dataValue); - break; - } - - return data; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.Lob; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +@Entity +public class InstrumentRunValue extends AbstractEntity { + + private static final long serialVersionUID = 267079755213810737L; + + @ManyToOne + @JoinColumn(name = "instrument_run_id") + private InstrumentRun instrumentRun; + + @ManyToOne + @JoinColumn(name = "instrument_parameter_id") + private InstrumentParameter instrumentParameter; + + private Boolean booleanValue; + + @Temporal(TemporalType.TIMESTAMP) + private Date dateValue; + + private Double decimalValue; + + private Long integerValue; + + @Column(length = 2000) + private String textValue; + + @Lob + @Column(length = Integer.MAX_VALUE) + private byte[] dataValue; + + @Enumerated(EnumType.STRING) + private InstrumentParameterCaptureMethod captureMethod; + + @Enumerated(EnumType.STRING) + private ValueIntegrity valueIntegrity; + + public InstrumentRunValue() { + } + + public InstrumentRun getInstrumentRun() { + return instrumentRun; + } + + public void setInstrumentRun(InstrumentRun instrumentRun) { + this.instrumentRun = instrumentRun; + } + + public InstrumentParameter getInstrumentParameter() { + return instrumentParameter; + } + + public void setInstrumentParameter(InstrumentParameter instrumentParameter) { + this.instrumentParameter = instrumentParameter; + } + + public InstrumentParameterCaptureMethod getCaptureMethod() { + return captureMethod; + } + + public void setCaptureMethod(InstrumentParameterCaptureMethod captureMethod) { + this.captureMethod = captureMethod; + } + + public ValueIntegrity getValueIntegrity() { + return valueIntegrity; + } + + public void setValueIntegrity(ValueIntegrity valueIntegrity) { + this.valueIntegrity = valueIntegrity; + } + + public DataType getDataType() { + return instrumentParameter.getDataType(); + } + + public void setData(Data data) { + + if(data != null) { + if(data.getType() == getDataType()) { + + switch(getDataType()) { + case BOOLEAN: + booleanValue = data.getValue(); + break; + + case DATE: + dateValue = data.getValue(); + break; + + case DECIMAL: + decimalValue = data.getValue(); + break; + + case INTEGER: + integerValue = data.getValue(); + break; + + case TEXT: + textValue = data.getValue(); + break; + + case DATA: + dataValue = data.getValue(); + break; + } + } else { + throw new IllegalArgumentException("DataType " + getDataType() + " expected, " + data.getType() + " received."); + } + } + } + + @Transient + @SuppressWarnings("unchecked") + public T getValue() { + return (T)getData().getValue(); + } + + public Data getData() { + Data data = null; + + switch(getDataType()) { + case BOOLEAN: + data = DataBuilder.buildBoolean(booleanValue); + break; + + case DATE: + data = DataBuilder.buildDate(dateValue); + break; + + case DECIMAL: + data = DataBuilder.buildDecimal(decimalValue); + break; + + case INTEGER: + data = DataBuilder.buildInteger(integerValue); + break; + + case TEXT: + data = DataBuilder.buildText(textValue); + break; + + case DATA: + data = new Data(getDataType(), dataValue); + break; + } + + return data; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ParticipantInterview.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ParticipantInterview.java index e25a49644..d8a02bd29 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ParticipantInterview.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ParticipantInterview.java @@ -1,51 +1,60 @@ -package org.obiba.onyx.jade.core.domain.run; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.participant.Participant; - -@Entity -public class ParticipantInterview extends AbstractEntity { - - private static final long serialVersionUID = -6980920538268971339L; - - @OneToOne - @JoinColumn(name = "participant_id") - private Participant participant; - - @OneToMany(mappedBy = "participantInterview") - private List instrumentRuns; - - public ParticipantInterview() { - } - - public ParticipantInterview(Participant participant) { - this.participant = participant; - } - - public Participant getParticipant() { - return participant; - } - - public void setParticipant(Participant participant) { - this.participant = participant; - } - - public List getInstrumentRuns() { - return instrumentRuns != null ? instrumentRuns : (instrumentRuns = new ArrayList()); - } - - public void addInstrumentRun(InstrumentRun instrumentRun) { - if (instrumentRun != null) { - getInstrumentRuns().add(instrumentRun); - instrumentRun.setParticipantInterview(this); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.participant.Participant; + +@Entity +public class ParticipantInterview extends AbstractEntity { + + private static final long serialVersionUID = -6980920538268971339L; + + @OneToOne + @JoinColumn(name = "participant_id") + private Participant participant; + + @OneToMany(mappedBy = "participantInterview") + private List instrumentRuns; + + public ParticipantInterview() { + } + + public ParticipantInterview(Participant participant) { + this.participant = participant; + } + + public Participant getParticipant() { + return participant; + } + + public void setParticipant(Participant participant) { + this.participant = participant; + } + + public List getInstrumentRuns() { + return instrumentRuns != null ? instrumentRuns : (instrumentRuns = new ArrayList()); + } + + public void addInstrumentRun(InstrumentRun instrumentRun) { + if (instrumentRun != null) { + getInstrumentRuns().add(instrumentRun); + instrumentRun.setParticipantInterview(this); + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ValueIntegrity.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ValueIntegrity.java index b9a527226..4581d1215 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ValueIntegrity.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/domain/run/ValueIntegrity.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.jade.core.domain.run; - -public enum ValueIntegrity { - VALID, INVALID, UNCHECKED -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.run; + +public enum ValueIntegrity { + VALID, INVALID, UNCHECKED +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/ActiveInstrumentRunService.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/ActiveInstrumentRunService.java index b1d8490e2..e3553ddfc 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/ActiveInstrumentRunService.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/ActiveInstrumentRunService.java @@ -1,136 +1,145 @@ -package org.obiba.onyx.jade.core.service; - -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; - -public interface ActiveInstrumentRunService { - - /** - * Set the {@link ContraIndication} associated the current {@link InstrumentRun}. - * @param contraIndication - */ - public void setContraIndication(ContraIndication contraIndication); - - /** - * Get the {@link ContraIndication} associated the current {@link InstrumentRun}. - */ - public ContraIndication getContraIndication(); - - /** - * Set the other contra-indication text to the current {@link InstrumentRun}. - * @param otherContraIndication - */ - public void setOtherContraIndication(String otherContraIndication); - - /** - * Get the other contra-indication text for the current {@link InstrumentRun}. - * @return - */ - public String getOtherContraIndication(); - - /** - * Set the {@link InstrumentRunStatus} to the current {@link InstrumentRun}. - * @param status - */ - public void setInstrumentRunStatus(InstrumentRunStatus status); - - /** - * Get the {@link InstrumentRunStatus} for the current {@link InstrumentRun}. - * @return - */ - public InstrumentRunStatus getInstrumentRunStatus(); - - /** - * Set the current {@link InstrumentType}. - * @return - */ - public void setInstrumentType(InstrumentType instrumentType); - - /** - * Get the current {@link InstrumentType}. - * @return - */ - public InstrumentType getInstrumentType(); - - /** - * Get the current {@link InstrumentRun}. - * @return - */ - public InstrumentRun getInstrumentRun(); - - /** - * Get the {@link Instrument} associated to the current {@link InstrumentRun}. - * @return - */ - public Instrument getInstrument(); - - /** - * Create the current {@link InstrumentRun} without persisting it. - * @param participant - * @param instrument - * @return - */ - public InstrumentRun start(Participant participant, Instrument instrument); - - /** - * Get the associated {@link Participant} - * @return - */ - public Participant getParticipant(); - - /** - * Set the end date to the current {@link InstrumentRun} with its current status. - */ - public void end(); - - /** - * Make sure there is no current {@link InstrumentRun}. - */ - public void reset(); - - /** - * Persist current {@link InstrumentRun}. - * @param currentRun - */ - public void update(InstrumentRun currentRun); - - /** - * Persist {@link InstrumentRunValue} current {@link InstrumentRun}. - * @param currentRunValue - */ - public void update(InstrumentRunValue currentRunValue); - - /** - * Compute the output parameters values of {@link InstrumentComputedOutputParameter} for the current - * {@link InstrumentRun}. - */ - public void computeOutputParameters(); - - /** - * Get (or create it if needed) the {@link InstrumentRunValue} for the named {@link InstrumentOutputParameter} of the - * current {@link InstrumentRun}. - * @param parameterName - * @return null if current instrument run is null - * @throws IllegalArgumentException if parameter name is not applicable to the {@link Instrument} - */ - public InstrumentRunValue getOutputInstrumentRunValue(String parameterName); - - /** - * Get (or create it if needed) the {@link InstrumentRunValue} for the named {@link InstrumentInputParameter} of the - * current {@link InstrumentRun}. - * @param parameterName - * @return null if current instrument run is null - * @throws IllegalArgumentException if parameter name is not applicable to the {@link Instrument} - */ - public InstrumentRunValue getInputInstrumentRunValue(String parameterName); - - public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; + +public interface ActiveInstrumentRunService { + + /** + * Set the {@link ContraIndication} associated the current {@link InstrumentRun}. + * @param contraIndication + */ + public void setContraIndication(ContraIndication contraIndication); + + /** + * Get the {@link ContraIndication} associated the current {@link InstrumentRun}. + */ + public ContraIndication getContraIndication(); + + /** + * Set the other contra-indication text to the current {@link InstrumentRun}. + * @param otherContraIndication + */ + public void setOtherContraIndication(String otherContraIndication); + + /** + * Get the other contra-indication text for the current {@link InstrumentRun}. + * @return + */ + public String getOtherContraIndication(); + + /** + * Set the {@link InstrumentRunStatus} to the current {@link InstrumentRun}. + * @param status + */ + public void setInstrumentRunStatus(InstrumentRunStatus status); + + /** + * Get the {@link InstrumentRunStatus} for the current {@link InstrumentRun}. + * @return + */ + public InstrumentRunStatus getInstrumentRunStatus(); + + /** + * Set the current {@link InstrumentType}. + * @return + */ + public void setInstrumentType(InstrumentType instrumentType); + + /** + * Get the current {@link InstrumentType}. + * @return + */ + public InstrumentType getInstrumentType(); + + /** + * Get the current {@link InstrumentRun}. + * @return + */ + public InstrumentRun getInstrumentRun(); + + /** + * Get the {@link Instrument} associated to the current {@link InstrumentRun}. + * @return + */ + public Instrument getInstrument(); + + /** + * Create the current {@link InstrumentRun} without persisting it. + * @param participant + * @param instrument + * @return + */ + public InstrumentRun start(Participant participant, Instrument instrument); + + /** + * Get the associated {@link Participant} + * @return + */ + public Participant getParticipant(); + + /** + * Set the end date to the current {@link InstrumentRun} with its current status. + */ + public void end(); + + /** + * Make sure there is no current {@link InstrumentRun}. + */ + public void reset(); + + /** + * Persist current {@link InstrumentRun}. + * @param currentRun + */ + public void update(InstrumentRun currentRun); + + /** + * Persist {@link InstrumentRunValue} current {@link InstrumentRun}. + * @param currentRunValue + */ + public void update(InstrumentRunValue currentRunValue); + + /** + * Compute the output parameters values of {@link InstrumentComputedOutputParameter} for the current + * {@link InstrumentRun}. + */ + public void computeOutputParameters(); + + /** + * Get (or create it if needed) the {@link InstrumentRunValue} for the named {@link InstrumentOutputParameter} of the + * current {@link InstrumentRun}. + * @param parameterName + * @return null if current instrument run is null + * @throws IllegalArgumentException if parameter name is not applicable to the {@link Instrument} + */ + public InstrumentRunValue getOutputInstrumentRunValue(String parameterName); + + /** + * Get (or create it if needed) the {@link InstrumentRunValue} for the named {@link InstrumentInputParameter} of the + * current {@link InstrumentRun}. + * @param parameterName + * @return null if current instrument run is null + * @throws IllegalArgumentException if parameter name is not applicable to the {@link Instrument} + */ + public InstrumentRunValue getInputInstrumentRunValue(String parameterName); + + public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputDataSourceVisitor.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputDataSourceVisitor.java index b3f2893cd..bba1fe8c9 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputDataSourceVisitor.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputDataSourceVisitor.java @@ -1,11 +1,20 @@ -package org.obiba.onyx.jade.core.service; - -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.util.data.Data; - -public interface InputDataSourceVisitor extends InputSourceVisitor { - - public Data getData(Participant participant, InstrumentInputParameter parameter); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.util.data.Data; + +public interface InputDataSourceVisitor extends InputSourceVisitor { + + public Data getData(Participant participant, InstrumentInputParameter parameter); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputSourceVisitor.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputSourceVisitor.java index e9ed7a36f..da24d53f4 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputSourceVisitor.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InputSourceVisitor.java @@ -1,21 +1,30 @@ -package org.obiba.onyx.jade.core.service; - -import org.obiba.onyx.jade.core.domain.instrument.FixedSource; -import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; -import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; - -public interface InputSourceVisitor { - - public void visit(FixedSource source); - - public void visit(OperatorSource source); - - public void visit(OutputParameterSource source); - - public void visit(MultipleOutputParameterSource source); - - public void visit(ParticipantPropertySource source); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import org.obiba.onyx.jade.core.domain.instrument.FixedSource; +import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; +import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; + +public interface InputSourceVisitor { + + public void visit(FixedSource source); + + public void visit(OperatorSource source); + + public void visit(OutputParameterSource source); + + public void visit(MultipleOutputParameterSource source); + + public void visit(ParticipantPropertySource source); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentDescriptorService.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentDescriptorService.java index 2f19f5527..df655af2c 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentDescriptorService.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentDescriptorService.java @@ -1,22 +1,31 @@ -package org.obiba.onyx.jade.core.service; - -public interface InstrumentDescriptorService { - - /** - * Get the codebase of a specific instrument using its unique barcode. - * - * @param instrumentBarCode - * @return - */ - public String getCodeBase(String instrumentBarCode); - - /** - * Stores the codebase (base path used in Jnlp) for a specific instrument. The barcode is used as unique identifier - * for the instrument. - * - * @param instrumentBarCode - * @param codeBase - */ - public void setCodeBase(String instrumentBarCode, String codeBase); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +public interface InstrumentDescriptorService { + + /** + * Get the codebase of a specific instrument using its unique barcode. + * + * @param instrumentBarCode + * @return + */ + public String getCodeBase(String instrumentBarCode); + + /** + * Stores the codebase (base path used in Jnlp) for a specific instrument. The barcode is used as unique identifier + * for the instrument. + * + * @param instrumentBarCode + * @param codeBase + */ + public void setCodeBase(String instrumentBarCode, String codeBase); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentRunService.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentRunService.java index 166c6a420..69e5cc576 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentRunService.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentRunService.java @@ -1,53 +1,62 @@ -package org.obiba.onyx.jade.core.service; - -import java.util.List; - -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; - -public interface InstrumentRunService { - - /** - * Get the completed instrument runs for given participant. - * @param participant - * @param instrument - * @return - */ - public List getCompletedInstrumentRuns(Participant participant, Instrument instrument); - - /** - * Get the last instrument whatever is its status for participant and instrument type. - * @param participant - * @param instrumentType - * @return - */ - public InstrumentRun getLastInstrumentRun(Participant participant, InstrumentType instrumentType); - - /** - * Get the last completed run for participant and instrument type. - * @param participant - * @param instrumentType - * @return - */ - public InstrumentRun getLastCompletedInstrumentRun(Participant participant, InstrumentType instrumentType); - - /** - * Find the value from the last completed run of the instrument of the given type for given participant. - * @param participant - * @param instrumentType - * @param parameterName - * @return - */ - public InstrumentRunValue findInstrumentRunValue(Participant participant, InstrumentType instrumentType, String parameterName); - - /** - * Update the {@link InstrumentRun} with the given {@link InstrumentRunStatus}. - * @param run - * @param status - */ - public void setInstrumentRunStatus(InstrumentRun run, InstrumentRunStatus status); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import java.util.List; + +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; + +public interface InstrumentRunService { + + /** + * Get the completed instrument runs for given participant. + * @param participant + * @param instrument + * @return + */ + public List getCompletedInstrumentRuns(Participant participant, Instrument instrument); + + /** + * Get the last instrument whatever is its status for participant and instrument type. + * @param participant + * @param instrumentType + * @return + */ + public InstrumentRun getLastInstrumentRun(Participant participant, InstrumentType instrumentType); + + /** + * Get the last completed run for participant and instrument type. + * @param participant + * @param instrumentType + * @return + */ + public InstrumentRun getLastCompletedInstrumentRun(Participant participant, InstrumentType instrumentType); + + /** + * Find the value from the last completed run of the instrument of the given type for given participant. + * @param participant + * @param instrumentType + * @param parameterName + * @return + */ + public InstrumentRunValue findInstrumentRunValue(Participant participant, InstrumentType instrumentType, String parameterName); + + /** + * Update the {@link InstrumentRun} with the given {@link InstrumentRunStatus}. + * @param run + * @param status + */ + public void setInstrumentRunStatus(InstrumentRun run, InstrumentRunStatus status); +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentService.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentService.java index 1fc616274..303688aef 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentService.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/InstrumentService.java @@ -1,84 +1,93 @@ -package org.obiba.onyx.jade.core.service; - -import java.util.List; - -import org.obiba.onyx.jade.core.domain.instrument.InputSource; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; - -public interface InstrumentService { - - /** - * Create an instrument type. - * @param name - * @param description - * @return - */ - public InstrumentType createInstrumentType(String name, String description); - - /** - * Get the instrument type by its name. - * @param name - * @return null if not found - */ - public InstrumentType getInstrumentType(String name); - - /** - * Add an depending instrument type to given instrument type. - * @param type - * @param dependency - */ - public void addInstrumentTypeDependency(InstrumentType type, InstrumentType dependency); - - /** - * Get the instruments for the given instrument type name. - * @param typeName - * @return - */ - public List getInstruments(String typeName); - - /** - * Get the instruments for given instrument type. - * @param instrumentType - * @return - */ - public List getInstruments(InstrumentType instrumentType); - - /** - * Get the active instruments for given instrument type. - * @param instrumentType - * @return - */ - public List getActiveInstruments(InstrumentType instrumentType); - - /** - * Add an instrument to an instrument type. - * @param instrumentType - * @param instrument - */ - public void addInstrument(InstrumentType instrumentType, Instrument instrument); - - /** - * Shall we expect data from a remote instrument application ? - * @param instrument - * @return - */ - public boolean isInteractiveInstrument(Instrument instrument); - - /** - * Get the {@link InstrumentInputParameter}s that have a {@link InputSource} read only (or not). - * @param instrument - * @param readOnlySource - * @return - */ - public List getInstrumentInputParameter(Instrument instrument, boolean readOnlySource); - - /** - * Count the {@link InstrumentInputParameter}s that have a {@link InputSource} read only (or not). - * @param instrument - * @param readOnlySource - * @return - */ - public int countInstrumentInputParameter(Instrument instrument, boolean readOnlySource); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import java.util.List; + +import org.obiba.onyx.jade.core.domain.instrument.InputSource; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; + +public interface InstrumentService { + + /** + * Create an instrument type. + * @param name + * @param description + * @return + */ + public InstrumentType createInstrumentType(String name, String description); + + /** + * Get the instrument type by its name. + * @param name + * @return null if not found + */ + public InstrumentType getInstrumentType(String name); + + /** + * Add an depending instrument type to given instrument type. + * @param type + * @param dependency + */ + public void addInstrumentTypeDependency(InstrumentType type, InstrumentType dependency); + + /** + * Get the instruments for the given instrument type name. + * @param typeName + * @return + */ + public List getInstruments(String typeName); + + /** + * Get the instruments for given instrument type. + * @param instrumentType + * @return + */ + public List getInstruments(InstrumentType instrumentType); + + /** + * Get the active instruments for given instrument type. + * @param instrumentType + * @return + */ + public List getActiveInstruments(InstrumentType instrumentType); + + /** + * Add an instrument to an instrument type. + * @param instrumentType + * @param instrument + */ + public void addInstrument(InstrumentType instrumentType, Instrument instrument); + + /** + * Shall we expect data from a remote instrument application ? + * @param instrument + * @return + */ + public boolean isInteractiveInstrument(Instrument instrument); + + /** + * Get the {@link InstrumentInputParameter}s that have a {@link InputSource} read only (or not). + * @param instrument + * @param readOnlySource + * @return + */ + public List getInstrumentInputParameter(Instrument instrument, boolean readOnlySource); + + /** + * Count the {@link InstrumentInputParameter}s that have a {@link InputSource} read only (or not). + * @param instrument + * @param readOnlySource + * @return + */ + public int countInstrumentInputParameter(Instrument instrument, boolean readOnlySource); +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultActiveInstrumentRunServiceImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultActiveInstrumentRunServiceImpl.java index debb925cc..1782cad57 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultActiveInstrumentRunServiceImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultActiveInstrumentRunServiceImpl.java @@ -1,313 +1,322 @@ -package org.obiba.onyx.jade.core.service.impl; - -import java.io.Serializable; -import java.util.Date; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameterAlgorithm; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class DefaultActiveInstrumentRunServiceImpl extends PersistenceManagerAwareService implements ActiveInstrumentRunService { - - private UserSessionService userSessionService; - - private Serializable currentRunId = null; - - private Serializable instrumentTypeId = null; - - public InstrumentRun start(Participant participant, Instrument instrument) { - - if(currentRunId != null) { - InstrumentRun currentRun = getInstrumentRun(); - if(currentRun.getStatus().equals(InstrumentRunStatus.IN_PROGRESS)) { - cancel(); - } - currentRun = null; - } - - ParticipantInterview participantInterviewTemplate = new ParticipantInterview(); - participantInterviewTemplate.setParticipant(participant); - ParticipantInterview participantInterview = getPersistenceManager().matchOne(participantInterviewTemplate); - if(participantInterview == null) { - participantInterview = getPersistenceManager().save(participantInterviewTemplate); - } - - InstrumentRun currentRun = new InstrumentRun(); - currentRun.setParticipantInterview(participantInterview); - currentRun.setInstrument(instrument); - currentRun.setStatus(InstrumentRunStatus.IN_PROGRESS); - currentRun.setTimeStart(new Date()); - currentRun.setUser(userSessionService.getUser()); - getPersistenceManager().save(currentRun); - currentRunId = currentRun.getId(); - - return currentRun; - } - - public void cancel() { - end(InstrumentRunStatus.CANCELED); - } - - public void fail() { - end(InstrumentRunStatus.IN_ERROR); - } - - public void complete() { - end(InstrumentRunStatus.COMPLETED); - } - - public void end() { - if(currentRunId == null) return; - - InstrumentRun currentRun = getInstrumentRun(); - currentRun.setTimeEnd(new Date()); - - getPersistenceManager().save(currentRun); - } - - private void end(InstrumentRunStatus status) { - if(currentRunId == null) return; - - InstrumentRun currentRun = getInstrumentRun(); - currentRun.setTimeEnd(new Date()); - currentRun.setStatus(status); - - getPersistenceManager().save(currentRun); - } - - public InstrumentRun getInstrumentRun() { - if(currentRunId == null) return null; - - return getPersistenceManager().get(InstrumentRun.class, currentRunId); - } - - public Participant getParticipant() { - if(currentRunId == null) return null; - - return getInstrumentRun().getParticipantInterview().getParticipant(); - } - - public void reset() { - currentRunId = null; - instrumentTypeId = null; - } - - public void update(InstrumentRun currentRun) { - if(currentRunId == null) return; - if(currentRun == null) throw new IllegalArgumentException("Current instrument run cannot be null"); - if(!currentRunId.equals(currentRun.getId())) throw new IllegalArgumentException("Unexpected given current instrument run"); - - getPersistenceManager().save(currentRun); - } - - public void update(InstrumentRunValue currentRunValue) { - if(currentRunId == null) return; - if(currentRunValue.getInstrumentRun() == null) throw new IllegalArgumentException("Current instrument run cannot be null"); - if(!currentRunId.equals(currentRunValue.getInstrumentRun().getId())) throw new IllegalArgumentException("Unexpected given current instrument run"); - - getPersistenceManager().save(currentRunValue); - } - - public void computeOutputParameters() { - if(currentRunId == null) return; - - InstrumentRun currentRun = getInstrumentRun(); - - InstrumentOutputParameter template = new InstrumentOutputParameter(); - template.setInstrument(currentRun.getInstrument()); - template.setCaptureMethod(InstrumentParameterCaptureMethod.COMPUTED); - - // TODO quick and dirty implementation, to be checked - for(InstrumentOutputParameter param : getPersistenceManager().match(template)) { - InstrumentComputedOutputParameter computedParam = (InstrumentComputedOutputParameter) param; - if(computedParam.getAlgorithm().equals(InstrumentOutputParameterAlgorithm.AVERAGE)) { - InstrumentRunValue computedRunValue = getOutputInstrumentRunValue(computedParam.getName()); - - double sum = 0; - int count = 0; - for(InstrumentOutputParameter p : computedParam.getInstrumentOutputParameters()) { - count++; - InstrumentRunValue runValue = currentRun.getInstrumentRunValue(p); - if(runValue.getDataType().equals(DataType.DECIMAL)) { - Double value = runValue.getValue(); - sum += value; - } else if(runValue.getDataType().equals(DataType.INTEGER)) { - Long value = runValue.getValue(); - sum += value.doubleValue(); - } - } - double avg = sum / count; - - Serializable avgValue = null; - if(computedRunValue.getDataType().equals(DataType.DECIMAL)) { - long avgInt = Math.round(avg * 100); - avgValue = (double) avgInt / 100; - } else if(computedRunValue.getDataType().equals(DataType.INTEGER)) { - avgValue = Math.round(avg); - } - - if(avgValue != null) { - computedRunValue.setData(new Data(computedRunValue.getDataType(), avgValue)); - } - - getPersistenceManager().save(computedRunValue); - } - } - } - - public InstrumentRunValue getOutputInstrumentRunValue(String parameterName) { - if(currentRunId == null) return null; - - InstrumentRun currentRun = getInstrumentRun(); - - InstrumentOutputParameter instrumentOutputParameter = new InstrumentOutputParameter(); - instrumentOutputParameter.setName(parameterName); - instrumentOutputParameter.setInstrument(currentRun.getInstrument()); - instrumentOutputParameter = getPersistenceManager().matchOne(instrumentOutputParameter); - - if(instrumentOutputParameter == null) { - throw new IllegalArgumentException("No such output parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); - } - - InstrumentRunValue valueTemplate = new InstrumentRunValue(); - valueTemplate.setInstrumentParameter(instrumentOutputParameter); - valueTemplate.setInstrumentRun(currentRun); - - InstrumentRunValue outputParameterValue = getPersistenceManager().matchOne(valueTemplate); - - if(outputParameterValue == null) { - valueTemplate.setCaptureMethod(instrumentOutputParameter.getCaptureMethod()); - outputParameterValue = getPersistenceManager().save(valueTemplate); - } - - return outputParameterValue; - } - - public InstrumentRunValue getInputInstrumentRunValue(String parameterName) { - if(currentRunId == null) return null; - - InstrumentRun currentRun = getInstrumentRun(); - - InstrumentInputParameter instrumentInputParameter = new InstrumentInputParameter(); - instrumentInputParameter.setName(parameterName); - instrumentInputParameter.setInstrument(currentRun.getInstrument()); - instrumentInputParameter = getPersistenceManager().matchOne(instrumentInputParameter); - - if(instrumentInputParameter == null) { - throw new IllegalArgumentException("No such input parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); - } - - InstrumentRunValue valueTemplate = new InstrumentRunValue(); - valueTemplate.setInstrumentParameter(instrumentInputParameter); - valueTemplate.setInstrumentRun(currentRun); - - InstrumentRunValue inputParameterValue = getPersistenceManager().matchOne(valueTemplate); - - if(inputParameterValue == null) { - valueTemplate.setCaptureMethod(instrumentInputParameter.getCaptureMethod()); - inputParameterValue = getPersistenceManager().save(valueTemplate); - } - - return inputParameterValue; - } - - public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName) { - if(currentRunId == null) return null; - - InstrumentRun currentRun = getInstrumentRun(); - - InterpretativeParameter instrumentInterpretativeParameter = new InterpretativeParameter(); - instrumentInterpretativeParameter.setName(parameterName); - instrumentInterpretativeParameter.setInstrument(currentRun.getInstrument()); - instrumentInterpretativeParameter = getPersistenceManager().matchOne(instrumentInterpretativeParameter); - - if(instrumentInterpretativeParameter == null) { - throw new IllegalArgumentException("No such interpretative parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); - } - - InstrumentRunValue valueTemplate = new InstrumentRunValue(); - valueTemplate.setInstrumentParameter(instrumentInterpretativeParameter); - valueTemplate.setInstrumentRun(currentRun); - - InstrumentRunValue interpretativeParameterValue = getPersistenceManager().matchOne(valueTemplate); - - if(interpretativeParameterValue == null) { - valueTemplate.setCaptureMethod(instrumentInterpretativeParameter.getCaptureMethod()); - interpretativeParameterValue = getPersistenceManager().save(valueTemplate); - } - - return interpretativeParameterValue; - } - - public InstrumentType getInstrumentType() { - return getPersistenceManager().get(InstrumentType.class, instrumentTypeId); - } - - public void setInstrumentType(InstrumentType instrumentType) { - this.instrumentTypeId = instrumentType.getId(); - } - - public Instrument getInstrument() { - return getInstrumentRun().getInstrument(); - } - - public ContraIndication getContraIndication() { - return getInstrumentRun().getContraIndication(); - } - - public void setContraIndication(ContraIndication contraIndication) { - InstrumentRun currentRun = getInstrumentRun(); - - currentRun.setContraIndication(contraIndication); - getPersistenceManager().save(currentRun); - } - - public String getOtherContraIndication() { - return getInstrumentRun().getOtherContraIndication(); - } - - public void setOtherContraIndication(String otherContraIndication) { - InstrumentRun currentRun = getInstrumentRun(); - - currentRun.setOtherContraIndication(otherContraIndication); - getPersistenceManager().save(currentRun); - } - - public InstrumentRunStatus getInstrumentRunStatus() { - return getInstrumentRun().getStatus(); - } - - public void setInstrumentRunStatus(InstrumentRunStatus status) { - InstrumentRun currentRun = getInstrumentRun(); - - currentRun.setStatus(status); - getPersistenceManager().save(currentRun); - } - - public UserSessionService getUserSessionService() { - return userSessionService; - } - - public void setUserSessionService(UserSessionService userSessionService) { - this.userSessionService = userSessionService; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl; + +import java.io.Serializable; +import java.util.Date; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameterAlgorithm; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class DefaultActiveInstrumentRunServiceImpl extends PersistenceManagerAwareService implements ActiveInstrumentRunService { + + private UserSessionService userSessionService; + + private Serializable currentRunId = null; + + private Serializable instrumentTypeId = null; + + public InstrumentRun start(Participant participant, Instrument instrument) { + + if(currentRunId != null) { + InstrumentRun currentRun = getInstrumentRun(); + if(currentRun.getStatus().equals(InstrumentRunStatus.IN_PROGRESS)) { + cancel(); + } + currentRun = null; + } + + ParticipantInterview participantInterviewTemplate = new ParticipantInterview(); + participantInterviewTemplate.setParticipant(participant); + ParticipantInterview participantInterview = getPersistenceManager().matchOne(participantInterviewTemplate); + if(participantInterview == null) { + participantInterview = getPersistenceManager().save(participantInterviewTemplate); + } + + InstrumentRun currentRun = new InstrumentRun(); + currentRun.setParticipantInterview(participantInterview); + currentRun.setInstrument(instrument); + currentRun.setStatus(InstrumentRunStatus.IN_PROGRESS); + currentRun.setTimeStart(new Date()); + currentRun.setUser(userSessionService.getUser()); + getPersistenceManager().save(currentRun); + currentRunId = currentRun.getId(); + + return currentRun; + } + + public void cancel() { + end(InstrumentRunStatus.CANCELED); + } + + public void fail() { + end(InstrumentRunStatus.IN_ERROR); + } + + public void complete() { + end(InstrumentRunStatus.COMPLETED); + } + + public void end() { + if(currentRunId == null) return; + + InstrumentRun currentRun = getInstrumentRun(); + currentRun.setTimeEnd(new Date()); + + getPersistenceManager().save(currentRun); + } + + private void end(InstrumentRunStatus status) { + if(currentRunId == null) return; + + InstrumentRun currentRun = getInstrumentRun(); + currentRun.setTimeEnd(new Date()); + currentRun.setStatus(status); + + getPersistenceManager().save(currentRun); + } + + public InstrumentRun getInstrumentRun() { + if(currentRunId == null) return null; + + return getPersistenceManager().get(InstrumentRun.class, currentRunId); + } + + public Participant getParticipant() { + if(currentRunId == null) return null; + + return getInstrumentRun().getParticipantInterview().getParticipant(); + } + + public void reset() { + currentRunId = null; + instrumentTypeId = null; + } + + public void update(InstrumentRun currentRun) { + if(currentRunId == null) return; + if(currentRun == null) throw new IllegalArgumentException("Current instrument run cannot be null"); + if(!currentRunId.equals(currentRun.getId())) throw new IllegalArgumentException("Unexpected given current instrument run"); + + getPersistenceManager().save(currentRun); + } + + public void update(InstrumentRunValue currentRunValue) { + if(currentRunId == null) return; + if(currentRunValue.getInstrumentRun() == null) throw new IllegalArgumentException("Current instrument run cannot be null"); + if(!currentRunId.equals(currentRunValue.getInstrumentRun().getId())) throw new IllegalArgumentException("Unexpected given current instrument run"); + + getPersistenceManager().save(currentRunValue); + } + + public void computeOutputParameters() { + if(currentRunId == null) return; + + InstrumentRun currentRun = getInstrumentRun(); + + InstrumentOutputParameter template = new InstrumentOutputParameter(); + template.setInstrument(currentRun.getInstrument()); + template.setCaptureMethod(InstrumentParameterCaptureMethod.COMPUTED); + + // TODO quick and dirty implementation, to be checked + for(InstrumentOutputParameter param : getPersistenceManager().match(template)) { + InstrumentComputedOutputParameter computedParam = (InstrumentComputedOutputParameter) param; + if(computedParam.getAlgorithm().equals(InstrumentOutputParameterAlgorithm.AVERAGE)) { + InstrumentRunValue computedRunValue = getOutputInstrumentRunValue(computedParam.getName()); + + double sum = 0; + int count = 0; + for(InstrumentOutputParameter p : computedParam.getInstrumentOutputParameters()) { + count++; + InstrumentRunValue runValue = currentRun.getInstrumentRunValue(p); + if(runValue.getDataType().equals(DataType.DECIMAL)) { + Double value = runValue.getValue(); + sum += value; + } else if(runValue.getDataType().equals(DataType.INTEGER)) { + Long value = runValue.getValue(); + sum += value.doubleValue(); + } + } + double avg = sum / count; + + Serializable avgValue = null; + if(computedRunValue.getDataType().equals(DataType.DECIMAL)) { + long avgInt = Math.round(avg * 100); + avgValue = (double) avgInt / 100; + } else if(computedRunValue.getDataType().equals(DataType.INTEGER)) { + avgValue = Math.round(avg); + } + + if(avgValue != null) { + computedRunValue.setData(new Data(computedRunValue.getDataType(), avgValue)); + } + + getPersistenceManager().save(computedRunValue); + } + } + } + + public InstrumentRunValue getOutputInstrumentRunValue(String parameterName) { + if(currentRunId == null) return null; + + InstrumentRun currentRun = getInstrumentRun(); + + InstrumentOutputParameter instrumentOutputParameter = new InstrumentOutputParameter(); + instrumentOutputParameter.setName(parameterName); + instrumentOutputParameter.setInstrument(currentRun.getInstrument()); + instrumentOutputParameter = getPersistenceManager().matchOne(instrumentOutputParameter); + + if(instrumentOutputParameter == null) { + throw new IllegalArgumentException("No such output parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); + } + + InstrumentRunValue valueTemplate = new InstrumentRunValue(); + valueTemplate.setInstrumentParameter(instrumentOutputParameter); + valueTemplate.setInstrumentRun(currentRun); + + InstrumentRunValue outputParameterValue = getPersistenceManager().matchOne(valueTemplate); + + if(outputParameterValue == null) { + valueTemplate.setCaptureMethod(instrumentOutputParameter.getCaptureMethod()); + outputParameterValue = getPersistenceManager().save(valueTemplate); + } + + return outputParameterValue; + } + + public InstrumentRunValue getInputInstrumentRunValue(String parameterName) { + if(currentRunId == null) return null; + + InstrumentRun currentRun = getInstrumentRun(); + + InstrumentInputParameter instrumentInputParameter = new InstrumentInputParameter(); + instrumentInputParameter.setName(parameterName); + instrumentInputParameter.setInstrument(currentRun.getInstrument()); + instrumentInputParameter = getPersistenceManager().matchOne(instrumentInputParameter); + + if(instrumentInputParameter == null) { + throw new IllegalArgumentException("No such input parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); + } + + InstrumentRunValue valueTemplate = new InstrumentRunValue(); + valueTemplate.setInstrumentParameter(instrumentInputParameter); + valueTemplate.setInstrumentRun(currentRun); + + InstrumentRunValue inputParameterValue = getPersistenceManager().matchOne(valueTemplate); + + if(inputParameterValue == null) { + valueTemplate.setCaptureMethod(instrumentInputParameter.getCaptureMethod()); + inputParameterValue = getPersistenceManager().save(valueTemplate); + } + + return inputParameterValue; + } + + public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName) { + if(currentRunId == null) return null; + + InstrumentRun currentRun = getInstrumentRun(); + + InterpretativeParameter instrumentInterpretativeParameter = new InterpretativeParameter(); + instrumentInterpretativeParameter.setName(parameterName); + instrumentInterpretativeParameter.setInstrument(currentRun.getInstrument()); + instrumentInterpretativeParameter = getPersistenceManager().matchOne(instrumentInterpretativeParameter); + + if(instrumentInterpretativeParameter == null) { + throw new IllegalArgumentException("No such interpretative parameter name for instrument " + currentRun.getInstrument().getName() + " :" + parameterName); + } + + InstrumentRunValue valueTemplate = new InstrumentRunValue(); + valueTemplate.setInstrumentParameter(instrumentInterpretativeParameter); + valueTemplate.setInstrumentRun(currentRun); + + InstrumentRunValue interpretativeParameterValue = getPersistenceManager().matchOne(valueTemplate); + + if(interpretativeParameterValue == null) { + valueTemplate.setCaptureMethod(instrumentInterpretativeParameter.getCaptureMethod()); + interpretativeParameterValue = getPersistenceManager().save(valueTemplate); + } + + return interpretativeParameterValue; + } + + public InstrumentType getInstrumentType() { + return getPersistenceManager().get(InstrumentType.class, instrumentTypeId); + } + + public void setInstrumentType(InstrumentType instrumentType) { + this.instrumentTypeId = instrumentType.getId(); + } + + public Instrument getInstrument() { + return getInstrumentRun().getInstrument(); + } + + public ContraIndication getContraIndication() { + return getInstrumentRun().getContraIndication(); + } + + public void setContraIndication(ContraIndication contraIndication) { + InstrumentRun currentRun = getInstrumentRun(); + + currentRun.setContraIndication(contraIndication); + getPersistenceManager().save(currentRun); + } + + public String getOtherContraIndication() { + return getInstrumentRun().getOtherContraIndication(); + } + + public void setOtherContraIndication(String otherContraIndication) { + InstrumentRun currentRun = getInstrumentRun(); + + currentRun.setOtherContraIndication(otherContraIndication); + getPersistenceManager().save(currentRun); + } + + public InstrumentRunStatus getInstrumentRunStatus() { + return getInstrumentRun().getStatus(); + } + + public void setInstrumentRunStatus(InstrumentRunStatus status) { + InstrumentRun currentRun = getInstrumentRun(); + + currentRun.setStatus(status); + getPersistenceManager().save(currentRun); + } + + public UserSessionService getUserSessionService() { + return userSessionService; + } + + public void setUserSessionService(UserSessionService userSessionService) { + this.userSessionService = userSessionService; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentDescriptorServiceImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentDescriptorServiceImpl.java index 9eed096ab..4fb4e0fa1 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentDescriptorServiceImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentDescriptorServiceImpl.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.jade.core.service.impl; - -import java.util.HashMap; -import java.util.Map; - -import org.obiba.onyx.jade.core.domain.instrument.InstrumentDescriptor; -import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; - -public class DefaultInstrumentDescriptorServiceImpl implements InstrumentDescriptorService { - - private Map descriptorMap;; - - public DefaultInstrumentDescriptorServiceImpl() { - descriptorMap = new HashMap(); - } - - public String getCodeBase(String instrumentBarCode) { - InstrumentDescriptor descriptor = descriptorMap.get(instrumentBarCode); - if(descriptor == null) return null; - else - return descriptor.getCodeBase(); - } - - public void setCodeBase(String instrumentBarCode, String codeBase) { - InstrumentDescriptor descriptor = descriptorMap.get(instrumentBarCode); - if (descriptor == null) { - descriptor = new InstrumentDescriptor(instrumentBarCode); - descriptorMap.put(instrumentBarCode, descriptor); - } - descriptor.setCodeBase(codeBase); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.obiba.onyx.jade.core.domain.instrument.InstrumentDescriptor; +import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; + +public class DefaultInstrumentDescriptorServiceImpl implements InstrumentDescriptorService { + + private Map descriptorMap;; + + public DefaultInstrumentDescriptorServiceImpl() { + descriptorMap = new HashMap(); + } + + public String getCodeBase(String instrumentBarCode) { + InstrumentDescriptor descriptor = descriptorMap.get(instrumentBarCode); + if(descriptor == null) return null; + else + return descriptor.getCodeBase(); + } + + public void setCodeBase(String instrumentBarCode, String codeBase) { + InstrumentDescriptor descriptor = descriptorMap.get(instrumentBarCode); + if (descriptor == null) { + descriptor = new InstrumentDescriptor(instrumentBarCode); + descriptorMap.put(instrumentBarCode, descriptor); + } + descriptor.setCodeBase(codeBase); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentRunServiceImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentRunServiceImpl.java index 6475428e4..f5095c84a 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentRunServiceImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentRunServiceImpl.java @@ -1,32 +1,41 @@ -package org.obiba.onyx.jade.core.service.impl; - -import java.util.List; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.InstrumentRunService; - -public abstract class DefaultInstrumentRunServiceImpl extends PersistenceManagerAwareService implements InstrumentRunService { - - private List getInstrumentRuns(Instrument instrument, Participant participant, InstrumentRunStatus status) { - - ParticipantInterview interview = new ParticipantInterview(); - interview.setParticipant(participant); - interview = getPersistenceManager().matchOne(interview); - InstrumentRun template = new InstrumentRun(); - template.setInstrument(instrument); - template.setParticipantInterview(interview); - template.setStatus(status); - - return getPersistenceManager().match(template); - } - - public List getCompletedInstrumentRuns(Participant participant, Instrument instrument) { - return getInstrumentRuns(instrument, participant, InstrumentRunStatus.COMPLETED); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl; + +import java.util.List; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.InstrumentRunService; + +public abstract class DefaultInstrumentRunServiceImpl extends PersistenceManagerAwareService implements InstrumentRunService { + + private List getInstrumentRuns(Instrument instrument, Participant participant, InstrumentRunStatus status) { + + ParticipantInterview interview = new ParticipantInterview(); + interview.setParticipant(participant); + interview = getPersistenceManager().matchOne(interview); + InstrumentRun template = new InstrumentRun(); + template.setInstrument(instrument); + template.setParticipantInterview(interview); + template.setStatus(status); + + return getPersistenceManager().match(template); + } + + public List getCompletedInstrumentRuns(Participant participant, Instrument instrument) { + return getInstrumentRuns(instrument, participant, InstrumentRunStatus.COMPLETED); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentServiceImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentServiceImpl.java index a9bf5cfce..fd3b8a202 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentServiceImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/DefaultInstrumentServiceImpl.java @@ -1,88 +1,97 @@ -package org.obiba.onyx.jade.core.service.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class DefaultInstrumentServiceImpl extends PersistenceManagerAwareService implements InstrumentService { - - public InstrumentType createInstrumentType(String name, String description) { - InstrumentType type = new InstrumentType(name, description); - return getPersistenceManager().save(type); - } - - public InstrumentType getInstrumentType(String name) { - InstrumentType template = new InstrumentType(name, null); - return getPersistenceManager().matchOne(template); - } - - public void addInstrumentTypeDependency(InstrumentType type, InstrumentType dependency) { - type.addDependentType(dependency); - getPersistenceManager().save(type); - } - - public List getInstruments(String typeName) { - return getInstruments(getInstrumentType(typeName)); - } - - public List getInstruments(InstrumentType instrumentType) { - Instrument template = new Instrument(); - template.setInstrumentType(instrumentType); - - return getPersistenceManager().match(template); - } - - public List getActiveInstruments(InstrumentType instrumentType) { - Instrument template = new Instrument(); - template.setInstrumentType(instrumentType); - template.setStatus(InstrumentStatus.ACTIVE); - - return getPersistenceManager().match(template); - } - - public void addInstrument(InstrumentType instrumentType, Instrument instrument) { - if(instrumentType != null && instrument != null) { - instrumentType.addInstrument(instrument); - getPersistenceManager().save(instrumentType); - } - } - - public boolean isInteractiveInstrument(Instrument instrument) { - if(instrument == null) return false; - - InstrumentOutputParameter template = new InstrumentOutputParameter(); - template.setInstrument(instrument); - template.setCaptureMethod(InstrumentParameterCaptureMethod.AUTOMATIC); - - return getPersistenceManager().count(template) > 0; - } - - public int countInstrumentInputParameter(Instrument instrument, boolean readOnlySource) { - return getInstrumentInputParameter(instrument, readOnlySource).size(); - } - - public List getInstrumentInputParameter(Instrument instrument, boolean readOnlySource) { - List list = new ArrayList(); - InstrumentInputParameter template = new InstrumentInputParameter(); - template.setInstrument(instrument); - - for (InstrumentInputParameter param : getPersistenceManager().match(template)) { - if (param.getInputSource() != null && param.getInputSource().isReadOnly() == readOnlySource) { - list.add(param); - } - } - - return list; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class DefaultInstrumentServiceImpl extends PersistenceManagerAwareService implements InstrumentService { + + public InstrumentType createInstrumentType(String name, String description) { + InstrumentType type = new InstrumentType(name, description); + return getPersistenceManager().save(type); + } + + public InstrumentType getInstrumentType(String name) { + InstrumentType template = new InstrumentType(name, null); + return getPersistenceManager().matchOne(template); + } + + public void addInstrumentTypeDependency(InstrumentType type, InstrumentType dependency) { + type.addDependentType(dependency); + getPersistenceManager().save(type); + } + + public List getInstruments(String typeName) { + return getInstruments(getInstrumentType(typeName)); + } + + public List getInstruments(InstrumentType instrumentType) { + Instrument template = new Instrument(); + template.setInstrumentType(instrumentType); + + return getPersistenceManager().match(template); + } + + public List getActiveInstruments(InstrumentType instrumentType) { + Instrument template = new Instrument(); + template.setInstrumentType(instrumentType); + template.setStatus(InstrumentStatus.ACTIVE); + + return getPersistenceManager().match(template); + } + + public void addInstrument(InstrumentType instrumentType, Instrument instrument) { + if(instrumentType != null && instrument != null) { + instrumentType.addInstrument(instrument); + getPersistenceManager().save(instrumentType); + } + } + + public boolean isInteractiveInstrument(Instrument instrument) { + if(instrument == null) return false; + + InstrumentOutputParameter template = new InstrumentOutputParameter(); + template.setInstrument(instrument); + template.setCaptureMethod(InstrumentParameterCaptureMethod.AUTOMATIC); + + return getPersistenceManager().count(template) > 0; + } + + public int countInstrumentInputParameter(Instrument instrument, boolean readOnlySource) { + return getInstrumentInputParameter(instrument, readOnlySource).size(); + } + + public List getInstrumentInputParameter(Instrument instrument, boolean readOnlySource) { + List list = new ArrayList(); + InstrumentInputParameter template = new InstrumentInputParameter(); + template.setInstrument(instrument); + + for (InstrumentInputParameter param : getPersistenceManager().match(template)) { + if (param.getInputSource() != null && param.getInputSource().isReadOnly() == readOnlySource) { + list.add(param); + } + } + + return list; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/InputDataSourceVisitorImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/InputDataSourceVisitorImpl.java index b42ec8824..1fb9c089d 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/InputDataSourceVisitorImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/InputDataSourceVisitorImpl.java @@ -1,125 +1,134 @@ -package org.obiba.onyx.jade.core.service.impl; - -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.Serializable; -import java.text.SimpleDateFormat; - -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.FixedSource; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; -import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class InputDataSourceVisitorImpl implements InputDataSourceVisitor { - - private static final Logger log = LoggerFactory.getLogger(InputDataSourceVisitorImpl.class); - - private InstrumentRunService instrumentRunService; - - private Data data; - - private Participant participant; - - private InstrumentInputParameter parameter; - - public void setInstrumentRunService(InstrumentRunService instrumentRunService) { - this.instrumentRunService = instrumentRunService; - } - - public Data getData(Participant participant, InstrumentInputParameter parameter) { - if(parameter == null) return null; - if(parameter.getInputSource() == null) return null; - - this.participant = participant; - this.parameter = parameter; - data = null; - parameter.getInputSource().accept(this); - return data; - } - - public void visit(ParticipantPropertySource source) { - try { - log.info("source.participant.property=" + source.getProperty()); - for(PropertyDescriptor pd : Introspector.getBeanInfo(Participant.class).getPropertyDescriptors()) { - if(source.getProperty().equals(pd.getName())) { - Object propertyValue = pd.getReadMethod().invoke(participant); - log.info("source.participant.property." + source.getProperty() + "=" + propertyValue + " " + propertyValue.getClass().getSimpleName()); - if(propertyValue instanceof Gender) { - propertyValue = propertyValue.toString(); - } - - data = new Data(parameter.getDataType(), (Serializable) propertyValue); - } - } - - } catch(Exception e) { - log.warn("Failed getting Participant property: " + source.getProperty(), e); - } - } - - public void visit(FixedSource source) { - Serializable value = null; - if(source.getValue() != null) { - try { - switch(parameter.getDataType()) { - case BOOLEAN: - value = Boolean.parseBoolean(source.getValue()); - break; - case INTEGER: - value = Long.parseLong(source.getValue()); - break; - case DECIMAL: - value = Double.parseDouble(source.getValue()); - break; - case DATE: - value = SimpleDateFormat.getInstance().parse(source.getValue()); - break; - case TEXT: - value = source.getValue(); - break; - case DATA: - value = source.getValue().getBytes(); - break; - } - } catch(Exception e) { - log.warn("Failed getting Fixed value: " + source.getValue(), e); - } - } - data = new Data(parameter.getDataType(), value); - } - - public void visit(OperatorSource source) { - data = null; - } - - public void visit(OutputParameterSource source) { - InstrumentRunValue runValue = instrumentRunService.findInstrumentRunValue(participant, source.getInstrumentType(), source.getParameterName()); - if(runValue != null) { - // TODO unit conversion when necessary - // TODO type conversion when possible (INTEGER->DECIMAL->TEXT...) - data = runValue.getData(); - } - } - - public void visit(MultipleOutputParameterSource source) { - for(OutputParameterSource outputParameterSource : source.getOutputParameterSourceList()) { - InstrumentRunValue runValue = instrumentRunService.findInstrumentRunValue(participant, outputParameterSource.getInstrumentType(), outputParameterSource.getParameterName()); - if(runValue != null) { - if(runValue.getData().getValue() != null) { - data = runValue.getData(); - break; - } - } - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.Serializable; +import java.text.SimpleDateFormat; + +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.FixedSource; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; +import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InputDataSourceVisitorImpl implements InputDataSourceVisitor { + + private static final Logger log = LoggerFactory.getLogger(InputDataSourceVisitorImpl.class); + + private InstrumentRunService instrumentRunService; + + private Data data; + + private Participant participant; + + private InstrumentInputParameter parameter; + + public void setInstrumentRunService(InstrumentRunService instrumentRunService) { + this.instrumentRunService = instrumentRunService; + } + + public Data getData(Participant participant, InstrumentInputParameter parameter) { + if(parameter == null) return null; + if(parameter.getInputSource() == null) return null; + + this.participant = participant; + this.parameter = parameter; + data = null; + parameter.getInputSource().accept(this); + return data; + } + + public void visit(ParticipantPropertySource source) { + try { + log.info("source.participant.property=" + source.getProperty()); + for(PropertyDescriptor pd : Introspector.getBeanInfo(Participant.class).getPropertyDescriptors()) { + if(source.getProperty().equals(pd.getName())) { + Object propertyValue = pd.getReadMethod().invoke(participant); + log.info("source.participant.property." + source.getProperty() + "=" + propertyValue + " " + propertyValue.getClass().getSimpleName()); + if(propertyValue instanceof Gender) { + propertyValue = propertyValue.toString(); + } + + data = new Data(parameter.getDataType(), (Serializable) propertyValue); + } + } + + } catch(Exception e) { + log.warn("Failed getting Participant property: " + source.getProperty(), e); + } + } + + public void visit(FixedSource source) { + Serializable value = null; + if(source.getValue() != null) { + try { + switch(parameter.getDataType()) { + case BOOLEAN: + value = Boolean.parseBoolean(source.getValue()); + break; + case INTEGER: + value = Long.parseLong(source.getValue()); + break; + case DECIMAL: + value = Double.parseDouble(source.getValue()); + break; + case DATE: + value = SimpleDateFormat.getInstance().parse(source.getValue()); + break; + case TEXT: + value = source.getValue(); + break; + case DATA: + value = source.getValue().getBytes(); + break; + } + } catch(Exception e) { + log.warn("Failed getting Fixed value: " + source.getValue(), e); + } + } + data = new Data(parameter.getDataType(), value); + } + + public void visit(OperatorSource source) { + data = null; + } + + public void visit(OutputParameterSource source) { + InstrumentRunValue runValue = instrumentRunService.findInstrumentRunValue(participant, source.getInstrumentType(), source.getParameterName()); + if(runValue != null) { + // TODO unit conversion when necessary + // TODO type conversion when possible (INTEGER->DECIMAL->TEXT...) + data = runValue.getData(); + } + } + + public void visit(MultipleOutputParameterSource source) { + for(OutputParameterSource outputParameterSource : source.getOutputParameterSourceList()) { + InstrumentRunValue runValue = instrumentRunService.findInstrumentRunValue(participant, outputParameterSource.getInstrumentType(), outputParameterSource.getParameterName()); + if(runValue != null) { + if(runValue.getData().getValue() != null) { + data = runValue.getData(); + break; + } + } + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/hibernate/InstrumentRunServiceHibernateImpl.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/hibernate/InstrumentRunServiceHibernateImpl.java index f6f2f5c96..d4e700c0f 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/hibernate/InstrumentRunServiceHibernateImpl.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/service/impl/hibernate/InstrumentRunServiceHibernateImpl.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.jade.core.service.impl.hibernate; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Restrictions; -import org.obiba.core.service.SortingClause; -import org.obiba.core.service.impl.hibernate.AssociationCriteria; -import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.impl.DefaultInstrumentRunServiceImpl; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class InstrumentRunServiceHibernateImpl extends DefaultInstrumentRunServiceImpl { - - private SessionFactory factory; - - public void setSessionFactory(SessionFactory factory) { - this.factory = factory; - } - - private Session getSession() { - return factory.getCurrentSession(); - } - - public InstrumentRun getLastInstrumentRun(Participant participant, InstrumentType instrumentType) { - return (InstrumentRun) AssociationCriteria.create(InstrumentRun.class, getSession()).add("instrument.instrumentType", Operation.eq, instrumentType).add("participantInterview.participant", Operation.eq, participant).addSortingClauses(new SortingClause("timeEnd", false)).getCriteria().uniqueResult(); - } - - public InstrumentRun getLastCompletedInstrumentRun(Participant participant, InstrumentType instrumentType) { - Criteria criteria = AssociationCriteria.create(InstrumentRun.class, getSession()).add("instrument.instrumentType", Operation.eq, instrumentType).add("participantInterview.participant", Operation.eq, participant).addSortingClauses(new SortingClause("timeEnd", false)).getCriteria(); - criteria.add(Restrictions.or(Restrictions.eq("status", InstrumentRunStatus.COMPLETED), Restrictions.eq("status", InstrumentRunStatus.CONTRA_INDICATED))); - - return (InstrumentRun) criteria.setMaxResults(1).uniqueResult(); - } - - public InstrumentRunValue findInstrumentRunValue(Participant participant, InstrumentType instrumentType, String parameterName) { - InstrumentRunValue runValue = null; - InstrumentRun run = getLastCompletedInstrumentRun(participant, instrumentType); - - if(run != null) { - runValue = (InstrumentRunValue) AssociationCriteria.create(InstrumentRunValue.class, getSession()).add("instrumentRun", Operation.eq, run).add("instrumentParameter.name", Operation.eq, parameterName).getCriteria().uniqueResult(); - } - return runValue; - } - - public void setInstrumentRunStatus(InstrumentRun run, InstrumentRunStatus status) { - run.setStatus(status); - getPersistenceManager().save(run); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service.impl.hibernate; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Restrictions; +import org.obiba.core.service.SortingClause; +import org.obiba.core.service.impl.hibernate.AssociationCriteria; +import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.impl.DefaultInstrumentRunServiceImpl; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class InstrumentRunServiceHibernateImpl extends DefaultInstrumentRunServiceImpl { + + private SessionFactory factory; + + public void setSessionFactory(SessionFactory factory) { + this.factory = factory; + } + + private Session getSession() { + return factory.getCurrentSession(); + } + + public InstrumentRun getLastInstrumentRun(Participant participant, InstrumentType instrumentType) { + return (InstrumentRun) AssociationCriteria.create(InstrumentRun.class, getSession()).add("instrument.instrumentType", Operation.eq, instrumentType).add("participantInterview.participant", Operation.eq, participant).addSortingClauses(new SortingClause("timeEnd", false)).getCriteria().uniqueResult(); + } + + public InstrumentRun getLastCompletedInstrumentRun(Participant participant, InstrumentType instrumentType) { + Criteria criteria = AssociationCriteria.create(InstrumentRun.class, getSession()).add("instrument.instrumentType", Operation.eq, instrumentType).add("participantInterview.participant", Operation.eq, participant).addSortingClauses(new SortingClause("timeEnd", false)).getCriteria(); + criteria.add(Restrictions.or(Restrictions.eq("status", InstrumentRunStatus.COMPLETED), Restrictions.eq("status", InstrumentRunStatus.CONTRA_INDICATED))); + + return (InstrumentRun) criteria.setMaxResults(1).uniqueResult(); + } + + public InstrumentRunValue findInstrumentRunValue(Participant participant, InstrumentType instrumentType, String parameterName) { + InstrumentRunValue runValue = null; + InstrumentRun run = getLastCompletedInstrumentRun(participant, instrumentType); + + if(run != null) { + runValue = (InstrumentRunValue) AssociationCriteria.create(InstrumentRunValue.class, getSession()).add("instrumentRun", Operation.eq, run).add("instrumentParameter.name", Operation.eq, parameterName).getCriteria().uniqueResult(); + } + return runValue; + } + + public void setInstrumentRunStatus(InstrumentRun run, InstrumentRunStatus status) { + run.setStatus(status); + getPersistenceManager().save(run); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/JadePanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/JadePanel.java index 9081ece05..4f8aa1807 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/JadePanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/JadePanel.java @@ -1,138 +1,147 @@ -package org.obiba.onyx.jade.core.wicket; - -import java.io.Serializable; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.wicket.wizard.InstrumentWizardForm; -import org.obiba.onyx.wicket.IEngineComponentAware; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardPanel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; - -public class JadePanel extends Panel implements IEngineComponentAware { - - private static final long serialVersionUID = -6692482689347742363L; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private ActionWindow actionWindow; - - private FeedbackPanel feedbackPanel; - - private JadeModel model; - - @SuppressWarnings("serial") - public JadePanel(String id, Stage stage) { - super(id); - InstrumentType type = getInstrumentType(stage); - model = new JadeModel(new StageModel(moduleRegistry, stage.getName()), new DetachableEntityModel(queryService, type)); - - add(new WizardPanel("content", model.getIntrumentTypeModel()) { - - @Override - public WizardForm createForm(String componentId) { - return new InstrumentWizardForm(componentId, getModel()) { - - @Override - public void onCancel(AjaxRequestTarget target) { - IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); - ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); - if(actionDef != null) { - actionWindow.show(target, model.getStageModel(), actionDef); - } - } - - @Override - public void onFinish(AjaxRequestTarget target, Form form) { - IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); - ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); - if(actionDef != null) { - actionWindow.show(target, model.getStageModel(), actionDef); - } - } - - @Override - public void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedbackPanel); - } - - @Override - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - }; - } - - }); - } - - private InstrumentType getInstrumentType(Stage stage) { - InstrumentType template = new InstrumentType(stage.getName(), null); - return queryService.matchOne(template); - } - - public void setActionWindwon(ActionWindow window) { - this.actionWindow = window; - } - - public void setFeedbackPanel(FeedbackPanel feedbackPanel) { - this.feedbackPanel = feedbackPanel; - } - - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - @SuppressWarnings("serial") - private class JadeModel implements Serializable { - private IModel intrumentTypeModel; - - private IModel stageModel; - - public JadeModel(IModel stageModel, IModel instrumentTypeModel) { - this.intrumentTypeModel = instrumentTypeModel; - this.stageModel = stageModel; - } - - public InstrumentType getIntrumentType() { - return (InstrumentType) intrumentTypeModel.getObject(); - } - - public Stage getStage() { - return (Stage) stageModel.getObject(); - } - - public IModel getIntrumentTypeModel() { - return intrumentTypeModel; - } - - public IModel getStageModel() { - return stageModel; - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket; + +import java.io.Serializable; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.wicket.wizard.InstrumentWizardForm; +import org.obiba.onyx.wicket.IEngineComponentAware; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardPanel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; + +public class JadePanel extends Panel implements IEngineComponentAware { + + private static final long serialVersionUID = -6692482689347742363L; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private ActionWindow actionWindow; + + private FeedbackPanel feedbackPanel; + + private JadeModel model; + + @SuppressWarnings("serial") + public JadePanel(String id, Stage stage) { + super(id); + InstrumentType type = getInstrumentType(stage); + model = new JadeModel(new StageModel(moduleRegistry, stage.getName()), new DetachableEntityModel(queryService, type)); + + add(new WizardPanel("content", model.getIntrumentTypeModel()) { + + @Override + public WizardForm createForm(String componentId) { + return new InstrumentWizardForm(componentId, getModel()) { + + @Override + public void onCancel(AjaxRequestTarget target) { + IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); + ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); + if(actionDef != null) { + actionWindow.show(target, model.getStageModel(), actionDef); + } + } + + @Override + public void onFinish(AjaxRequestTarget target, Form form) { + IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); + ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); + if(actionDef != null) { + actionWindow.show(target, model.getStageModel(), actionDef); + } + } + + @Override + public void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedbackPanel); + } + + @Override + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + }; + } + + }); + } + + private InstrumentType getInstrumentType(Stage stage) { + InstrumentType template = new InstrumentType(stage.getName(), null); + return queryService.matchOne(template); + } + + public void setActionWindwon(ActionWindow window) { + this.actionWindow = window; + } + + public void setFeedbackPanel(FeedbackPanel feedbackPanel) { + this.feedbackPanel = feedbackPanel; + } + + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + @SuppressWarnings("serial") + private class JadeModel implements Serializable { + private IModel intrumentTypeModel; + + private IModel stageModel; + + public JadeModel(IModel stageModel, IModel instrumentTypeModel) { + this.intrumentTypeModel = instrumentTypeModel; + this.stageModel = stageModel; + } + + public InstrumentType getIntrumentType() { + return (InstrumentType) intrumentTypeModel.getObject(); + } + + public Stage getStage() { + return (Stage) stageModel.getObject(); + } + + public IModel getIntrumentTypeModel() { + return intrumentTypeModel; + } + + public IModel getStageModel() { + return stageModel; + } + + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/AskedContraIndicationPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/AskedContraIndicationPanel.java index 542a515a3..4a0af0c81 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/AskedContraIndicationPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/AskedContraIndicationPanel.java @@ -1,155 +1,164 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.FormComponentLabel; -import org.apache.wicket.markup.html.form.Radio; -import org.apache.wicket.markup.html.form.RadioGroup; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.list.ListView; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AskedContraIndicationPanel extends Panel { - - private static final long serialVersionUID = 1839206247478532673L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(AskedContraIndicationPanel.class); - - private static final String YES = "Yes"; - private static final String NO = "No"; - private static final String DOESNOT_KNOW = "DoesNotKnow"; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean(name = "userSessionService") - private UserSessionService userSessionService; - - private List radioGroups; - - @SuppressWarnings("serial") - public AskedContraIndicationPanel(String id) { - super(id); - setOutputMarkupId(true); - - radioGroups = new ArrayList(); - - RepeatingView repeat = new RepeatingView("repeat"); - add(repeat); - - final ContraIndication defaultCi = activeInstrumentRunService.getContraIndication(); - ContraIndication template = new ContraIndication(); - template.setType(ParticipantInteractionType.ASKED); - template.setInstrument(activeInstrumentRunService.getInstrument()); - for(final ContraIndication ci : queryService.match(template)) { - WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); - repeat.add(item); - - ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); - ci.setUserSessionService(userSessionService); - - item.add(new Label("ciLabel", new PropertyModel(ci, "description"))); - - // radio group without default selection - final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); - radioGroups.add(radioGroup); - radioGroup.setLabel(new PropertyModel(ci, "description")); - item.add(radioGroup); - ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO, DOESNOT_KNOW })) { - - @Override - protected void populateItem(ListItem listItem) { - final String key = listItem.getModelObjectAsString(); - final ContraIndicationSelection selection = new ContraIndicationSelection(); - selection.setContraIndication(ci); - selection.setSelectionKey(key); - - Model selectModel = new Model(selection); - - Radio radio = new Radio("radio", selectModel); - radio.setLabel(new StringResourceModel(key, AskedContraIndicationPanel.this, null)); - - // set default selection - // cannot decide if yes/no/dontknow was selected, so only deal with case the default ci is not null - // and it was because yes was selected - if (key.equals(YES) && defaultCi != null && (defaultCi.getType().equals(ci.getType()) & defaultCi.getName().equals(ci.getName()))) { - radioGroup.setModel(selectModel); - } - - FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); - listItem.add(radioLabel); - radioLabel.add(radio); - radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); - } - - }.setReuseItems(true); - radioGroup.add(radioList); - radioGroup.setRequired(true); - } - - } - - public void saveContraIndicationSelection() { - activeInstrumentRunService.setContraIndication(null); - for (RadioGroup rg : radioGroups) { - ContraIndicationSelection ciSelection = (ContraIndicationSelection)rg.getModelObject(); - if (ciSelection.isSelected()) { - activeInstrumentRunService.setContraIndication(ciSelection.getContraIndication()); - // just interested in the first one - break; - } - } - } - - @SuppressWarnings("serial") - private class ContraIndicationSelection implements Serializable { - - private String selectionKey; - - private ContraIndication contraIndication; - - public String getSelectionKey() { - return selectionKey; - } - - public void setSelectionKey(String selectionKey) { - this.selectionKey = selectionKey; - } - - public boolean isSelected() { - return selectionKey.equals(YES) || selectionKey.equals(DOESNOT_KNOW); - } - - public ContraIndication getContraIndication() { - return contraIndication; - } - - public void setContraIndication(ContraIndication contraIndication) { - this.contraIndication = contraIndication; - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.FormComponentLabel; +import org.apache.wicket.markup.html.form.Radio; +import org.apache.wicket.markup.html.form.RadioGroup; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AskedContraIndicationPanel extends Panel { + + private static final long serialVersionUID = 1839206247478532673L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(AskedContraIndicationPanel.class); + + private static final String YES = "Yes"; + private static final String NO = "No"; + private static final String DOESNOT_KNOW = "DoesNotKnow"; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean(name = "userSessionService") + private UserSessionService userSessionService; + + private List radioGroups; + + @SuppressWarnings("serial") + public AskedContraIndicationPanel(String id) { + super(id); + setOutputMarkupId(true); + + radioGroups = new ArrayList(); + + RepeatingView repeat = new RepeatingView("repeat"); + add(repeat); + + final ContraIndication defaultCi = activeInstrumentRunService.getContraIndication(); + ContraIndication template = new ContraIndication(); + template.setType(ParticipantInteractionType.ASKED); + template.setInstrument(activeInstrumentRunService.getInstrument()); + for(final ContraIndication ci : queryService.match(template)) { + WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); + repeat.add(item); + + ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); + ci.setUserSessionService(userSessionService); + + item.add(new Label("ciLabel", new PropertyModel(ci, "description"))); + + // radio group without default selection + final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); + radioGroups.add(radioGroup); + radioGroup.setLabel(new PropertyModel(ci, "description")); + item.add(radioGroup); + ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO, DOESNOT_KNOW })) { + + @Override + protected void populateItem(ListItem listItem) { + final String key = listItem.getModelObjectAsString(); + final ContraIndicationSelection selection = new ContraIndicationSelection(); + selection.setContraIndication(ci); + selection.setSelectionKey(key); + + Model selectModel = new Model(selection); + + Radio radio = new Radio("radio", selectModel); + radio.setLabel(new StringResourceModel(key, AskedContraIndicationPanel.this, null)); + + // set default selection + // cannot decide if yes/no/dontknow was selected, so only deal with case the default ci is not null + // and it was because yes was selected + if (key.equals(YES) && defaultCi != null && (defaultCi.getType().equals(ci.getType()) & defaultCi.getName().equals(ci.getName()))) { + radioGroup.setModel(selectModel); + } + + FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); + listItem.add(radioLabel); + radioLabel.add(radio); + radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); + } + + }.setReuseItems(true); + radioGroup.add(radioList); + radioGroup.setRequired(true); + } + + } + + public void saveContraIndicationSelection() { + activeInstrumentRunService.setContraIndication(null); + for (RadioGroup rg : radioGroups) { + ContraIndicationSelection ciSelection = (ContraIndicationSelection)rg.getModelObject(); + if (ciSelection.isSelected()) { + activeInstrumentRunService.setContraIndication(ciSelection.getContraIndication()); + // just interested in the first one + break; + } + } + } + + @SuppressWarnings("serial") + private class ContraIndicationSelection implements Serializable { + + private String selectionKey; + + private ContraIndication contraIndication; + + public String getSelectionKey() { + return selectionKey; + } + + public void setSelectionKey(String selectionKey) { + this.selectionKey = selectionKey; + } + + public boolean isSelected() { + return selectionKey.equals(YES) || selectionKey.equals(DOESNOT_KNOW); + } + + public ContraIndication getContraIndication() { + return contraIndication; + } + + public void setContraIndication(ContraIndication contraIndication) { + this.contraIndication = contraIndication; + } + + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ConclusionPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ConclusionPanel.java index 1a1635255..40c3a6a10 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ConclusionPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ConclusionPanel.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; -import org.obiba.onyx.jade.core.wicket.run.InstrumentRunPanel; - -public class ConclusionPanel extends Panel { - - private static final long serialVersionUID = 3008363510160516288L; - - @SuppressWarnings("serial") - public ConclusionPanel(String id) { - super(id); - setOutputMarkupId(true); - - final ModalWindow modal; - add(modal = new ModalWindow("modal")); - modal.setCookieName("instrument-run-modal"); - - add(new AjaxLink("show") { - - @Override - public void onClick(AjaxRequestTarget target) { - modal.setContent(new InstrumentRunPanel(modal.getContentId())); - modal.show(target); - } - - }); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; +import org.obiba.onyx.jade.core.wicket.run.InstrumentRunPanel; + +public class ConclusionPanel extends Panel { + + private static final long serialVersionUID = 3008363510160516288L; + + @SuppressWarnings("serial") + public ConclusionPanel(String id) { + super(id); + setOutputMarkupId(true); + + final ModalWindow modal; + add(modal = new ModalWindow("modal")); + modal.setCookieName("instrument-run-modal"); + + add(new AjaxLink("show") { + + @Override + public void onClick(AjaxRequestTarget target) { + modal.setContent(new InstrumentRunPanel(modal.getContentId())); + modal.show(target); + } + + }); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ContraIndicatedPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ContraIndicatedPanel.java index cbd2a046b..c69c50c7c 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ContraIndicatedPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ContraIndicatedPanel.java @@ -1,40 +1,49 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; - -public class ContraIndicatedPanel extends Panel { - - private static final long serialVersionUID = 9014406108097758044L; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean(name = "userSessionService") - private UserSessionService userSessionService; - - public ContraIndicatedPanel(String id) { - super(id); - - ContraIndication ci = activeInstrumentRunService.getContraIndication(); - - ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); - ci.setUserSessionService(userSessionService); - - String reason = ci.getDescription(); - if(ci.getName().equals("Other")) { - reason += " (" + activeInstrumentRunService.getOtherContraIndication() + ")"; - } - - add(new Label("label", new StringResourceModel("ReasonForContraIndication", this, new Model(new ValueMap("ci=" + reason))))); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; + +public class ContraIndicatedPanel extends Panel { + + private static final long serialVersionUID = 9014406108097758044L; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean(name = "userSessionService") + private UserSessionService userSessionService; + + public ContraIndicatedPanel(String id) { + super(id); + + ContraIndication ci = activeInstrumentRunService.getContraIndication(); + + ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); + ci.setUserSessionService(userSessionService); + + String reason = ci.getDescription(); + if(ci.getName().equals("Other")) { + reason += " (" + activeInstrumentRunService.getOtherContraIndication() + ")"; + } + + add(new Label("label", new StringResourceModel("ReasonForContraIndication", this, new Model(new ValueMap("ci=" + reason))))); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentBarcodeConverter.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentBarcodeConverter.java index 1c0d3299d..534498399 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentBarcodeConverter.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentBarcodeConverter.java @@ -1,63 +1,72 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.util.Locale; - -import org.apache.wicket.util.convert.ConversionException; -import org.apache.wicket.util.convert.IConverter; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; - -/** - * Converts the instrument barcode, supposed to be unique, to the corresponding instrument. - * @author Yannick Marcon - * - */ -@SuppressWarnings("serial") -public class InstrumentBarcodeConverter implements IConverter { - - private EntityQueryService queryService; - - private boolean activeOnly; - - private InstrumentType instrumentType; - - public InstrumentBarcodeConverter(EntityQueryService queryService, InstrumentType instrumentType) { - this(queryService, true); - this.instrumentType = instrumentType; - } - - public InstrumentBarcodeConverter(EntityQueryService queryService, boolean activeOnly) { - this.queryService = queryService; - this.activeOnly = activeOnly; - } - - public Object convertToObject(String value, Locale locale) { - if(value == null) return null; - Instrument template = new Instrument(); - template.setBarcode(value); - template.setInstrumentType(instrumentType); - Instrument instrument = queryService.matchOne(template); - - if (instrument == null) { - ConversionException cex = new ConversionException("No instrument for barcode: '" + value + "'"); - cex.setResourceKey("InstrumentBarcodeConverter.NoInstrumentForBarcode"); - throw cex; - } - else if(activeOnly && !instrument.getStatus().equals(InstrumentStatus.ACTIVE)) { - ConversionException cex = new ConversionException("Not an active instrument: '" + value + "'"); - cex.setResourceKey("InstrumentBarcodeConverter.NotAnActiveInstrument"); - throw cex; - } - - return instrument; - } - - public String convertToString(Object value, Locale locale) { - if(value == null) return null; - else - return ((Instrument) value).getBarcode(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.util.Locale; + +import org.apache.wicket.util.convert.ConversionException; +import org.apache.wicket.util.convert.IConverter; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; + +/** + * Converts the instrument barcode, supposed to be unique, to the corresponding instrument. + * @author Yannick Marcon + * + */ +@SuppressWarnings("serial") +public class InstrumentBarcodeConverter implements IConverter { + + private EntityQueryService queryService; + + private boolean activeOnly; + + private InstrumentType instrumentType; + + public InstrumentBarcodeConverter(EntityQueryService queryService, InstrumentType instrumentType) { + this(queryService, true); + this.instrumentType = instrumentType; + } + + public InstrumentBarcodeConverter(EntityQueryService queryService, boolean activeOnly) { + this.queryService = queryService; + this.activeOnly = activeOnly; + } + + public Object convertToObject(String value, Locale locale) { + if(value == null) return null; + Instrument template = new Instrument(); + template.setBarcode(value); + template.setInstrumentType(instrumentType); + Instrument instrument = queryService.matchOne(template); + + if (instrument == null) { + ConversionException cex = new ConversionException("No instrument for barcode: '" + value + "'"); + cex.setResourceKey("InstrumentBarcodeConverter.NoInstrumentForBarcode"); + throw cex; + } + else if(activeOnly && !instrument.getStatus().equals(InstrumentStatus.ACTIVE)) { + ConversionException cex = new ConversionException("Not an active instrument: '" + value + "'"); + cex.setResourceKey("InstrumentBarcodeConverter.NotAnActiveInstrument"); + throw cex; + } + + return instrument; + } + + public String convertToString(Object value, Locale locale) { + if(value == null) return null; + else + return ((Instrument) value).getBarcode(); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentInputParameterPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentInputParameterPanel.java index c8fb82f39..8639c44c0 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentInputParameterPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentInputParameterPanel.java @@ -1,288 +1,297 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.FormComponentLabel; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.Radio; -import org.apache.wicket.markup.html.form.RadioGroup; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.list.ListView; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; -import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.obiba.onyx.jade.core.wicket.instrument.validation.IntegrityCheckValidator; -import org.obiba.onyx.util.StringUtil; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; -import org.obiba.onyx.wicket.data.DataField; -import org.obiba.onyx.wicket.model.SpringStringResourceModel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Get the input parameters that requires operator provisionning. - * @author Yannick Marcon - * - */ -public class InstrumentInputParameterPanel extends Panel { - - private static final long serialVersionUID = 3008363510160516288L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(InstrumentInputParameterPanel.class); - - private static final String YES = "Yes"; - - private static final String NO = "No"; - - private static final String DOESNOT_KNOW = "DoesNotKnow"; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private InstrumentService instrumentService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - private List interpretativeRadioGroups = new ArrayList(); - - private List inputRunValueModels = new ArrayList(); - - private boolean observedTitleSet = false; - - public InstrumentInputParameterPanel(String id) { - super(id); - setOutputMarkupId(true); - - InterpretativeParameter template = new InterpretativeParameter(); - template.setInstrument(activeInstrumentRunService.getInstrument()); - template.setType(ParticipantInteractionType.ASKED); - if(queryService.count(template) == 0) { - add(new EmptyPanel("askedInputs")); - } else { - add(new InterpretativeFragment("askedInputs", queryService.match(template), ParticipantInteractionType.ASKED)); - } - - template.setType(ParticipantInteractionType.OBSERVED); - if(queryService.count(template) == 0) { - add(new EmptyPanel("observedInputs")); - } else { - add(new InterpretativeFragment("observedInputs", queryService.match(template), ParticipantInteractionType.OBSERVED)); - } - - Instrument instrument = activeInstrumentRunService.getInstrument(); - List instrumentInputParameters = instrumentService.getInstrumentInputParameter(instrument, false); - - if(instrumentInputParameters.size() == 0) { - add(new EmptyPanel("inputs")); - } else { - add(new InputFragment("inputs", instrumentInputParameters)); - } - } - - public void save() { - saveInterpretativeInstrumentRunValues(); - saveInputInstrumentRunValues(); - } - - private void saveInterpretativeInstrumentRunValues() { - for(RadioGroup rg : interpretativeRadioGroups) { - InterpretativeSelection selection = (InterpretativeSelection) rg.getModelObject(); - InstrumentRunValue runValue = activeInstrumentRunService.getInterpretativeInstrumentRunValue(selection.getParameterName()); - runValue.setData(new Data(DataType.TEXT, selection.getSelectionKey())); - activeInstrumentRunService.update(runValue); - } - } - - private void saveInputInstrumentRunValues() { - for(IModel runValueModel : inputRunValueModels) { - activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); - } - } - - @SuppressWarnings("serial") - private class InterpretativeFragment extends Fragment { - - public InterpretativeFragment(String id, List interpretativeParameters, ParticipantInteractionType type) { - super(id, "interpretativeFragment", InstrumentInputParameterPanel.this); - - if(type.equals(ParticipantInteractionType.ASKED)) { - add(new Label("title", new StringResourceModel("AskParticipantTheFollowingQuestions", InstrumentInputParameterPanel.this, null))); - } else { - observedTitleSet = true; - add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", InstrumentInputParameterPanel.this, null))); - } - - RepeatingView repeat = new RepeatingView("repeat"); - add(repeat); - - for(final InterpretativeParameter param : interpretativeParameters) { - WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); - repeat.add(item); - - item.add(new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description")))); - - Data data = activeInstrumentRunService.getInterpretativeInstrumentRunValue(param.getName()).getData(); - final String defaultDataValue = data != null ? data.getValueAsString() : null; - - // radio group without default selection - final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); - interpretativeRadioGroups.add(radioGroup); - radioGroup.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); - item.add(radioGroup); - ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO, DOESNOT_KNOW })) { - - @Override - protected void populateItem(ListItem listItem) { - final String key = listItem.getModelObjectAsString(); - InterpretativeSelection selection = new InterpretativeSelection(); - selection.setSelectionKey(key); - selection.setParameterName(param.getName()); - - Model selectionModel = new Model(selection); - - if(key.equals(defaultDataValue)) { - radioGroup.setModel(selectionModel); - } - - Radio radio = new Radio("radio", selectionModel); - radio.setLabel(new StringResourceModel(key, InstrumentInputParameterPanel.this, null)); - - FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); - listItem.add(radioLabel); - radioLabel.add(radio); - radioLabel.add(new Label("label", radio.getLabel())); - } - - }.setReuseItems(true); - radioGroup.add(radioList); - radioGroup.setRequired(true); - } - } - - } - - @SuppressWarnings("serial") - private class InterpretativeSelection implements Serializable { - - private String selectionKey; - - private String parameterName; - - public String getSelectionKey() { - return selectionKey; - } - - public void setSelectionKey(String selectionKey) { - this.selectionKey = selectionKey; - } - - public boolean isSelected() { - return selectionKey.equals(YES) || selectionKey.equals(DOESNOT_KNOW); - } - - public String getParameterName() { - return parameterName; - } - - public void setParameterName(String parameterName) { - this.parameterName = parameterName; - } - - } - - @SuppressWarnings("serial") - private class InputFragment extends Fragment { - - public InputFragment(String id, List instrumentInputParameters) { - super(id, "inputFragment", InstrumentInputParameterPanel.this); - - if(instrumentInputParameters.size() == 0 || observedTitleSet) { - add(new EmptyPanel("title")); - } else { - add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", InstrumentInputParameterPanel.this, null))); - } - - RepeatingView repeat = new RepeatingView("repeat"); - add(repeat); - - for(final InstrumentInputParameter param : instrumentInputParameters) { - WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); - repeat.add(item); - - Label label = new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description"))); - item.add(label); - - InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); - final IModel runValueModel = new DetachableEntityModel(queryService, runValue); - inputRunValueModels.add(runValueModel); - - List choices = null; - if(param.getInputSource() instanceof OperatorSource) { - List strChoices = StringUtil.parseCSVString(((OperatorSource) param.getInputSource()).getChoices()); - if(strChoices.size() > 0) { - choices = new ArrayList(); - for(String str : strChoices) { - choices.add(DataBuilder.build(param.getDataType(), str)); - } - } - } - - DataField field; - if(choices != null && choices.size() > 0) { - field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), choices, new IChoiceRenderer() { - - public Object getDisplayValue(Object object) { - Data data = (Data) object; - return new SpringStringResourceModel(data.getValueAsString()).getString(); - } - - public String getIdValue(Object object, int index) { - Data data = (Data) object; - return data.getValueAsString(); - } - - }, param.getMeasurementUnit()); - } else { - field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), param.getMeasurementUnit()); - } - field.setRequired(true); - field.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); - field.add(new AjaxFormComponentUpdatingBehavior("onblur") { - protected void onUpdate(AjaxRequestTarget target) { - activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); - } - }); - IntegrityCheckValidator.addChecks(field, param.getIntegrityChecks()); - item.add(field); - } - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.FormComponentLabel; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.Radio; +import org.apache.wicket.markup.html.form.RadioGroup; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; +import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.obiba.onyx.jade.core.wicket.instrument.validation.IntegrityCheckValidator; +import org.obiba.onyx.util.StringUtil; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; +import org.obiba.onyx.wicket.data.DataField; +import org.obiba.onyx.wicket.model.SpringStringResourceModel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Get the input parameters that requires operator provisionning. + * @author Yannick Marcon + * + */ +public class InstrumentInputParameterPanel extends Panel { + + private static final long serialVersionUID = 3008363510160516288L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(InstrumentInputParameterPanel.class); + + private static final String YES = "Yes"; + + private static final String NO = "No"; + + private static final String DOESNOT_KNOW = "DoesNotKnow"; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private InstrumentService instrumentService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + private List interpretativeRadioGroups = new ArrayList(); + + private List inputRunValueModels = new ArrayList(); + + private boolean observedTitleSet = false; + + public InstrumentInputParameterPanel(String id) { + super(id); + setOutputMarkupId(true); + + InterpretativeParameter template = new InterpretativeParameter(); + template.setInstrument(activeInstrumentRunService.getInstrument()); + template.setType(ParticipantInteractionType.ASKED); + if(queryService.count(template) == 0) { + add(new EmptyPanel("askedInputs")); + } else { + add(new InterpretativeFragment("askedInputs", queryService.match(template), ParticipantInteractionType.ASKED)); + } + + template.setType(ParticipantInteractionType.OBSERVED); + if(queryService.count(template) == 0) { + add(new EmptyPanel("observedInputs")); + } else { + add(new InterpretativeFragment("observedInputs", queryService.match(template), ParticipantInteractionType.OBSERVED)); + } + + Instrument instrument = activeInstrumentRunService.getInstrument(); + List instrumentInputParameters = instrumentService.getInstrumentInputParameter(instrument, false); + + if(instrumentInputParameters.size() == 0) { + add(new EmptyPanel("inputs")); + } else { + add(new InputFragment("inputs", instrumentInputParameters)); + } + } + + public void save() { + saveInterpretativeInstrumentRunValues(); + saveInputInstrumentRunValues(); + } + + private void saveInterpretativeInstrumentRunValues() { + for(RadioGroup rg : interpretativeRadioGroups) { + InterpretativeSelection selection = (InterpretativeSelection) rg.getModelObject(); + InstrumentRunValue runValue = activeInstrumentRunService.getInterpretativeInstrumentRunValue(selection.getParameterName()); + runValue.setData(new Data(DataType.TEXT, selection.getSelectionKey())); + activeInstrumentRunService.update(runValue); + } + } + + private void saveInputInstrumentRunValues() { + for(IModel runValueModel : inputRunValueModels) { + activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); + } + } + + @SuppressWarnings("serial") + private class InterpretativeFragment extends Fragment { + + public InterpretativeFragment(String id, List interpretativeParameters, ParticipantInteractionType type) { + super(id, "interpretativeFragment", InstrumentInputParameterPanel.this); + + if(type.equals(ParticipantInteractionType.ASKED)) { + add(new Label("title", new StringResourceModel("AskParticipantTheFollowingQuestions", InstrumentInputParameterPanel.this, null))); + } else { + observedTitleSet = true; + add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", InstrumentInputParameterPanel.this, null))); + } + + RepeatingView repeat = new RepeatingView("repeat"); + add(repeat); + + for(final InterpretativeParameter param : interpretativeParameters) { + WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); + repeat.add(item); + + item.add(new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description")))); + + Data data = activeInstrumentRunService.getInterpretativeInstrumentRunValue(param.getName()).getData(); + final String defaultDataValue = data != null ? data.getValueAsString() : null; + + // radio group without default selection + final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); + interpretativeRadioGroups.add(radioGroup); + radioGroup.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); + item.add(radioGroup); + ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO, DOESNOT_KNOW })) { + + @Override + protected void populateItem(ListItem listItem) { + final String key = listItem.getModelObjectAsString(); + InterpretativeSelection selection = new InterpretativeSelection(); + selection.setSelectionKey(key); + selection.setParameterName(param.getName()); + + Model selectionModel = new Model(selection); + + if(key.equals(defaultDataValue)) { + radioGroup.setModel(selectionModel); + } + + Radio radio = new Radio("radio", selectionModel); + radio.setLabel(new StringResourceModel(key, InstrumentInputParameterPanel.this, null)); + + FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); + listItem.add(radioLabel); + radioLabel.add(radio); + radioLabel.add(new Label("label", radio.getLabel())); + } + + }.setReuseItems(true); + radioGroup.add(radioList); + radioGroup.setRequired(true); + } + } + + } + + @SuppressWarnings("serial") + private class InterpretativeSelection implements Serializable { + + private String selectionKey; + + private String parameterName; + + public String getSelectionKey() { + return selectionKey; + } + + public void setSelectionKey(String selectionKey) { + this.selectionKey = selectionKey; + } + + public boolean isSelected() { + return selectionKey.equals(YES) || selectionKey.equals(DOESNOT_KNOW); + } + + public String getParameterName() { + return parameterName; + } + + public void setParameterName(String parameterName) { + this.parameterName = parameterName; + } + + } + + @SuppressWarnings("serial") + private class InputFragment extends Fragment { + + public InputFragment(String id, List instrumentInputParameters) { + super(id, "inputFragment", InstrumentInputParameterPanel.this); + + if(instrumentInputParameters.size() == 0 || observedTitleSet) { + add(new EmptyPanel("title")); + } else { + add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", InstrumentInputParameterPanel.this, null))); + } + + RepeatingView repeat = new RepeatingView("repeat"); + add(repeat); + + for(final InstrumentInputParameter param : instrumentInputParameters) { + WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); + repeat.add(item); + + Label label = new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description"))); + item.add(label); + + InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); + final IModel runValueModel = new DetachableEntityModel(queryService, runValue); + inputRunValueModels.add(runValueModel); + + List choices = null; + if(param.getInputSource() instanceof OperatorSource) { + List strChoices = StringUtil.parseCSVString(((OperatorSource) param.getInputSource()).getChoices()); + if(strChoices.size() > 0) { + choices = new ArrayList(); + for(String str : strChoices) { + choices.add(DataBuilder.build(param.getDataType(), str)); + } + } + } + + DataField field; + if(choices != null && choices.size() > 0) { + field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), choices, new IChoiceRenderer() { + + public Object getDisplayValue(Object object) { + Data data = (Data) object; + return new SpringStringResourceModel(data.getValueAsString()).getString(); + } + + public String getIdValue(Object object, int index) { + Data data = (Data) object; + return data.getValueAsString(); + } + + }, param.getMeasurementUnit()); + } else { + field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), param.getMeasurementUnit()); + } + field.setRequired(true); + field.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); + field.add(new AjaxFormComponentUpdatingBehavior("onblur") { + protected void onUpdate(AjaxRequestTarget target) { + activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); + } + }); + IntegrityCheckValidator.addChecks(field, param.getIntegrityChecks()); + item.add(field); + } + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLaunchPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLaunchPanel.java index e273193af..dfc83131e 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLaunchPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLaunchPanel.java @@ -1,145 +1,154 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.link.Link; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; -import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.obiba.onyx.wicket.model.SpringStringResourceModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Get the input parameters that are from read-only sources and give the instructions to the operator: - *
    - *
  • General information with instrument launcher (if available)
  • - *
  • instructions to enter manually captured input parameters (if needed)
  • - *
- * @author Yannick Marcon - * - */ -public abstract class InstrumentLaunchPanel extends Panel { - - private static final long serialVersionUID = 8250439838157103589L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(InstrumentLaunchPanel.class); - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private InputDataSourceVisitor inputDataSourceVisitor; - - @SpringBean - private InstrumentService instrumentService; - - @SpringBean - private InstrumentDescriptorService instrumentDescriptorService; - - @SuppressWarnings("serial") - public InstrumentLaunchPanel(String id) { - super(id); - setOutputMarkupId(true); - - Instrument instrument = activeInstrumentRunService.getInstrument(); - log.info("instrument.name=" + instrument.getName()); - - // general instructions and launcher - add(new Label("general", new StringResourceModel("StartMeasurementWithInstrument", this, new Model(new ValueMap("name=" + instrument.getName()))))); - String instrumentCodeBase = instrumentDescriptorService.getCodeBase(instrument.getBarcode()); - - if(instrumentCodeBase == null) { - log.info("No code base for instrument {}", instrument.getName()); - throw new IllegalArgumentException("No code base found for instrument " + instrument.getName()); - } - - final InstrumentLauncher launcher = new InstrumentLauncher(instrument, instrumentCodeBase); - - add(new Link("start") { - - @Override - public void onClick() { - launcher.launch(); - InstrumentLaunchPanel.this.onInstrumentLaunch(); - } - - }); - - // get the data from not read-only input parameters sources - for(InstrumentInputParameter param : instrumentService.getInstrumentInputParameter(instrument, true)) { - final InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); - runValue.setData(inputDataSourceVisitor.getData(activeInterviewService.getParticipant(), param)); - activeInstrumentRunService.update(runValue); - } - - RepeatingView repeat = new RepeatingView("repeat"); - add(repeat); - - // get all the input run values that requires manual capture - InstrumentInputParameter template = new InstrumentInputParameter(); - template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); - template.setInstrument(instrument); - - if(queryService.count(template) > 0) { - add(new Label("instructions", new StringResourceModel("Instructions", InstrumentLaunchPanel.this, null))); - } else { - add(new EmptyPanel("instructions")); - } - - for(final InstrumentInputParameter param : queryService.match(template)) { - WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); - repeat.add(item); - - // Inject the Spring application context and the user session service - // into the instrument parameter. NOTE: These are dependencies of - // InstrumentParameter.getDescription(). - // param.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); - // param.setUserSessionService(userSessionService); - - item.add(new Label("instruction", new StringResourceModel("TypeTheValueInTheInstrument", InstrumentLaunchPanel.this, new Model() { - public Object getObject() { - InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); - ValueMap map = new ValueMap("description=" + new SpringStringResourceModel(param.getDescription()).getString()); - if(runValue.getData() != null && runValue.getData().getValue() != null) { - map.put("value", new SpringStringResourceModel(runValue.getData().getValueAsString()).getString()); - String unit = param.getMeasurementUnit(); - if(unit == null) { - unit = ""; - } - map.put("unit", unit); - } - return map; - } - }))); - } - - } - - /** - * Called when instrument launcher is clicked. - */ - public abstract void onInstrumentLaunch(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.link.Link; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; +import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.obiba.onyx.wicket.model.SpringStringResourceModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Get the input parameters that are from read-only sources and give the instructions to the operator: + *
    + *
  • General information with instrument launcher (if available)
  • + *
  • instructions to enter manually captured input parameters (if needed)
  • + *
+ * @author Yannick Marcon + * + */ +public abstract class InstrumentLaunchPanel extends Panel { + + private static final long serialVersionUID = 8250439838157103589L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(InstrumentLaunchPanel.class); + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private InputDataSourceVisitor inputDataSourceVisitor; + + @SpringBean + private InstrumentService instrumentService; + + @SpringBean + private InstrumentDescriptorService instrumentDescriptorService; + + @SuppressWarnings("serial") + public InstrumentLaunchPanel(String id) { + super(id); + setOutputMarkupId(true); + + Instrument instrument = activeInstrumentRunService.getInstrument(); + log.info("instrument.name=" + instrument.getName()); + + // general instructions and launcher + add(new Label("general", new StringResourceModel("StartMeasurementWithInstrument", this, new Model(new ValueMap("name=" + instrument.getName()))))); + String instrumentCodeBase = instrumentDescriptorService.getCodeBase(instrument.getBarcode()); + + if(instrumentCodeBase == null) { + log.info("No code base for instrument {}", instrument.getName()); + throw new IllegalArgumentException("No code base found for instrument " + instrument.getName()); + } + + final InstrumentLauncher launcher = new InstrumentLauncher(instrument, instrumentCodeBase); + + add(new Link("start") { + + @Override + public void onClick() { + launcher.launch(); + InstrumentLaunchPanel.this.onInstrumentLaunch(); + } + + }); + + // get the data from not read-only input parameters sources + for(InstrumentInputParameter param : instrumentService.getInstrumentInputParameter(instrument, true)) { + final InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); + runValue.setData(inputDataSourceVisitor.getData(activeInterviewService.getParticipant(), param)); + activeInstrumentRunService.update(runValue); + } + + RepeatingView repeat = new RepeatingView("repeat"); + add(repeat); + + // get all the input run values that requires manual capture + InstrumentInputParameter template = new InstrumentInputParameter(); + template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); + template.setInstrument(instrument); + + if(queryService.count(template) > 0) { + add(new Label("instructions", new StringResourceModel("Instructions", InstrumentLaunchPanel.this, null))); + } else { + add(new EmptyPanel("instructions")); + } + + for(final InstrumentInputParameter param : queryService.match(template)) { + WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); + repeat.add(item); + + // Inject the Spring application context and the user session service + // into the instrument parameter. NOTE: These are dependencies of + // InstrumentParameter.getDescription(). + // param.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); + // param.setUserSessionService(userSessionService); + + item.add(new Label("instruction", new StringResourceModel("TypeTheValueInTheInstrument", InstrumentLaunchPanel.this, new Model() { + public Object getObject() { + InstrumentRunValue runValue = activeInstrumentRunService.getInputInstrumentRunValue(param.getName()); + ValueMap map = new ValueMap("description=" + new SpringStringResourceModel(param.getDescription()).getString()); + if(runValue.getData() != null && runValue.getData().getValue() != null) { + map.put("value", new SpringStringResourceModel(runValue.getData().getValueAsString()).getString()); + String unit = param.getMeasurementUnit(); + if(unit == null) { + unit = ""; + } + map.put("unit", unit); + } + return map; + } + }))); + } + + } + + /** + * Called when instrument launcher is clicked. + */ + public abstract void onInstrumentLaunch(); + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLauncher.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLauncher.java index 9a09553ae..117869910 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLauncher.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentLauncher.java @@ -1,157 +1,166 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import org.apache.wicket.RequestCycle; -import org.apache.wicket.Resource; -import org.apache.wicket.ResourceReference; -import org.apache.wicket.Session; -import org.apache.wicket.markup.html.WebResource; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.protocol.http.WebRequest; -import org.apache.wicket.request.target.basic.RedirectRequestTarget; -import org.apache.wicket.util.io.Streams; -import org.apache.wicket.util.resource.AbstractResourceStream; -import org.apache.wicket.util.resource.IResourceStream; -import org.apache.wicket.util.resource.ResourceStreamNotFoundException; -import org.apache.wicket.util.string.interpolator.VariableInterpolator; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class InstrumentLauncher implements Serializable { - - private static final long serialVersionUID = 7558426642051575327L; - - private static final Logger log = LoggerFactory.getLogger(InstrumentLauncher.class); - - private Instrument instrument; - - private String instrumentCodeBase; - - public InstrumentLauncher(Instrument instrument, String instrumentCodeBase) { - super(); - this.instrument = instrument; - this.instrumentCodeBase = instrumentCodeBase; - } - - @SuppressWarnings("serial") - public void launch() { - if(instrument != null && instrumentCodeBase != null) { - log.info("launch {} !", instrument.getInstrumentType()); - - ServletContext context = ((WebApplication) RequestCycle.get().getApplication()).getServletContext(); - - log.info("codeBase={}", instrumentCodeBase); - final Properties props = new Properties(); - props.setProperty("org.obiba.onyx.remoting.url", makeUrl("remoting")); - props.setProperty("codebaseUrl", makeUrl(instrumentCodeBase)); - props.setProperty("jSessionId", Session.get().getId()); - props.setProperty("jnlpPath", context.getRealPath(File.separatorChar + instrumentCodeBase + File.separatorChar + "launch.jnlp")); - - log.info("Current language is = {} getDisplayLanguage()", Session.get().getLocale().getDisplayLanguage()); - props.setProperty("locale", Session.get().getLocale().getLanguage()); - - ResourceReference jnlpReference = new ResourceReference(instrumentCodeBase + "_" + Session.get().getId() + "_" + Session.get().getLocale().getLanguage()) { - - protected Resource newResource() { - return new JnlpResource(props); - } - }; - String url = RequestCycle.get().urlFor(jnlpReference).toString(); - log.info("url={}", url); - RequestCycle.get().setRequestTarget(new RedirectRequestTarget(url)); - - } - } - - private class JnlpResource extends WebResource { - - private static final long serialVersionUID = 5200797507230675946L; - - private Properties jnlpProps; - - public JnlpResource(Properties jnlpProps) { - this.jnlpProps = jnlpProps; - setCacheable(false); - } - - @Override - public IResourceStream getResourceStream() { - - String jnlpData; - try { - jnlpData = Streams.readString(new FileInputStream(jnlpProps.getProperty("jnlpPath")), "UTF-8"); - jnlpData = new PropertiesVariableInterpolator(jnlpData, jnlpProps).toString(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - jnlpProps.storeToXML(baos, null, "UTF-8"); - jnlpData = jnlpData.replace("__config__", baos.toString("UTF-8")); - } catch(Exception e) { - throw new RuntimeException(e); - } - log.info("JNLP File: {}", jnlpData); - return new Utf8ByteArrayResourceStream(jnlpData); - } - } - - private String makeUrl(String path) { - WebRequest wr = (WebRequest) RequestCycle.get().getRequest(); - return wr.getHttpServletRequest().getRequestURL().append(path).toString(); - } - - private class PropertiesVariableInterpolator extends VariableInterpolator { - Properties props; - - public PropertiesVariableInterpolator(String string, Properties props) { - super(string); - this.props = props; - } - - @Override - protected String getValue(String variableName) { - return props.getProperty(variableName); - } - } - - private class Utf8ByteArrayResourceStream extends AbstractResourceStream { - - private static final long serialVersionUID = -4446535648749071250L; - - String data; - - InputStream in; - - public Utf8ByteArrayResourceStream(String s) { - data = s; - } - - public void close() throws IOException { - if(in != null) in.close(); - in = null; - } - - public InputStream getInputStream() throws ResourceStreamNotFoundException { - try { - return in = new ByteArrayInputStream(data.getBytes("UTF-8")); - } catch(UnsupportedEncodingException e) { - throw new ResourceStreamNotFoundException(e); - } - } - - @Override - public String getContentType() { - return "application/x-java-jnlp-file"; - } - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.util.Properties; + +import javax.servlet.ServletContext; + +import org.apache.wicket.RequestCycle; +import org.apache.wicket.Resource; +import org.apache.wicket.ResourceReference; +import org.apache.wicket.Session; +import org.apache.wicket.markup.html.WebResource; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.protocol.http.WebRequest; +import org.apache.wicket.request.target.basic.RedirectRequestTarget; +import org.apache.wicket.util.io.Streams; +import org.apache.wicket.util.resource.AbstractResourceStream; +import org.apache.wicket.util.resource.IResourceStream; +import org.apache.wicket.util.resource.ResourceStreamNotFoundException; +import org.apache.wicket.util.string.interpolator.VariableInterpolator; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InstrumentLauncher implements Serializable { + + private static final long serialVersionUID = 7558426642051575327L; + + private static final Logger log = LoggerFactory.getLogger(InstrumentLauncher.class); + + private Instrument instrument; + + private String instrumentCodeBase; + + public InstrumentLauncher(Instrument instrument, String instrumentCodeBase) { + super(); + this.instrument = instrument; + this.instrumentCodeBase = instrumentCodeBase; + } + + @SuppressWarnings("serial") + public void launch() { + if(instrument != null && instrumentCodeBase != null) { + log.info("launch {} !", instrument.getInstrumentType()); + + ServletContext context = ((WebApplication) RequestCycle.get().getApplication()).getServletContext(); + + log.info("codeBase={}", instrumentCodeBase); + final Properties props = new Properties(); + props.setProperty("org.obiba.onyx.remoting.url", makeUrl("remoting")); + props.setProperty("codebaseUrl", makeUrl(instrumentCodeBase)); + props.setProperty("jSessionId", Session.get().getId()); + props.setProperty("jnlpPath", context.getRealPath(File.separatorChar + instrumentCodeBase + File.separatorChar + "launch.jnlp")); + + log.info("Current language is = {} getDisplayLanguage()", Session.get().getLocale().getDisplayLanguage()); + props.setProperty("locale", Session.get().getLocale().getLanguage()); + + ResourceReference jnlpReference = new ResourceReference(instrumentCodeBase + "_" + Session.get().getId() + "_" + Session.get().getLocale().getLanguage()) { + + protected Resource newResource() { + return new JnlpResource(props); + } + }; + String url = RequestCycle.get().urlFor(jnlpReference).toString(); + log.info("url={}", url); + RequestCycle.get().setRequestTarget(new RedirectRequestTarget(url)); + + } + } + + private class JnlpResource extends WebResource { + + private static final long serialVersionUID = 5200797507230675946L; + + private Properties jnlpProps; + + public JnlpResource(Properties jnlpProps) { + this.jnlpProps = jnlpProps; + setCacheable(false); + } + + @Override + public IResourceStream getResourceStream() { + + String jnlpData; + try { + jnlpData = Streams.readString(new FileInputStream(jnlpProps.getProperty("jnlpPath")), "UTF-8"); + jnlpData = new PropertiesVariableInterpolator(jnlpData, jnlpProps).toString(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + jnlpProps.storeToXML(baos, null, "UTF-8"); + jnlpData = jnlpData.replace("__config__", baos.toString("UTF-8")); + } catch(Exception e) { + throw new RuntimeException(e); + } + log.info("JNLP File: {}", jnlpData); + return new Utf8ByteArrayResourceStream(jnlpData); + } + } + + private String makeUrl(String path) { + WebRequest wr = (WebRequest) RequestCycle.get().getRequest(); + return wr.getHttpServletRequest().getRequestURL().append(path).toString(); + } + + private class PropertiesVariableInterpolator extends VariableInterpolator { + Properties props; + + public PropertiesVariableInterpolator(String string, Properties props) { + super(string); + this.props = props; + } + + @Override + protected String getValue(String variableName) { + return props.getProperty(variableName); + } + } + + private class Utf8ByteArrayResourceStream extends AbstractResourceStream { + + private static final long serialVersionUID = -4446535648749071250L; + + String data; + + InputStream in; + + public Utf8ByteArrayResourceStream(String s) { + data = s; + } + + public void close() throws IOException { + if(in != null) in.close(); + in = null; + } + + public InputStream getInputStream() throws ResourceStreamNotFoundException { + try { + return in = new ByteArrayInputStream(data.getBytes("UTF-8")); + } catch(UnsupportedEncodingException e) { + throw new ResourceStreamNotFoundException(e); + } + } + + @Override + public String getContentType() { + return "application/x-java-jnlp-file"; + } + + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentOutputParameterPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentOutputParameterPanel.java index 0f667cd95..a7c59ea46 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentOutputParameterPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentOutputParameterPanel.java @@ -1,90 +1,99 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.validation.IntegrityCheckValidator; -import org.obiba.onyx.wicket.data.DataField; -import org.obiba.onyx.wicket.model.SpringStringResourceModel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class InstrumentOutputParameterPanel extends Panel { - - private static final long serialVersionUID = 3008363510160516288L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(InstrumentOutputParameterPanel.class); - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - private List outputRunValueModels = new ArrayList(); - - @SuppressWarnings("serial") - public InstrumentOutputParameterPanel(String id) { - super(id); - setOutputMarkupId(true); - - InstrumentOutputParameter template = new InstrumentOutputParameter(); - template.setInstrument(activeInstrumentRunService.getInstrument()); - template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); - - if(queryService.count(template) == 0) { - add(new EmptyPanel("manualOutputs")); - } else { - - RepeatingView repeat = new RepeatingView("repeat"); - add(repeat); - - for(final InstrumentOutputParameter param : queryService.match(template)) { - WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); - repeat.add(item); - - Label label = new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description"))); - item.add(label); - - InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); - final IModel runValueModel = new DetachableEntityModel(queryService, runValue); - outputRunValueModels.add(runValueModel); - - DataField field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), param.getMeasurementUnit()); - field.setRequired(true); - field.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); - field.add(new AjaxFormComponentUpdatingBehavior("onblur") { - protected void onUpdate(AjaxRequestTarget target) { - activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); - } - }); - IntegrityCheckValidator.addChecks(field, param.getIntegrityChecks()); - item.add(field); - } - } - } - - public void saveOutputInstrumentRunValues() { - for(IModel runValueModel : outputRunValueModels) { - activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.validation.IntegrityCheckValidator; +import org.obiba.onyx.wicket.data.DataField; +import org.obiba.onyx.wicket.model.SpringStringResourceModel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InstrumentOutputParameterPanel extends Panel { + + private static final long serialVersionUID = 3008363510160516288L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(InstrumentOutputParameterPanel.class); + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + private List outputRunValueModels = new ArrayList(); + + @SuppressWarnings("serial") + public InstrumentOutputParameterPanel(String id) { + super(id); + setOutputMarkupId(true); + + InstrumentOutputParameter template = new InstrumentOutputParameter(); + template.setInstrument(activeInstrumentRunService.getInstrument()); + template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); + + if(queryService.count(template) == 0) { + add(new EmptyPanel("manualOutputs")); + } else { + + RepeatingView repeat = new RepeatingView("repeat"); + add(repeat); + + for(final InstrumentOutputParameter param : queryService.match(template)) { + WebMarkupContainer item = new WebMarkupContainer(repeat.newChildId()); + repeat.add(item); + + Label label = new Label("label", new SpringStringResourceModel(new PropertyModel(param, "description"))); + item.add(label); + + InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); + final IModel runValueModel = new DetachableEntityModel(queryService, runValue); + outputRunValueModels.add(runValueModel); + + DataField field = new DataField("field", new PropertyModel(runValueModel, "data"), runValue.getDataType(), param.getMeasurementUnit()); + field.setRequired(true); + field.setLabel(new SpringStringResourceModel(new PropertyModel(param, "description"))); + field.add(new AjaxFormComponentUpdatingBehavior("onblur") { + protected void onUpdate(AjaxRequestTarget target) { + activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); + } + }); + IntegrityCheckValidator.addChecks(field, param.getIntegrityChecks()); + item.add(field); + } + } + } + + public void saveOutputInstrumentRunValues() { + for(IModel runValueModel : outputRunValueModels) { + activeInstrumentRunService.update((InstrumentRunValue) runValueModel.getObject()); + } + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentSelector.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentSelector.java index a386ea3dd..162495cd6 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentSelector.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/InstrumentSelector.java @@ -1,81 +1,90 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import org.apache.wicket.Application; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.RequiredTextField; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.convert.IConverter; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; - -public class InstrumentSelector extends Panel { - - private static final long serialVersionUID = 3920957095572085598L; - - private Instrument instrument = null; - - @SpringBean - private EntityQueryService queryService; - - @SuppressWarnings("serial") - public InstrumentSelector(String id, IModel instrumentTypeModel) { - super(id, instrumentTypeModel); - - // get only active instruments in this type. - Instrument template = new Instrument(); - template.setInstrumentType((InstrumentType) getModelObject()); - template.setStatus(InstrumentStatus.ACTIVE); - - KeyValueDataPanel selector = new KeyValueDataPanel("selector"); - add(selector); - selector.addRow(new Label(KeyValueDataPanel.getRowKeyId(), new StringResourceModel("InstrumentBarcode", InstrumentSelector.this, null)), new Selector(KeyValueDataPanel.getRowValueId())); - - String barcodes = ""; - for(Instrument inst : queryService.match(template)) { - barcodes += inst.getBarcode() + " "; - } - Label debugField = new Label("values", barcodes); - if(Application.DEVELOPMENT.equalsIgnoreCase(WebApplication.get().getConfigurationType()) == false) { - // Hide the debug field when not in development mode - debugField.setVisible(false); - } - add(debugField); - } - - public Instrument getInstrument() { - return instrument; - } - - public void setInstrument(Instrument instrument) { - this.instrument = instrument; - } - - @SuppressWarnings("serial") - private class Selector extends Fragment { - - public Selector(String id) { - super(id, "selectorFragment", InstrumentSelector.this); - - final TextField tf = new RequiredTextField("field", new PropertyModel(InstrumentSelector.this, "instrument"), Instrument.class) { - @SuppressWarnings("unchecked") - @Override - public IConverter getConverter(Class type) { - return new InstrumentBarcodeConverter(queryService, (InstrumentType) InstrumentSelector.this.getModelObject()); - } - }; - tf.setLabel(new StringResourceModel("InstrumentBarcode", InstrumentSelector.this, null)); - tf.setOutputMarkupId(true); - add(tf); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import org.apache.wicket.Application; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.RequiredTextField; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.convert.IConverter; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; + +public class InstrumentSelector extends Panel { + + private static final long serialVersionUID = 3920957095572085598L; + + private Instrument instrument = null; + + @SpringBean + private EntityQueryService queryService; + + @SuppressWarnings("serial") + public InstrumentSelector(String id, IModel instrumentTypeModel) { + super(id, instrumentTypeModel); + + // get only active instruments in this type. + Instrument template = new Instrument(); + template.setInstrumentType((InstrumentType) getModelObject()); + template.setStatus(InstrumentStatus.ACTIVE); + + KeyValueDataPanel selector = new KeyValueDataPanel("selector"); + add(selector); + selector.addRow(new Label(KeyValueDataPanel.getRowKeyId(), new StringResourceModel("InstrumentBarcode", InstrumentSelector.this, null)), new Selector(KeyValueDataPanel.getRowValueId())); + + String barcodes = ""; + for(Instrument inst : queryService.match(template)) { + barcodes += inst.getBarcode() + " "; + } + Label debugField = new Label("values", barcodes); + if(Application.DEVELOPMENT.equalsIgnoreCase(WebApplication.get().getConfigurationType()) == false) { + // Hide the debug field when not in development mode + debugField.setVisible(false); + } + add(debugField); + } + + public Instrument getInstrument() { + return instrument; + } + + public void setInstrument(Instrument instrument) { + this.instrument = instrument; + } + + @SuppressWarnings("serial") + private class Selector extends Fragment { + + public Selector(String id) { + super(id, "selectorFragment", InstrumentSelector.this); + + final TextField tf = new RequiredTextField("field", new PropertyModel(InstrumentSelector.this, "instrument"), Instrument.class) { + @SuppressWarnings("unchecked") + @Override + public IConverter getConverter(Class type) { + return new InstrumentBarcodeConverter(queryService, (InstrumentType) InstrumentSelector.this.getModelObject()); + } + }; + tf.setLabel(new StringResourceModel("InstrumentBarcode", InstrumentSelector.this, null)); + tf.setOutputMarkupId(true); + add(tf); + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ObservedContraIndicationPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ObservedContraIndicationPanel.java index ef78ffbc3..5f07fed3b 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ObservedContraIndicationPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/ObservedContraIndicationPanel.java @@ -1,183 +1,192 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import java.io.Serializable; -import java.util.Arrays; - -import org.apache.wicket.ajax.AjaxEventBehavior; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.FormComponentLabel; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.Radio; -import org.apache.wicket.markup.html.form.RadioGroup; -import org.apache.wicket.markup.html.form.TextArea; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.list.ListView; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ObservedContraIndicationPanel extends Panel { - - private static final long serialVersionUID = 1839206247478532673L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ObservedContraIndicationPanel.class); - - private static final String YES = "Yes"; - - private static final String NO = "No"; - - private static final String OTHER = "Other"; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean(name = "userSessionService") - private UserSessionService userSessionService; - - private DropDownChoice contraIndicationDropDownChoice; - - private TextArea otherContraIndication; - - private Label otherLabel; - - private ContraIndicationSelection selectionModel; - - @SuppressWarnings("serial") - public ObservedContraIndicationPanel(String id) { - super(id); - setOutputMarkupId(true); - - selectionModel = new ContraIndicationSelection(); - final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); - radioGroup.setLabel(new StringResourceModel("YesNo", this, null)); - add(radioGroup); - ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO })) { - - @Override - protected void populateItem(final ListItem item) { - final String key = item.getModelObjectAsString(); - Radio radio = new Radio("radio", item.getModel()); - radio.add(new AjaxEventBehavior("onchange") { - - @Override - protected void onEvent(AjaxRequestTarget target) { - log.info("onChange={}", key); - boolean yes = key.equals(YES); - radioGroup.setModel(item.getModel()); - selectionModel.setContraIndication(null); - selectionModel.setOtherContraIndication(null); - contraIndicationDropDownChoice.setEnabled(yes); - contraIndicationDropDownChoice.setRequired(yes); - setOtherVisible(false); - target.addComponent(ObservedContraIndicationPanel.this); - } - - }); - radio.setLabel(new StringResourceModel(key, ObservedContraIndicationPanel.this, null)); - - FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); - item.add(radioLabel); - radioLabel.add(radio); - radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); - } - - }.setReuseItems(true); - radioGroup.add(radioList); - radioGroup.setRequired(true); - - ContraIndication template = new ContraIndication(); - template.setType(ParticipantInteractionType.OBSERVED); - template.setInstrument(activeInstrumentRunService.getInstrument()); - - contraIndicationDropDownChoice = new DropDownChoice("ciChoice", new PropertyModel(selectionModel, "contraIndication"), queryService.match(template), new IChoiceRenderer() { - - public Object getDisplayValue(Object object) { - ContraIndication ci = (ContraIndication) object; - - ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); - ci.setUserSessionService(userSessionService); - - return ci.getDescription(); - } - - public String getIdValue(Object object, int index) { - ContraIndication ci = (ContraIndication) object; - return ci.getName(); - } - - }); - contraIndicationDropDownChoice.setOutputMarkupId(true); - contraIndicationDropDownChoice.setLabel(new StringResourceModel("ContraIndicationSelection", this, null)); - contraIndicationDropDownChoice.add(new OnChangeAjaxBehavior() { - - @Override - protected void onUpdate(AjaxRequestTarget target) { - // Clear input. - radioGroup.clearInput(); - - // make sure the right radio is selected - radioGroup.getModel().setObject(selectionModel.getContraIndication() != null ? YES : NO); - - activeInstrumentRunService.setOtherContraIndication(null); - setOtherVisible(selectionModel.getContraIndication() != null && selectionModel.getContraIndication().getName().equals(OTHER)); - target.addComponent(ObservedContraIndicationPanel.this); - } - - }); - add(contraIndicationDropDownChoice); - - add(otherLabel = new Label("otherLabel", new StringResourceModel("IfOtherPleaseSpecify", this, null))); - - otherContraIndication = new TextArea("otherCi", new PropertyModel(selectionModel, "otherContraIndication")); - otherContraIndication.setOutputMarkupId(true); - otherContraIndication.setLabel(new StringResourceModel("OtherContraIndication", this, null)); - add(otherContraIndication); - - setOtherVisible(false); - } - - private void setOtherVisible(boolean visible) { - otherLabel.setVisible(visible); - otherContraIndication.setVisible(visible); - otherContraIndication.setRequired(visible); - } - - @SuppressWarnings("serial") - private class ContraIndicationSelection implements Serializable { - - public String getOtherContraIndication() { - return activeInstrumentRunService.getOtherContraIndication(); - } - - public void setOtherContraIndication(String otherContraIndication) { - activeInstrumentRunService.setOtherContraIndication(otherContraIndication); - } - - public ContraIndication getContraIndication() { - return activeInstrumentRunService.getContraIndication(); - } - - public void setContraIndication(ContraIndication contraIndication) { - activeInstrumentRunService.setContraIndication(contraIndication); - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import java.io.Serializable; +import java.util.Arrays; + +import org.apache.wicket.ajax.AjaxEventBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.FormComponentLabel; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.Radio; +import org.apache.wicket.markup.html.form.RadioGroup; +import org.apache.wicket.markup.html.form.TextArea; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ObservedContraIndicationPanel extends Panel { + + private static final long serialVersionUID = 1839206247478532673L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ObservedContraIndicationPanel.class); + + private static final String YES = "Yes"; + + private static final String NO = "No"; + + private static final String OTHER = "Other"; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean(name = "userSessionService") + private UserSessionService userSessionService; + + private DropDownChoice contraIndicationDropDownChoice; + + private TextArea otherContraIndication; + + private Label otherLabel; + + private ContraIndicationSelection selectionModel; + + @SuppressWarnings("serial") + public ObservedContraIndicationPanel(String id) { + super(id); + setOutputMarkupId(true); + + selectionModel = new ContraIndicationSelection(); + final RadioGroup radioGroup = new RadioGroup("radioGroup", new Model()); + radioGroup.setLabel(new StringResourceModel("YesNo", this, null)); + add(radioGroup); + ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO })) { + + @Override + protected void populateItem(final ListItem item) { + final String key = item.getModelObjectAsString(); + Radio radio = new Radio("radio", item.getModel()); + radio.add(new AjaxEventBehavior("onchange") { + + @Override + protected void onEvent(AjaxRequestTarget target) { + log.info("onChange={}", key); + boolean yes = key.equals(YES); + radioGroup.setModel(item.getModel()); + selectionModel.setContraIndication(null); + selectionModel.setOtherContraIndication(null); + contraIndicationDropDownChoice.setEnabled(yes); + contraIndicationDropDownChoice.setRequired(yes); + setOtherVisible(false); + target.addComponent(ObservedContraIndicationPanel.this); + } + + }); + radio.setLabel(new StringResourceModel(key, ObservedContraIndicationPanel.this, null)); + + FormComponentLabel radioLabel = new FormComponentLabel("radioLabel", radio); + item.add(radioLabel); + radioLabel.add(radio); + radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); + } + + }.setReuseItems(true); + radioGroup.add(radioList); + radioGroup.setRequired(true); + + ContraIndication template = new ContraIndication(); + template.setType(ParticipantInteractionType.OBSERVED); + template.setInstrument(activeInstrumentRunService.getInstrument()); + + contraIndicationDropDownChoice = new DropDownChoice("ciChoice", new PropertyModel(selectionModel, "contraIndication"), queryService.match(template), new IChoiceRenderer() { + + public Object getDisplayValue(Object object) { + ContraIndication ci = (ContraIndication) object; + + ci.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); + ci.setUserSessionService(userSessionService); + + return ci.getDescription(); + } + + public String getIdValue(Object object, int index) { + ContraIndication ci = (ContraIndication) object; + return ci.getName(); + } + + }); + contraIndicationDropDownChoice.setOutputMarkupId(true); + contraIndicationDropDownChoice.setLabel(new StringResourceModel("ContraIndicationSelection", this, null)); + contraIndicationDropDownChoice.add(new OnChangeAjaxBehavior() { + + @Override + protected void onUpdate(AjaxRequestTarget target) { + // Clear input. + radioGroup.clearInput(); + + // make sure the right radio is selected + radioGroup.getModel().setObject(selectionModel.getContraIndication() != null ? YES : NO); + + activeInstrumentRunService.setOtherContraIndication(null); + setOtherVisible(selectionModel.getContraIndication() != null && selectionModel.getContraIndication().getName().equals(OTHER)); + target.addComponent(ObservedContraIndicationPanel.this); + } + + }); + add(contraIndicationDropDownChoice); + + add(otherLabel = new Label("otherLabel", new StringResourceModel("IfOtherPleaseSpecify", this, null))); + + otherContraIndication = new TextArea("otherCi", new PropertyModel(selectionModel, "otherContraIndication")); + otherContraIndication.setOutputMarkupId(true); + otherContraIndication.setLabel(new StringResourceModel("OtherContraIndication", this, null)); + add(otherContraIndication); + + setOtherVisible(false); + } + + private void setOtherVisible(boolean visible) { + otherLabel.setVisible(visible); + otherContraIndication.setVisible(visible); + otherContraIndication.setRequired(visible); + } + + @SuppressWarnings("serial") + private class ContraIndicationSelection implements Serializable { + + public String getOtherContraIndication() { + return activeInstrumentRunService.getOtherContraIndication(); + } + + public void setOtherContraIndication(String otherContraIndication) { + activeInstrumentRunService.setOtherContraIndication(otherContraIndication); + } + + public ContraIndication getContraIndication() { + return activeInstrumentRunService.getContraIndication(); + } + + public void setContraIndication(ContraIndication contraIndication) { + activeInstrumentRunService.setContraIndication(contraIndication); + } + + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/RunValueLabelModel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/RunValueLabelModel.java index 9ff037b87..c952e5c2a 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/RunValueLabelModel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/RunValueLabelModel.java @@ -1,17 +1,26 @@ -package org.obiba.onyx.jade.core.wicket.instrument; - -import org.apache.wicket.model.Model; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; - -public class RunValueLabelModel extends Model { - - private static final long serialVersionUID = 1338477100531673569L; - - public RunValueLabelModel(InstrumentRunValue runValue) { - String unit = runValue.getInstrumentParameter().getMeasurementUnit(); - if(unit == null) unit = ""; - String label = runValue.getValue() == null ? unit : runValue.getData().getValueAsString() + " " + unit; - setObject(label); - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument; + +import org.apache.wicket.model.Model; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; + +public class RunValueLabelModel extends Model { + + private static final long serialVersionUID = 1338477100531673569L; + + public RunValueLabelModel(InstrumentRunValue runValue) { + String unit = runValue.getInstrumentParameter().getMeasurementUnit(); + if(unit == null) unit = ""; + String label = runValue.getValue() == null ? unit : runValue.getData().getValueAsString() + " " + unit; + setObject(label); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/validation/IntegrityCheckValidator.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/validation/IntegrityCheckValidator.java index 9c0fe55f3..54ab09a79 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/validation/IntegrityCheckValidator.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/instrument/validation/IntegrityCheckValidator.java @@ -1,94 +1,103 @@ -package org.obiba.onyx.jade.core.wicket.instrument.validation; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.wicket.Application; -import org.apache.wicket.injection.web.InjectorHolder; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.validation.IErrorMessageSource; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidationError; -import org.apache.wicket.validation.validator.AbstractValidator; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.wicket.data.DataField; - -public class IntegrityCheckValidator extends AbstractValidator { - - private static final long serialVersionUID = 1L; - - private IntegrityCheck integrityCheck; - - @SpringBean - private transient InstrumentRunService instrumentRunService; - - @SpringBean - private transient ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean - private transient UserSessionService userSessionService; - - public IntegrityCheckValidator(IntegrityCheck integrityCheck) { - this.integrityCheck = integrityCheck; - - InjectorHolder.getInjector().inject(this); - } - - // - // AbstractValidator Methods - // - - @Override - protected void onValidate(IValidatable validatable) { - boolean isValid = integrityCheck.checkParameterValue((Data)(validatable.getValue()), instrumentRunService, activeInstrumentRunService); - - if (!isValid) { - integrityCheck.setApplicationContext(((SpringWebApplication)Application.get()).getSpringContextLocator().getSpringContext()); - integrityCheck.setUserSessionService(userSessionService); - - validatable.error(new IntegrityCheckValidationError(integrityCheck)); - } - } - - // - // Methods - // - - /** - * Convenience method for configuring DataField with a - * list of integrity checks. - * - * @param targetField the field - * @param integrityChecks the checks - */ - public static void addChecks(DataField targetField, List integrityChecks) { - for (IntegrityCheck check : integrityChecks) { - if (check.getType().equals(IntegrityCheckType.ERROR)) { - targetField.add(new IntegrityCheckValidator(check)); - } - } - } - - class IntegrityCheckValidationError implements IValidationError, Serializable { - private static final long serialVersionUID = 1L; - - private IntegrityCheck integrityCheck; - - public IntegrityCheckValidationError(IntegrityCheck integrityCheck) { - this.integrityCheck = integrityCheck; - } - - public String getErrorMessage(IErrorMessageSource messageSource) { - return integrityCheck.getDescription(activeInstrumentRunService); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.instrument.validation; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.wicket.Application; +import org.apache.wicket.injection.web.InjectorHolder; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.IErrorMessageSource; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidationError; +import org.apache.wicket.validation.validator.AbstractValidator; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.wicket.data.DataField; + +public class IntegrityCheckValidator extends AbstractValidator { + + private static final long serialVersionUID = 1L; + + private IntegrityCheck integrityCheck; + + @SpringBean + private transient InstrumentRunService instrumentRunService; + + @SpringBean + private transient ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean + private transient UserSessionService userSessionService; + + public IntegrityCheckValidator(IntegrityCheck integrityCheck) { + this.integrityCheck = integrityCheck; + + InjectorHolder.getInjector().inject(this); + } + + // + // AbstractValidator Methods + // + + @Override + protected void onValidate(IValidatable validatable) { + boolean isValid = integrityCheck.checkParameterValue((Data)(validatable.getValue()), instrumentRunService, activeInstrumentRunService); + + if (!isValid) { + integrityCheck.setApplicationContext(((SpringWebApplication)Application.get()).getSpringContextLocator().getSpringContext()); + integrityCheck.setUserSessionService(userSessionService); + + validatable.error(new IntegrityCheckValidationError(integrityCheck)); + } + } + + // + // Methods + // + + /** + * Convenience method for configuring DataField with a + * list of integrity checks. + * + * @param targetField the field + * @param integrityChecks the checks + */ + public static void addChecks(DataField targetField, List integrityChecks) { + for (IntegrityCheck check : integrityChecks) { + if (check.getType().equals(IntegrityCheckType.ERROR)) { + targetField.add(new IntegrityCheckValidator(check)); + } + } + } + + class IntegrityCheckValidationError implements IValidationError, Serializable { + private static final long serialVersionUID = 1L; + + private IntegrityCheck integrityCheck; + + public IntegrityCheckValidationError(IntegrityCheck integrityCheck) { + this.integrityCheck = integrityCheck; + } + + public String getErrorMessage(IErrorMessageSource messageSource) { + return integrityCheck.getDescription(activeInstrumentRunService); + } + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/run/InstrumentRunPanel.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/run/InstrumentRunPanel.java index 87c4aa3a2..47ebd8af7 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/run/InstrumentRunPanel.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/run/InstrumentRunPanel.java @@ -1,167 +1,176 @@ -package org.obiba.onyx.jade.core.wicket.run; - -import java.util.List; - -import org.apache.wicket.Component; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.wicket.model.SpringStringResourceModel; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; - -public class InstrumentRunPanel extends Panel { - - private static final long serialVersionUID = -3652647014649095945L; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean - private InstrumentRunService instrumentRunService; - - @SpringBean - private InstrumentService instrumentService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - /** - * Build the panel with the current instrument run. - * @param id - */ - public InstrumentRunPanel(String id) { - super(id); - - InstrumentRun run = activeInstrumentRunService.getInstrumentRun(); - if(run == null) { - throw new IllegalStateException("No instrument run in session."); - } - - setModel(new DetachableEntityModel(queryService, run)); - - build(); - } - - /** - * Build the panel with the last completed run for the given instrument type. - * @param id - * @param instrumentTypeModel - */ - public InstrumentRunPanel(String id, IModel instrumentTypeModel) { - super(id); - - InstrumentRun run = instrumentRunService.getLastCompletedInstrumentRun(activeInterviewService.getParticipant(), (InstrumentType) instrumentTypeModel.getObject()); - if(run == null) { - throw new IllegalStateException("No instrument run in session."); - } - - setModel(new DetachableEntityModel(queryService, run)); - - build(); - } - - private void build() { - InstrumentRun run = (InstrumentRun) InstrumentRunPanel.this.getModelObject(); - - KeyValueDataPanel kvPanel = new KeyValueDataPanel("run", new StringResourceModel("RunInfo", this, null)); - add(kvPanel); - kvPanel.addRow(new StringResourceModel("Operator", this, null), new PropertyModel(run, "user.fullName")); - kvPanel.addRow(new StringResourceModel("StartDate", this, null), DateModelUtils.getShortDateTimeModel(new PropertyModel(run, "timeStart"))); - if(run.getTimeEnd() != null) { - kvPanel.addRow(new StringResourceModel("EndDate", this, null), DateModelUtils.getShortDateTimeModel(new PropertyModel(run, "timeEnd"))); - } - - boolean isInteractive = instrumentService.isInteractiveInstrument(run.getInstrument()); - - InterpretativeParameter interpretative = new InterpretativeParameter(); - interpretative.setInstrument(run.getInstrument()); - - if(queryService.count(interpretative) > 0) { - add(getKeyValueDataPanel("interpretatives", new StringResourceModel("Interpretatives", this, null), queryService.match(interpretative))); - } else { - add(new EmptyPanel("interpretatives")); - } - - InstrumentInputParameter input = new InstrumentInputParameter(); - input.setInstrument(run.getInstrument()); - - if(queryService.count(input) > 0) { - String key = isInteractive ? "InstrumentInputs" : "OperatorInputs"; - add(getKeyValueDataPanel("inputs", new StringResourceModel(key, this, null), queryService.match(input))); - } else { - add(new EmptyPanel("inputs")); - } - - InstrumentOutputParameter output = new InstrumentOutputParameter(); - output.setInstrument(run.getInstrument()); - - if(queryService.count(output) > 0) { - String key = isInteractive ? "InstrumentOutputs" : "OperatorOutputs"; - add(getKeyValueDataPanel("outputs", new StringResourceModel(key, this, null), queryService.match(output))); - } else { - add(new EmptyPanel("outputs")); - } - } - - @SuppressWarnings("unchecked") - private Component getKeyValueDataPanel(String id, IModel titleModel, List parameters) { - - KeyValueDataPanel kvPanel = new KeyValueDataPanel(id, titleModel); - add(kvPanel); - - InstrumentRun run = (InstrumentRun) getModelObject(); - for(Object parameter : parameters) { - InstrumentParameter param = (InstrumentParameter) parameter; - InstrumentRunValue runValue = run.getInstrumentRunValue(param); - - // do not show COMPUTED values or misssing values - if(runValue != null && !runValue.getCaptureMethod().equals(InstrumentParameterCaptureMethod.COMPUTED)) { - - Label label = new Label(KeyValueDataPanel.getRowKeyId(), new SpringStringResourceModel(new PropertyModel(param, "description"))); - - Data data = runValue.getData(); - Label value; - if(data != null && data.getValue() != null) { - if(param instanceof InterpretativeParameter) { - value = new Label(KeyValueDataPanel.getRowValueId(), new StringResourceModel(data.getValueAsString(), this, null)); - } else { - String unit = param.getMeasurementUnit(); - if(unit == null) { - unit = ""; - } - value = new Label(KeyValueDataPanel.getRowValueId(), new SpringStringResourceModel(data.getValueAsString()).getString() + " " + unit); - } - } else { - value = new Label(KeyValueDataPanel.getRowValueId()); - } - - kvPanel.addRow(label, value); - } - } - - return kvPanel; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.run; + +import java.util.List; + +import org.apache.wicket.Component; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.wicket.model.SpringStringResourceModel; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; + +public class InstrumentRunPanel extends Panel { + + private static final long serialVersionUID = -3652647014649095945L; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean + private InstrumentRunService instrumentRunService; + + @SpringBean + private InstrumentService instrumentService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + /** + * Build the panel with the current instrument run. + * @param id + */ + public InstrumentRunPanel(String id) { + super(id); + + InstrumentRun run = activeInstrumentRunService.getInstrumentRun(); + if(run == null) { + throw new IllegalStateException("No instrument run in session."); + } + + setModel(new DetachableEntityModel(queryService, run)); + + build(); + } + + /** + * Build the panel with the last completed run for the given instrument type. + * @param id + * @param instrumentTypeModel + */ + public InstrumentRunPanel(String id, IModel instrumentTypeModel) { + super(id); + + InstrumentRun run = instrumentRunService.getLastCompletedInstrumentRun(activeInterviewService.getParticipant(), (InstrumentType) instrumentTypeModel.getObject()); + if(run == null) { + throw new IllegalStateException("No instrument run in session."); + } + + setModel(new DetachableEntityModel(queryService, run)); + + build(); + } + + private void build() { + InstrumentRun run = (InstrumentRun) InstrumentRunPanel.this.getModelObject(); + + KeyValueDataPanel kvPanel = new KeyValueDataPanel("run", new StringResourceModel("RunInfo", this, null)); + add(kvPanel); + kvPanel.addRow(new StringResourceModel("Operator", this, null), new PropertyModel(run, "user.fullName")); + kvPanel.addRow(new StringResourceModel("StartDate", this, null), DateModelUtils.getShortDateTimeModel(new PropertyModel(run, "timeStart"))); + if(run.getTimeEnd() != null) { + kvPanel.addRow(new StringResourceModel("EndDate", this, null), DateModelUtils.getShortDateTimeModel(new PropertyModel(run, "timeEnd"))); + } + + boolean isInteractive = instrumentService.isInteractiveInstrument(run.getInstrument()); + + InterpretativeParameter interpretative = new InterpretativeParameter(); + interpretative.setInstrument(run.getInstrument()); + + if(queryService.count(interpretative) > 0) { + add(getKeyValueDataPanel("interpretatives", new StringResourceModel("Interpretatives", this, null), queryService.match(interpretative))); + } else { + add(new EmptyPanel("interpretatives")); + } + + InstrumentInputParameter input = new InstrumentInputParameter(); + input.setInstrument(run.getInstrument()); + + if(queryService.count(input) > 0) { + String key = isInteractive ? "InstrumentInputs" : "OperatorInputs"; + add(getKeyValueDataPanel("inputs", new StringResourceModel(key, this, null), queryService.match(input))); + } else { + add(new EmptyPanel("inputs")); + } + + InstrumentOutputParameter output = new InstrumentOutputParameter(); + output.setInstrument(run.getInstrument()); + + if(queryService.count(output) > 0) { + String key = isInteractive ? "InstrumentOutputs" : "OperatorOutputs"; + add(getKeyValueDataPanel("outputs", new StringResourceModel(key, this, null), queryService.match(output))); + } else { + add(new EmptyPanel("outputs")); + } + } + + @SuppressWarnings("unchecked") + private Component getKeyValueDataPanel(String id, IModel titleModel, List parameters) { + + KeyValueDataPanel kvPanel = new KeyValueDataPanel(id, titleModel); + add(kvPanel); + + InstrumentRun run = (InstrumentRun) getModelObject(); + for(Object parameter : parameters) { + InstrumentParameter param = (InstrumentParameter) parameter; + InstrumentRunValue runValue = run.getInstrumentRunValue(param); + + // do not show COMPUTED values or misssing values + if(runValue != null && !runValue.getCaptureMethod().equals(InstrumentParameterCaptureMethod.COMPUTED)) { + + Label label = new Label(KeyValueDataPanel.getRowKeyId(), new SpringStringResourceModel(new PropertyModel(param, "description"))); + + Data data = runValue.getData(); + Label value; + if(data != null && data.getValue() != null) { + if(param instanceof InterpretativeParameter) { + value = new Label(KeyValueDataPanel.getRowValueId(), new StringResourceModel(data.getValueAsString(), this, null)); + } else { + String unit = param.getMeasurementUnit(); + if(unit == null) { + unit = ""; + } + value = new Label(KeyValueDataPanel.getRowValueId(), new SpringStringResourceModel(data.getValueAsString()).getString() + " " + unit); + } + } else { + value = new Label(KeyValueDataPanel.getRowValueId()); + } + + kvPanel.addRow(label, value); + } + } + + return kvPanel; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/seed/JadeDatabaseSeed.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/seed/JadeDatabaseSeed.java index 66bf41e1a..0313b783c 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/seed/JadeDatabaseSeed.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/seed/JadeDatabaseSeed.java @@ -1,154 +1,163 @@ -package org.obiba.onyx.jade.core.wicket.seed; - -import java.io.IOException; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.wicket.protocol.http.WebApplication; -import org.obiba.core.service.PersistenceManager; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.FixedSource; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; -import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; -import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; -import org.obiba.onyx.jade.core.domain.instrument.validation.EqualsParameterCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.EqualsValueCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.ParameterSpreadCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.RangeCheck; -import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -import com.thoughtworks.xstream.XStream; - -public class JadeDatabaseSeed extends XstreamResourceDatabaseSeed { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private PersistenceManager persistenceManager; - - private InstrumentService instrumentService; - - private InstrumentDescriptorService instrumentDescriptorService; - - private boolean toPersist = false; - - public void setPersistenceManager(PersistenceManager persistenceManager) { - this.persistenceManager = persistenceManager; - } - - public void setInstrumentService(InstrumentService instrumentService) { - this.instrumentService = instrumentService; - } - - public InstrumentDescriptorService getInstrumentDescriptorService() { - return instrumentDescriptorService; - } - - public void setInstrumentDescriptorService(InstrumentDescriptorService instrumentDescriptorService) { - this.instrumentDescriptorService = instrumentDescriptorService; - } - - @SuppressWarnings("unchecked") - @Override - protected void handleXstreamResult(Resource resource, Object result) { - if(result != null && result instanceof List) { - List objects = (List) result; - - Set inputParameterNames = new HashSet(10); - Set outputParameterNames = new HashSet(10); - for(Object entity : objects) { - - if(entity instanceof Instrument) { - Instrument instrument = (Instrument) entity; - InstrumentType type = instrumentService.getInstrumentType(instrument.getInstrumentType().getName()); - instrument.setInstrumentType(type); - // find code base: - // resource is in ...//lib/instrument-descriptor.xml - - try { - String codeBase = resource.getFile().getParentFile().getParentFile().getName() + "/" + resource.getFile().getParentFile().getName(); - log.info("Seeding instrument descriptor service with instrument {} code base {}", instrument.getBarcode(), codeBase); - instrumentDescriptorService.setCodeBase(instrument.getBarcode(), codeBase); - } catch(IOException cannotFindResource) { - log.error("Cannot find resource : " + resource.getDescription()); - throw new RuntimeException(cannotFindResource); - } - - } else if(entity instanceof OutputParameterSource) { - OutputParameterSource source = (OutputParameterSource) entity; - InstrumentType type = instrumentService.getInstrumentType(source.getInstrumentType().getName()); - source.setInstrumentType(type); - } else if(entity instanceof InstrumentParameter) { - InstrumentParameter parameter = (InstrumentParameter) entity; - - String type; - Set names; - if(entity instanceof InstrumentInputParameter) { - type = "input"; - names = inputParameterNames; - } else { - type = "output"; - names = outputParameterNames; - } - - // Add the name to the set. If the Set already contains the name, throw an exception describing the problem. - // if(names.add(parameter.getName()) == false) { - // log.error("The instrument descriptor {} contains multiple {} parameters with name {}. Instrument parameters - // must have a unique name for within its instrument.", new Object[] { resource.getDescription(), type, - // parameter.getName() }); - // throw new IllegalStateException("The instrument descriptor " + resource.getDescription() + " contains - // multiple " + type + " parameters with name " + parameter.getName() + ". Instrument parameters must have a - // unique name for within its instrument."); - // } - } - - if(toPersist) { - log.info("Seeding database from [" + resource + "] with entity {} of type {}", entity, entity.getClass().getSimpleName()); - persistenceManager.save(entity); - } - } - } - } - - @Override - protected boolean shouldSeed(WebApplication application) { - toPersist = (persistenceManager.list(InstrumentType.class).size() == 0); - // read the seeding file but optionnaly persist entity (always need to seed instrument descriptor service) - return true; - } - - @Override - protected void initializeXstream(XStream xstream) { - log.info("initializeXstream"); - super.initializeXstream(xstream); - xstream.alias("instrumentType", InstrumentType.class); - xstream.alias("instrument", Instrument.class); - xstream.alias("contraIndication", ContraIndication.class); - xstream.alias("interpretative", InterpretativeParameter.class); - xstream.alias("input", InstrumentInputParameter.class); - xstream.alias("output", InstrumentOutputParameter.class); - xstream.alias("computedOutput", InstrumentComputedOutputParameter.class); - xstream.alias("fixedSource", FixedSource.class); - xstream.alias("participantPropertySource", ParticipantPropertySource.class); - xstream.alias("outputParameterSource", OutputParameterSource.class); - xstream.alias("multipleOutputParameterSource", MultipleOutputParameterSource.class); - xstream.alias("operatorSource", OperatorSource.class); - xstream.alias("equalsValueCheck", EqualsValueCheck.class); - xstream.alias("equalsParameterCheck", EqualsParameterCheck.class); - xstream.alias("rangeCheck", RangeCheck.class); - xstream.alias("parameterSpreadCheck", ParameterSpreadCheck.class); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.seed; + +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.wicket.protocol.http.WebApplication; +import org.obiba.core.service.PersistenceManager; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.FixedSource; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentComputedOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; +import org.obiba.onyx.jade.core.domain.instrument.MultipleOutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.OperatorSource; +import org.obiba.onyx.jade.core.domain.instrument.OutputParameterSource; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantPropertySource; +import org.obiba.onyx.jade.core.domain.instrument.validation.EqualsParameterCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.EqualsValueCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.ParameterSpreadCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.RangeCheck; +import org.obiba.onyx.jade.core.service.InstrumentDescriptorService; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.Resource; + +import com.thoughtworks.xstream.XStream; + +public class JadeDatabaseSeed extends XstreamResourceDatabaseSeed { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + private PersistenceManager persistenceManager; + + private InstrumentService instrumentService; + + private InstrumentDescriptorService instrumentDescriptorService; + + private boolean toPersist = false; + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + public void setInstrumentService(InstrumentService instrumentService) { + this.instrumentService = instrumentService; + } + + public InstrumentDescriptorService getInstrumentDescriptorService() { + return instrumentDescriptorService; + } + + public void setInstrumentDescriptorService(InstrumentDescriptorService instrumentDescriptorService) { + this.instrumentDescriptorService = instrumentDescriptorService; + } + + @SuppressWarnings("unchecked") + @Override + protected void handleXstreamResult(Resource resource, Object result) { + if(result != null && result instanceof List) { + List objects = (List) result; + + Set inputParameterNames = new HashSet(10); + Set outputParameterNames = new HashSet(10); + for(Object entity : objects) { + + if(entity instanceof Instrument) { + Instrument instrument = (Instrument) entity; + InstrumentType type = instrumentService.getInstrumentType(instrument.getInstrumentType().getName()); + instrument.setInstrumentType(type); + // find code base: + // resource is in ...//lib/instrument-descriptor.xml + + try { + String codeBase = resource.getFile().getParentFile().getParentFile().getName() + "/" + resource.getFile().getParentFile().getName(); + log.info("Seeding instrument descriptor service with instrument {} code base {}", instrument.getBarcode(), codeBase); + instrumentDescriptorService.setCodeBase(instrument.getBarcode(), codeBase); + } catch(IOException cannotFindResource) { + log.error("Cannot find resource : " + resource.getDescription()); + throw new RuntimeException(cannotFindResource); + } + + } else if(entity instanceof OutputParameterSource) { + OutputParameterSource source = (OutputParameterSource) entity; + InstrumentType type = instrumentService.getInstrumentType(source.getInstrumentType().getName()); + source.setInstrumentType(type); + } else if(entity instanceof InstrumentParameter) { + InstrumentParameter parameter = (InstrumentParameter) entity; + + String type; + Set names; + if(entity instanceof InstrumentInputParameter) { + type = "input"; + names = inputParameterNames; + } else { + type = "output"; + names = outputParameterNames; + } + + // Add the name to the set. If the Set already contains the name, throw an exception describing the problem. + // if(names.add(parameter.getName()) == false) { + // log.error("The instrument descriptor {} contains multiple {} parameters with name {}. Instrument parameters + // must have a unique name for within its instrument.", new Object[] { resource.getDescription(), type, + // parameter.getName() }); + // throw new IllegalStateException("The instrument descriptor " + resource.getDescription() + " contains + // multiple " + type + " parameters with name " + parameter.getName() + ". Instrument parameters must have a + // unique name for within its instrument."); + // } + } + + if(toPersist) { + log.info("Seeding database from [" + resource + "] with entity {} of type {}", entity, entity.getClass().getSimpleName()); + persistenceManager.save(entity); + } + } + } + } + + @Override + protected boolean shouldSeed(WebApplication application) { + toPersist = (persistenceManager.list(InstrumentType.class).size() == 0); + // read the seeding file but optionnaly persist entity (always need to seed instrument descriptor service) + return true; + } + + @Override + protected void initializeXstream(XStream xstream) { + log.info("initializeXstream"); + super.initializeXstream(xstream); + xstream.alias("instrumentType", InstrumentType.class); + xstream.alias("instrument", Instrument.class); + xstream.alias("contraIndication", ContraIndication.class); + xstream.alias("interpretative", InterpretativeParameter.class); + xstream.alias("input", InstrumentInputParameter.class); + xstream.alias("output", InstrumentOutputParameter.class); + xstream.alias("computedOutput", InstrumentComputedOutputParameter.class); + xstream.alias("fixedSource", FixedSource.class); + xstream.alias("participantPropertySource", ParticipantPropertySource.class); + xstream.alias("outputParameterSource", OutputParameterSource.class); + xstream.alias("multipleOutputParameterSource", MultipleOutputParameterSource.class); + xstream.alias("operatorSource", OperatorSource.class); + xstream.alias("equalsValueCheck", EqualsValueCheck.class); + xstream.alias("equalsParameterCheck", EqualsParameterCheck.class); + xstream.alias("rangeCheck", RangeCheck.class); + xstream.alias("parameterSpreadCheck", ParameterSpreadCheck.class); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AbstractContraIndicationStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AbstractContraIndicationStep.java index 43d13ac3d..f57c82d71 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AbstractContraIndicationStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AbstractContraIndicationStep.java @@ -1,62 +1,71 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Termination Step after contra-indication has been selected. - * - */ -public abstract class AbstractContraIndicationStep extends WizardStepPanel { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(AbstractContraIndicationStep.class); - - @SpringBean - protected ActiveInstrumentRunService activeInstrumentRunService; - - public AbstractContraIndicationStep(String id) { - super(id); - // TODO Auto-generated constructor stub - } - - protected abstract ParticipantInteractionType getParticipantInteractionType(); - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - // exit if a ci is selected - ContraIndication ci = activeInstrumentRunService.getContraIndication(); - if(ci != null && ci.getType().equals(getParticipantInteractionType())) { - WizardStepPanel nextStep = new ContraIndicatedStep(WizardForm.getStepId()); - // no possibility to come back - // nextStep.setPreviousStep(this); - setNextStep(nextStep); - nextStep.setPreviousStep(this); - log.debug("Contra-indicated by {} ({})", ci, activeInstrumentRunService.getOtherContraIndication()); - } - else { - // do it in case of back and forth - ((InstrumentWizardForm)form).setUpWizardFlow(); - } - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(getPreviousStep() != null); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - target.addComponent(form.getFinishLink()); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Termination Step after contra-indication has been selected. + * + */ +public abstract class AbstractContraIndicationStep extends WizardStepPanel { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(AbstractContraIndicationStep.class); + + @SpringBean + protected ActiveInstrumentRunService activeInstrumentRunService; + + public AbstractContraIndicationStep(String id) { + super(id); + // TODO Auto-generated constructor stub + } + + protected abstract ParticipantInteractionType getParticipantInteractionType(); + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + // exit if a ci is selected + ContraIndication ci = activeInstrumentRunService.getContraIndication(); + if(ci != null && ci.getType().equals(getParticipantInteractionType())) { + WizardStepPanel nextStep = new ContraIndicatedStep(WizardForm.getStepId()); + // no possibility to come back + // nextStep.setPreviousStep(this); + setNextStep(nextStep); + nextStep.setPreviousStep(this); + log.debug("Contra-indicated by {} ({})", ci, activeInstrumentRunService.getOtherContraIndication()); + } + else { + // do it in case of back and forth + ((InstrumentWizardForm)form).setUpWizardFlow(); + } + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(getPreviousStep() != null); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + target.addComponent(form.getFinishLink()); + } + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AskedContraIndicationStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AskedContraIndicationStep.java index 8d5fe56ee..b7b648011 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AskedContraIndicationStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/AskedContraIndicationStep.java @@ -1,43 +1,52 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.wicket.instrument.AskedContraIndicationPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; - -/** - * Instrument selection Step. - * - */ -public class AskedContraIndicationStep extends AbstractContraIndicationStep { - - private static final long serialVersionUID = 4489598868219932761L; - - private AskedContraIndicationPanel askedContraIndicationPanel; - - @SuppressWarnings("serial") - public AskedContraIndicationStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label(getTitleId(), new StringResourceModel("AskedContraIndication", this, null))); - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, askedContraIndicationPanel = new AskedContraIndicationPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - askedContraIndicationPanel.saveContraIndicationSelection(); - super.onStepOutNext(form, target); - } - - protected ParticipantInteractionType getParticipantInteractionType() { - return ParticipantInteractionType.ASKED; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.wicket.instrument.AskedContraIndicationPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; + +/** + * Instrument selection Step. + * + */ +public class AskedContraIndicationStep extends AbstractContraIndicationStep { + + private static final long serialVersionUID = 4489598868219932761L; + + private AskedContraIndicationPanel askedContraIndicationPanel; + + @SuppressWarnings("serial") + public AskedContraIndicationStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label(getTitleId(), new StringResourceModel("AskedContraIndication", this, null))); + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, askedContraIndicationPanel = new AskedContraIndicationPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + askedContraIndicationPanel.saveContraIndicationSelection(); + super.onStepOutNext(form, target); + } + + protected ParticipantInteractionType getParticipantInteractionType() { + return ParticipantInteractionType.ASKED; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ConclusionStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ConclusionStep.java index 6c17c24bf..d6c35710c 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ConclusionStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ConclusionStep.java @@ -1,44 +1,53 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.ConclusionPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class ConclusionStep extends WizardStepPanel { - - private static final long serialVersionUID = -2477348071975440201L; - - @SpringBean - protected ActiveInstrumentRunService activeInstrumentRunService; - - public ConclusionStep(String id) { - super(id); - - add(new Label("title", new StringResourceModel("Conclusion", ConclusionStep.this, null))); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getNextLink().setEnabled(false); - form.getPreviousLink().setEnabled(true); - form.getFinishLink().setEnabled(true); - if(target != null) { - target.addComponent(form.getNextLink()); - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getFinishLink()); - } - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.COMPLETED); - setContent(target, new ConclusionPanel(getContentId())); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.ConclusionPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class ConclusionStep extends WizardStepPanel { + + private static final long serialVersionUID = -2477348071975440201L; + + @SpringBean + protected ActiveInstrumentRunService activeInstrumentRunService; + + public ConclusionStep(String id) { + super(id); + + add(new Label("title", new StringResourceModel("Conclusion", ConclusionStep.this, null))); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getNextLink().setEnabled(false); + form.getPreviousLink().setEnabled(true); + form.getFinishLink().setEnabled(true); + if(target != null) { + target.addComponent(form.getNextLink()); + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getFinishLink()); + } + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.COMPLETED); + setContent(target, new ConclusionPanel(getContentId())); + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ContraIndicatedStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ContraIndicatedStep.java index 28de8531a..b1c1d8d9c 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ContraIndicatedStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ContraIndicatedStep.java @@ -1,49 +1,58 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.ContraIndicatedPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -/** - * Termination Step after contra-indication has been selected for this instrument run. No possibility to come back. - * - */ -public class ContraIndicatedStep extends WizardStepPanel { - - private static final long serialVersionUID = 2498999653493497444L; - - @SpringBean - protected ActiveInstrumentRunService activeInstrumentRunService; - - public ContraIndicatedStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label(getTitleId(), new StringResourceModel("InstrumentRunContraIndicated", this, null))); - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.CONTRA_INDICATED); - setContent(target, new ContraIndicatedPanel(getContentId())); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(true); - form.getNextLink().setEnabled(false); - form.getFinishLink().setEnabled(true); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - target.addComponent(form.getFinishLink()); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.ContraIndicatedPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +/** + * Termination Step after contra-indication has been selected for this instrument run. No possibility to come back. + * + */ +public class ContraIndicatedStep extends WizardStepPanel { + + private static final long serialVersionUID = 2498999653493497444L; + + @SpringBean + protected ActiveInstrumentRunService activeInstrumentRunService; + + public ContraIndicatedStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label(getTitleId(), new StringResourceModel("InstrumentRunContraIndicated", this, null))); + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.CONTRA_INDICATED); + setContent(target, new ContraIndicatedPanel(getContentId())); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(true); + form.getNextLink().setEnabled(false); + form.getFinishLink().setEnabled(true); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + target.addComponent(form.getFinishLink()); + } + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InputParametersStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InputParametersStep.java index 8c6bdcf1a..54e1a7912 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InputParametersStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InputParametersStep.java @@ -1,43 +1,52 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.obiba.onyx.jade.core.wicket.instrument.InstrumentInputParameterPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class InputParametersStep extends WizardStepPanel { - - private static final long serialVersionUID = 1L; - - private InstrumentInputParameterPanel instrumentInputParameterPanel; - - public InputParametersStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new EmptyPanel(getTitleId())); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - // No previous step - form.getPreviousLink().setEnabled(true); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, instrumentInputParameterPanel = new InstrumentInputParameterPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - instrumentInputParameterPanel.save(); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.obiba.onyx.jade.core.wicket.instrument.InstrumentInputParameterPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class InputParametersStep extends WizardStepPanel { + + private static final long serialVersionUID = 1L; + + private InstrumentInputParameterPanel instrumentInputParameterPanel; + + public InputParametersStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new EmptyPanel(getTitleId())); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + // No previous step + form.getPreviousLink().setEnabled(true); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, instrumentInputParameterPanel = new InstrumentInputParameterPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + instrumentInputParameterPanel.save(); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentLaunchStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentLaunchStep.java index 72830b531..dde5f6532 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentLaunchStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentLaunchStep.java @@ -1,163 +1,172 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.wicket.Application; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.InstrumentLaunchPanel; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class InstrumentLaunchStep extends WizardStepPanel { - - private static final long serialVersionUID = -2511672064460152210L; - - private static final Logger log = LoggerFactory.getLogger(InstrumentLaunchStep.class); - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean - private UserSessionService userSessionService; - - private boolean launched = false; - - public InstrumentLaunchStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label("title", new StringResourceModel("InstrumentApplicationLaunch", this, null))); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(getPreviousStep() != null); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } - - @SuppressWarnings("serial") - @Override - public void onStepInNext(final WizardForm form, AjaxRequestTarget target) { - setContent(target, new InstrumentLaunchPanel(getContentId()) { - - @Override - public void onInstrumentLaunch() { - log.info("onInstrumentLaunch"); - activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.IN_PROGRESS); - launched = true; - } - - }); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - if(launched) { - if(InstrumentRunStatus.IN_ERROR.equals(activeInstrumentRunService.getInstrumentRunStatus())) { - error(getString("InstrumentApplicationError")); - setNextStep(null); - } else { - InstrumentOutputParameter template = new InstrumentOutputParameter(); - template.setCaptureMethod(InstrumentParameterCaptureMethod.AUTOMATIC); - template.setInstrument(activeInstrumentRunService.getInstrument()); - - List outputParams = queryService.match(template); - - boolean completed = true; - - for(InstrumentOutputParameter param : outputParams) { - InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); - Data data = runValue.getData(); - if(data == null || data.getValue() == null) { - error(getString("NoInstrumentDataSaveThem")); - setNextStep(null); - completed = false; - break; - } - } - - if(completed) { - // Perform each output parameter's integrity checks. - List failedChecks = checkIntegrity(outputParams); - - if (failedChecks.isEmpty()) { - ((InstrumentWizardForm) form).setUpWizardFlow(); - } else { - for (IntegrityCheck failedCheck : failedChecks) { - // Set the integrity check's context and user session service to ensure - // proper localization of the error message. - failedCheck.setApplicationContext(((SpringWebApplication)Application.get()).getSpringContextLocator().getSpringContext()); - failedCheck.setUserSessionService(userSessionService); - - error(failedCheck.getDescription(activeInstrumentRunService)); - } - - setNextStep(null); - } - } - } - - } else { - error(getString("InstrumentApplicationMustBeStarted")); - setNextStep(null); - } - } - - /** - * For each output parameter, performs all integrity checks of type - * ERROR. - * - * @param outputParams output parameters - * @return list of integrity checks that failed (empty list if none) - */ - private List checkIntegrity(List outputParams) { - List failedChecks = new ArrayList(); - - for (InstrumentOutputParameter param : outputParams) { - List integrityChecks = param.getIntegrityChecks(); - - for (AbstractIntegrityCheck integrityCheck : integrityChecks) { - // Skip non-ERROR type checks. - if (!integrityCheck.getType().equals(IntegrityCheckType.ERROR)) { - continue; - } - - InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); - Data paramData = (runValue != null) ? runValue.getData() : null; - - if (!integrityCheck.checkParameterValue(paramData, null, activeInstrumentRunService)) { - failedChecks.add(integrityCheck); - break; // stop checking parameter after first failure (but continue checking other parameters!) - } - } - } - - return failedChecks; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.wicket.Application; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.validation.AbstractIntegrityCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.InstrumentLaunchPanel; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InstrumentLaunchStep extends WizardStepPanel { + + private static final long serialVersionUID = -2511672064460152210L; + + private static final Logger log = LoggerFactory.getLogger(InstrumentLaunchStep.class); + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean + private UserSessionService userSessionService; + + private boolean launched = false; + + public InstrumentLaunchStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label("title", new StringResourceModel("InstrumentApplicationLaunch", this, null))); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(getPreviousStep() != null); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } + + @SuppressWarnings("serial") + @Override + public void onStepInNext(final WizardForm form, AjaxRequestTarget target) { + setContent(target, new InstrumentLaunchPanel(getContentId()) { + + @Override + public void onInstrumentLaunch() { + log.info("onInstrumentLaunch"); + activeInstrumentRunService.setInstrumentRunStatus(InstrumentRunStatus.IN_PROGRESS); + launched = true; + } + + }); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + if(launched) { + if(InstrumentRunStatus.IN_ERROR.equals(activeInstrumentRunService.getInstrumentRunStatus())) { + error(getString("InstrumentApplicationError")); + setNextStep(null); + } else { + InstrumentOutputParameter template = new InstrumentOutputParameter(); + template.setCaptureMethod(InstrumentParameterCaptureMethod.AUTOMATIC); + template.setInstrument(activeInstrumentRunService.getInstrument()); + + List outputParams = queryService.match(template); + + boolean completed = true; + + for(InstrumentOutputParameter param : outputParams) { + InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); + Data data = runValue.getData(); + if(data == null || data.getValue() == null) { + error(getString("NoInstrumentDataSaveThem")); + setNextStep(null); + completed = false; + break; + } + } + + if(completed) { + // Perform each output parameter's integrity checks. + List failedChecks = checkIntegrity(outputParams); + + if (failedChecks.isEmpty()) { + ((InstrumentWizardForm) form).setUpWizardFlow(); + } else { + for (IntegrityCheck failedCheck : failedChecks) { + // Set the integrity check's context and user session service to ensure + // proper localization of the error message. + failedCheck.setApplicationContext(((SpringWebApplication)Application.get()).getSpringContextLocator().getSpringContext()); + failedCheck.setUserSessionService(userSessionService); + + error(failedCheck.getDescription(activeInstrumentRunService)); + } + + setNextStep(null); + } + } + } + + } else { + error(getString("InstrumentApplicationMustBeStarted")); + setNextStep(null); + } + } + + /** + * For each output parameter, performs all integrity checks of type + * ERROR. + * + * @param outputParams output parameters + * @return list of integrity checks that failed (empty list if none) + */ + private List checkIntegrity(List outputParams) { + List failedChecks = new ArrayList(); + + for (InstrumentOutputParameter param : outputParams) { + List integrityChecks = param.getIntegrityChecks(); + + for (AbstractIntegrityCheck integrityCheck : integrityChecks) { + // Skip non-ERROR type checks. + if (!integrityCheck.getType().equals(IntegrityCheckType.ERROR)) { + continue; + } + + InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); + Data paramData = (runValue != null) ? runValue.getData() : null; + + if (!integrityCheck.checkParameterValue(paramData, null, activeInstrumentRunService)) { + failedChecks.add(integrityCheck); + break; // stop checking parameter after first failure (but continue checking other parameters!) + } + } + } + + return failedChecks; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentSelectionStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentSelectionStep.java index 599b5e24d..e1d1e9db9 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentSelectionStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentSelectionStep.java @@ -1,70 +1,79 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.InstrumentSelector; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; - -/** - * Instrument selection Step. - * - */ -public class InstrumentSelectionStep extends WizardStepPanel { - - private static final long serialVersionUID = 4489598868219932761L; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - private InstrumentSelector selector; - - @SuppressWarnings("serial") - public InstrumentSelectionStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label(getTitleId(), new StringResourceModel("InstrumentSelection", this, null))); - - add(selector = new InstrumentSelector(getContentId(), new DetachableEntityModel(queryService, activeInstrumentRunService.getInstrumentType()))); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - InstrumentWizardForm instrumentForm = (InstrumentWizardForm) form; - Instrument instrument = selector.getInstrument(); - - if(instrument != null) { - activeInstrumentRunService.start(activeInterviewService.getParticipant(), instrument); - setNextStep(instrumentForm.setUpWizardFlow()); - } else { - setNextStep(null); - } - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - // No previous step - form.getPreviousLink().setEnabled(false); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.InstrumentSelector; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; + +/** + * Instrument selection Step. + * + */ +public class InstrumentSelectionStep extends WizardStepPanel { + + private static final long serialVersionUID = 4489598868219932761L; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + private InstrumentSelector selector; + + @SuppressWarnings("serial") + public InstrumentSelectionStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label(getTitleId(), new StringResourceModel("InstrumentSelection", this, null))); + + add(selector = new InstrumentSelector(getContentId(), new DetachableEntityModel(queryService, activeInstrumentRunService.getInstrumentType()))); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + InstrumentWizardForm instrumentForm = (InstrumentWizardForm) form; + Instrument instrument = selector.getInstrument(); + + if(instrument != null) { + activeInstrumentRunService.start(activeInterviewService.getParticipant(), instrument); + setNextStep(instrumentForm.setUpWizardFlow()); + } else { + setNextStep(null); + } + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + // No previous step + form.getPreviousLink().setEnabled(false); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentWizardForm.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentWizardForm.java index 823e320f8..7a0231156 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentWizardForm.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/InstrumentWizardForm.java @@ -1,217 +1,226 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class InstrumentWizardForm extends WizardForm { - - private static final Logger log = LoggerFactory.getLogger(InstrumentWizardForm.class); - - @SpringBean - private EntityQueryService queryService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean - private InstrumentService instrumentService; - - private WizardStepPanel instrumentSelectionStep; - - private WizardStepPanel observedContraIndicationStep; - - private WizardStepPanel askedContraIndicationStep; - - private WizardStepPanel inputParametersStep; - - private WizardStepPanel instrumentLaunchStep; - - private WizardStepPanel outputParametersStep; - - private WizardStepPanel conclusionStep; - - private WizardStepPanel warningStep; - - public InstrumentWizardForm(String id, IModel instrumentTypeModel) { - super(id); - - activeInstrumentRunService.setInstrumentType((InstrumentType) instrumentTypeModel.getObject()); - - WizardStepPanel startStep = null; - - instrumentSelectionStep = new InstrumentSelectionStep(getStepId()); - observedContraIndicationStep = new ObservedContraIndicationStep(getStepId()); - askedContraIndicationStep = new AskedContraIndicationStep(getStepId()); - inputParametersStep = new InputParametersStep(getStepId()); - instrumentLaunchStep = new InstrumentLaunchStep(getStepId()); - conclusionStep = new ConclusionStep(getStepId()); - warningStep = new WarningsStep(getStepId()); - outputParametersStep = new OutputParametersStep(getStepId(), conclusionStep, warningStep); - - warningStep.setNextStep(conclusionStep); - warningStep.setPreviousStep(outputParametersStep); - - // do we need to select the instrument ? - Instrument template = new Instrument(); - template.setInstrumentType((InstrumentType) instrumentTypeModel.getObject()); - template.setStatus(InstrumentStatus.ACTIVE); - if(queryService.count(template) > 1) { - activeInstrumentRunService.reset(); - startStep = instrumentSelectionStep; - } else { - // pre selected instrument - activeInstrumentRunService.start(activeInterviewService.getParticipant(), queryService.matchOne(template)); - startStep = setUpWizardFlow(); - } - - add(startStep); - startStep.onStepInNext(this, null); - startStep.handleWizardState(this, null); - } - - public WizardStepPanel setUpWizardFlow() { - WizardStepPanel startStep = null; - WizardStepPanel lastStep = null; - - // instrument is not null at this point - Instrument instrument = activeInstrumentRunService.getInstrument(); - if (instrument == null) throw new IllegalStateException("Instrument is not supposed to be null in current active instrument run."); - - // are there observed contra-indications to display ? - ContraIndication ciTemplate = new ContraIndication(); - ciTemplate.setType(ParticipantInteractionType.OBSERVED); - ciTemplate.setInstrument(instrument); - log.info("observed.ci.count={}", queryService.count(ciTemplate)); - if(queryService.count(ciTemplate) > 0) { - if(startStep == null) { - startStep = observedContraIndicationStep; - lastStep = startStep; - } else { - lastStep.setNextStep(observedContraIndicationStep); - observedContraIndicationStep.setPreviousStep(lastStep); - lastStep = observedContraIndicationStep; - } - } - - // are there asked contra-indications to display ? - ciTemplate.setType(ParticipantInteractionType.ASKED); - log.info("asked.ci.count={}", queryService.count(ciTemplate)); - if(queryService.count(ciTemplate) > 0) { - if(startStep == null) { - startStep = askedContraIndicationStep; - lastStep = startStep; - } else { - lastStep.setNextStep(askedContraIndicationStep); - askedContraIndicationStep.setPreviousStep(lastStep); - lastStep = askedContraIndicationStep; - } - } - - // are there input parameters with input source that requires user provisionning ? - // or interpretative questions - InterpretativeParameter template = new InterpretativeParameter(); - template.setInstrument(instrument); - log.info("instrumentInterpretativeParameters.count={}", queryService.count(template)); - log.info("instrumentInputParameters.count={}", instrumentService.countInstrumentInputParameter(instrument, false)); - if(queryService.count(template) > 0 || instrumentService.countInstrumentInputParameter(instrument, false) > 0) { - if(startStep == null) { - startStep = inputParametersStep; - lastStep = startStep; - } else { - lastStep.setNextStep(inputParametersStep); - inputParametersStep.setPreviousStep(lastStep); - lastStep = inputParametersStep; - } - } - - // are there output parameters that are to be captured automatically from instrument (i.e. requires instrument - // launch) ? - log.info("instrument.isInteractive={}", instrumentService.isInteractiveInstrument(instrument)); - if(instrumentService.isInteractiveInstrument(instrument)) { - if(startStep == null) { - startStep = instrumentLaunchStep; - lastStep = startStep; - } else { - lastStep.setNextStep(instrumentLaunchStep); - instrumentLaunchStep.setPreviousStep(lastStep); - lastStep = instrumentLaunchStep; - } - } - - // are there output parameters that are to be captured manually from instrument ? - InstrumentOutputParameter opTemplate = new InstrumentOutputParameter(); - opTemplate.setInstrument(instrument); - opTemplate.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); - log.info("instrumentOutputParameters.MANUAL.count={}", queryService.count(opTemplate)); - if(queryService.count(opTemplate) > 0) { - if(startStep == null) { - startStep = outputParametersStep; - lastStep = startStep; - } else { - lastStep.setNextStep(outputParametersStep); - outputParametersStep.setPreviousStep(lastStep); - lastStep = outputParametersStep; - } - } - - // validation: final step - if(startStep == null) { - startStep = conclusionStep; - lastStep = startStep; - } else { - lastStep.setNextStep(conclusionStep); - conclusionStep.setPreviousStep(lastStep); - lastStep = conclusionStep; - } - - return startStep; - } - - public WizardStepPanel getInstrumentSelectionStep() { - return instrumentSelectionStep; - } - - public WizardStepPanel getObservedContraIndicationStep() { - return observedContraIndicationStep; - } - - public WizardStepPanel getAskedContraIndicationStep() { - return askedContraIndicationStep; - } - - public WizardStepPanel getInputParametersStep() { - return inputParametersStep; - } - - public WizardStepPanel getInstrumentLaunchStep() { - return instrumentLaunchStep; - } - - public WizardStepPanel getOutputParametersStep() { - return outputParametersStep; - } - - public WizardStepPanel getConclusionStep() { - return conclusionStep; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentStatus; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.instrument.InterpretativeParameter; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class InstrumentWizardForm extends WizardForm { + + private static final Logger log = LoggerFactory.getLogger(InstrumentWizardForm.class); + + @SpringBean + private EntityQueryService queryService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean + private InstrumentService instrumentService; + + private WizardStepPanel instrumentSelectionStep; + + private WizardStepPanel observedContraIndicationStep; + + private WizardStepPanel askedContraIndicationStep; + + private WizardStepPanel inputParametersStep; + + private WizardStepPanel instrumentLaunchStep; + + private WizardStepPanel outputParametersStep; + + private WizardStepPanel conclusionStep; + + private WizardStepPanel warningStep; + + public InstrumentWizardForm(String id, IModel instrumentTypeModel) { + super(id); + + activeInstrumentRunService.setInstrumentType((InstrumentType) instrumentTypeModel.getObject()); + + WizardStepPanel startStep = null; + + instrumentSelectionStep = new InstrumentSelectionStep(getStepId()); + observedContraIndicationStep = new ObservedContraIndicationStep(getStepId()); + askedContraIndicationStep = new AskedContraIndicationStep(getStepId()); + inputParametersStep = new InputParametersStep(getStepId()); + instrumentLaunchStep = new InstrumentLaunchStep(getStepId()); + conclusionStep = new ConclusionStep(getStepId()); + warningStep = new WarningsStep(getStepId()); + outputParametersStep = new OutputParametersStep(getStepId(), conclusionStep, warningStep); + + warningStep.setNextStep(conclusionStep); + warningStep.setPreviousStep(outputParametersStep); + + // do we need to select the instrument ? + Instrument template = new Instrument(); + template.setInstrumentType((InstrumentType) instrumentTypeModel.getObject()); + template.setStatus(InstrumentStatus.ACTIVE); + if(queryService.count(template) > 1) { + activeInstrumentRunService.reset(); + startStep = instrumentSelectionStep; + } else { + // pre selected instrument + activeInstrumentRunService.start(activeInterviewService.getParticipant(), queryService.matchOne(template)); + startStep = setUpWizardFlow(); + } + + add(startStep); + startStep.onStepInNext(this, null); + startStep.handleWizardState(this, null); + } + + public WizardStepPanel setUpWizardFlow() { + WizardStepPanel startStep = null; + WizardStepPanel lastStep = null; + + // instrument is not null at this point + Instrument instrument = activeInstrumentRunService.getInstrument(); + if (instrument == null) throw new IllegalStateException("Instrument is not supposed to be null in current active instrument run."); + + // are there observed contra-indications to display ? + ContraIndication ciTemplate = new ContraIndication(); + ciTemplate.setType(ParticipantInteractionType.OBSERVED); + ciTemplate.setInstrument(instrument); + log.info("observed.ci.count={}", queryService.count(ciTemplate)); + if(queryService.count(ciTemplate) > 0) { + if(startStep == null) { + startStep = observedContraIndicationStep; + lastStep = startStep; + } else { + lastStep.setNextStep(observedContraIndicationStep); + observedContraIndicationStep.setPreviousStep(lastStep); + lastStep = observedContraIndicationStep; + } + } + + // are there asked contra-indications to display ? + ciTemplate.setType(ParticipantInteractionType.ASKED); + log.info("asked.ci.count={}", queryService.count(ciTemplate)); + if(queryService.count(ciTemplate) > 0) { + if(startStep == null) { + startStep = askedContraIndicationStep; + lastStep = startStep; + } else { + lastStep.setNextStep(askedContraIndicationStep); + askedContraIndicationStep.setPreviousStep(lastStep); + lastStep = askedContraIndicationStep; + } + } + + // are there input parameters with input source that requires user provisionning ? + // or interpretative questions + InterpretativeParameter template = new InterpretativeParameter(); + template.setInstrument(instrument); + log.info("instrumentInterpretativeParameters.count={}", queryService.count(template)); + log.info("instrumentInputParameters.count={}", instrumentService.countInstrumentInputParameter(instrument, false)); + if(queryService.count(template) > 0 || instrumentService.countInstrumentInputParameter(instrument, false) > 0) { + if(startStep == null) { + startStep = inputParametersStep; + lastStep = startStep; + } else { + lastStep.setNextStep(inputParametersStep); + inputParametersStep.setPreviousStep(lastStep); + lastStep = inputParametersStep; + } + } + + // are there output parameters that are to be captured automatically from instrument (i.e. requires instrument + // launch) ? + log.info("instrument.isInteractive={}", instrumentService.isInteractiveInstrument(instrument)); + if(instrumentService.isInteractiveInstrument(instrument)) { + if(startStep == null) { + startStep = instrumentLaunchStep; + lastStep = startStep; + } else { + lastStep.setNextStep(instrumentLaunchStep); + instrumentLaunchStep.setPreviousStep(lastStep); + lastStep = instrumentLaunchStep; + } + } + + // are there output parameters that are to be captured manually from instrument ? + InstrumentOutputParameter opTemplate = new InstrumentOutputParameter(); + opTemplate.setInstrument(instrument); + opTemplate.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); + log.info("instrumentOutputParameters.MANUAL.count={}", queryService.count(opTemplate)); + if(queryService.count(opTemplate) > 0) { + if(startStep == null) { + startStep = outputParametersStep; + lastStep = startStep; + } else { + lastStep.setNextStep(outputParametersStep); + outputParametersStep.setPreviousStep(lastStep); + lastStep = outputParametersStep; + } + } + + // validation: final step + if(startStep == null) { + startStep = conclusionStep; + lastStep = startStep; + } else { + lastStep.setNextStep(conclusionStep); + conclusionStep.setPreviousStep(lastStep); + lastStep = conclusionStep; + } + + return startStep; + } + + public WizardStepPanel getInstrumentSelectionStep() { + return instrumentSelectionStep; + } + + public WizardStepPanel getObservedContraIndicationStep() { + return observedContraIndicationStep; + } + + public WizardStepPanel getAskedContraIndicationStep() { + return askedContraIndicationStep; + } + + public WizardStepPanel getInputParametersStep() { + return inputParametersStep; + } + + public WizardStepPanel getInstrumentLaunchStep() { + return instrumentLaunchStep; + } + + public WizardStepPanel getOutputParametersStep() { + return outputParametersStep; + } + + public WizardStepPanel getConclusionStep() { + return conclusionStep; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ObservedContraIndicationStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ObservedContraIndicationStep.java index 03dae7213..2db513033 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ObservedContraIndicationStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/ObservedContraIndicationStep.java @@ -1,35 +1,44 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; -import org.obiba.onyx.jade.core.wicket.instrument.ObservedContraIndicationPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; - -/** - * Instrument selection Step. - * - */ -public class ObservedContraIndicationStep extends AbstractContraIndicationStep { - - private static final long serialVersionUID = 4489598868219932761L; - - @SuppressWarnings("serial") - public ObservedContraIndicationStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label(getTitleId(), new StringResourceModel("ObservedContraIndication", this, null))); - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, new ObservedContraIndicationPanel(getContentId())); - } - - protected ParticipantInteractionType getParticipantInteractionType() { - return ParticipantInteractionType.OBSERVED; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.jade.core.domain.instrument.ParticipantInteractionType; +import org.obiba.onyx.jade.core.wicket.instrument.ObservedContraIndicationPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; + +/** + * Instrument selection Step. + * + */ +public class ObservedContraIndicationStep extends AbstractContraIndicationStep { + + private static final long serialVersionUID = 4489598868219932761L; + + @SuppressWarnings("serial") + public ObservedContraIndicationStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label(getTitleId(), new StringResourceModel("ObservedContraIndication", this, null))); + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, new ObservedContraIndicationPanel(getContentId())); + } + + protected ParticipantInteractionType getParticipantInteractionType() { + return ParticipantInteractionType.OBSERVED; + } + +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java index 7708afc26..8e200a392 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java @@ -1,118 +1,127 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; -import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.wicket.instrument.InstrumentOutputParameterPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class OutputParametersStep extends WizardStepPanel { - - private static final long serialVersionUID = 6617334507631332206L; - - @SpringBean - private transient EntityQueryService queryService; - - @SpringBean - private transient ActiveInstrumentRunService activeInstrumentRunService; - - private InstrumentOutputParameterPanel instrumentOutputParameterPanel; - - private WizardStepPanel conclusionStep; - - private WizardStepPanel warningsStep; - - public OutputParametersStep(String id, WizardStepPanel conclusionStep, WizardStepPanel warningsStep) { - super(id); - - this.conclusionStep = conclusionStep; - this.warningsStep = warningsStep; - - setOutputMarkupId(true); - add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", OutputParametersStep.this, null))); - - add(new EmptyPanel("panel")); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getNextLink().setEnabled(true); - form.getPreviousLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getNextLink()); - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getFinishLink()); - } - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, instrumentOutputParameterPanel = new InstrumentOutputParameterPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - instrumentOutputParameterPanel.saveOutputInstrumentRunValues(); - activeInstrumentRunService.computeOutputParameters(); - - List paramsWithWarnings = getParametersWithWarnings(); - - if (!paramsWithWarnings.isEmpty()) { - warn(getString("ThereAreWarnings")); - ((WarningsStep)warningsStep).setParametersWithWarnings(paramsWithWarnings); - setNextStep(warningsStep); - } - else { - setNextStep(conclusionStep); - } - } - - private List getParametersWithWarnings() { - List paramsWithWarnings = new ArrayList(); - - // Query the output parameters. - InstrumentOutputParameter template = new InstrumentOutputParameter(); - template.setInstrument(activeInstrumentRunService.getInstrument()); - template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); - - List outputParams = queryService.match(template); - - for (InstrumentOutputParameter param : outputParams) { - InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); - - // Don't check parameters that haven't been assigned a value. - if (runValue == null || runValue.getData() == null || runValue.getData().getValue() == null) { - continue; - } - - for (IntegrityCheck check : param.getIntegrityChecks()) { - // Skip non-warning checks. - if (!check.getType().equals(IntegrityCheckType.WARNING)) { - continue; - } - - if (!check.checkParameterValue(runValue.getData(), null, activeInstrumentRunService)) { - paramsWithWarnings.add(param); - break; - } - } - } - - return paramsWithWarnings; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameterCaptureMethod; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheck; +import org.obiba.onyx.jade.core.domain.instrument.validation.IntegrityCheckType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.wicket.instrument.InstrumentOutputParameterPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class OutputParametersStep extends WizardStepPanel { + + private static final long serialVersionUID = 6617334507631332206L; + + @SpringBean + private transient EntityQueryService queryService; + + @SpringBean + private transient ActiveInstrumentRunService activeInstrumentRunService; + + private InstrumentOutputParameterPanel instrumentOutputParameterPanel; + + private WizardStepPanel conclusionStep; + + private WizardStepPanel warningsStep; + + public OutputParametersStep(String id, WizardStepPanel conclusionStep, WizardStepPanel warningsStep) { + super(id); + + this.conclusionStep = conclusionStep; + this.warningsStep = warningsStep; + + setOutputMarkupId(true); + add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", OutputParametersStep.this, null))); + + add(new EmptyPanel("panel")); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getNextLink().setEnabled(true); + form.getPreviousLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getNextLink()); + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getFinishLink()); + } + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, instrumentOutputParameterPanel = new InstrumentOutputParameterPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + instrumentOutputParameterPanel.saveOutputInstrumentRunValues(); + activeInstrumentRunService.computeOutputParameters(); + + List paramsWithWarnings = getParametersWithWarnings(); + + if (!paramsWithWarnings.isEmpty()) { + warn(getString("ThereAreWarnings")); + ((WarningsStep)warningsStep).setParametersWithWarnings(paramsWithWarnings); + setNextStep(warningsStep); + } + else { + setNextStep(conclusionStep); + } + } + + private List getParametersWithWarnings() { + List paramsWithWarnings = new ArrayList(); + + // Query the output parameters. + InstrumentOutputParameter template = new InstrumentOutputParameter(); + template.setInstrument(activeInstrumentRunService.getInstrument()); + template.setCaptureMethod(InstrumentParameterCaptureMethod.MANUAL); + + List outputParams = queryService.match(template); + + for (InstrumentOutputParameter param : outputParams) { + InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); + + // Don't check parameters that haven't been assigned a value. + if (runValue == null || runValue.getData() == null || runValue.getData().getValue() == null) { + continue; + } + + for (IntegrityCheck check : param.getIntegrityChecks()) { + // Skip non-warning checks. + if (!check.getType().equals(IntegrityCheckType.WARNING)) { + continue; + } + + if (!check.checkParameterValue(runValue.getData(), null, activeInstrumentRunService)) { + paramsWithWarnings.add(param); + break; + } + } + } + + return paramsWithWarnings; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/WarningsStep.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/WarningsStep.java index 6e392b9c8..72b943371 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/WarningsStep.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/WarningsStep.java @@ -1,84 +1,93 @@ -package org.obiba.onyx.jade.core.wicket.wizard; - -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; - -public class WarningsStep extends WizardStepPanel { - - private static final long serialVersionUID = 1L; - - @SpringBean - private transient EntityQueryService queryService; - - @SpringBean - private transient ActiveInstrumentRunService activeInstrumentRunService; - - @SpringBean(name = "userSessionService") - private UserSessionService userSessionService; - - private List paramsWithWarnings; - - public WarningsStep(String id) { - super(id); - - setOutputMarkupId(true); - add(new Label("title", new StringResourceModel("WarningsTitle", WarningsStep.this, null))); - - add(new EmptyPanel("panel")); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(true); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } - - void setParametersWithWarnings(List paramsWithWarnings) { - this.paramsWithWarnings = paramsWithWarnings; - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - KeyValueDataPanel warningsPanel = new KeyValueDataPanel(getContentId()); - warningsPanel.setOutputMarkupId(true); - - for (InstrumentOutputParameter param : paramsWithWarnings) { - // Inject the Spring application context and the user session service - // into the instrument parameter. NOTE: These are dependencies of - // InstrumentParameter.getDescription(). - param.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); - param.setUserSessionService(userSessionService); - - // Get the parameter's run value. - InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); - String valueAsString = runValue.getData().getValueAsString(); - if (valueAsString == null) { - valueAsString = ""; - } - - warningsPanel.addRow(new Label(KeyValueDataPanel.getRowKeyId(), param.getDescription()), new Label(KeyValueDataPanel.getRowValueId(), valueAsString + " "+param.getMeasurementUnit())); - } - - setContent(target, warningsPanel); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.wicket.wizard; + +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; + +public class WarningsStep extends WizardStepPanel { + + private static final long serialVersionUID = 1L; + + @SpringBean + private transient EntityQueryService queryService; + + @SpringBean + private transient ActiveInstrumentRunService activeInstrumentRunService; + + @SpringBean(name = "userSessionService") + private UserSessionService userSessionService; + + private List paramsWithWarnings; + + public WarningsStep(String id) { + super(id); + + setOutputMarkupId(true); + add(new Label("title", new StringResourceModel("WarningsTitle", WarningsStep.this, null))); + + add(new EmptyPanel("panel")); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(true); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } + + void setParametersWithWarnings(List paramsWithWarnings) { + this.paramsWithWarnings = paramsWithWarnings; + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + KeyValueDataPanel warningsPanel = new KeyValueDataPanel(getContentId()); + warningsPanel.setOutputMarkupId(true); + + for (InstrumentOutputParameter param : paramsWithWarnings) { + // Inject the Spring application context and the user session service + // into the instrument parameter. NOTE: These are dependencies of + // InstrumentParameter.getDescription(). + param.setApplicationContext(((SpringWebApplication) getApplication()).getSpringContextLocator().getSpringContext()); + param.setUserSessionService(userSessionService); + + // Get the parameter's run value. + InstrumentRunValue runValue = activeInstrumentRunService.getOutputInstrumentRunValue(param.getName()); + String valueAsString = runValue.getData().getValueAsString(); + if (valueAsString == null) { + valueAsString = ""; + } + + warningsPanel.addRow(new Label(KeyValueDataPanel.getRowKeyId(), param.getDescription()), new Label(KeyValueDataPanel.getRowValueId(), valueAsString + " "+param.getMeasurementUnit())); + } + + setContent(target, warningsPanel); + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/JadeModule.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/JadeModule.java index 6889fb012..e79b11c80 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/JadeModule.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/JadeModule.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.engine; import java.util.List; diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeCompletedState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeCompletedState.java index 4e73a7cd3..cf01c2411 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeCompletedState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeCompletedState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -84,4 +93,4 @@ public String getName() { public ActionType getStartingActionType() { return ActionType.EXECUTE; } -} \ No newline at end of file +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeContraIndicatedState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeContraIndicatedState.java index 55b3f3803..7803033bc 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeContraIndicatedState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeContraIndicatedState.java @@ -1,53 +1,62 @@ -package org.obiba.onyx.jade.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class JadeContraIndicatedState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(JadeCompletedState.class); - - public void afterPropertiesSet() throws Exception { - ActionDefinition def = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition(); - addAction(def); - } - - @Override - public void stop(Action action) { - super.execute(action); - log.info("Jade Stage {} is canceling", super.getStage().getName()); - if(areDependenciesCompleted() != null && areDependenciesCompleted()) { - castEvent(TransitionEvent.CANCEL); - } else { - castEvent(TransitionEvent.INVALID); - } - } - - @Override - public boolean isCompleted() { - return true; - } - - public String getName() { - return "Jade.ContraIndicated"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.CONTRAINDICATED) || transitionEvent.equals(TransitionEvent.VALID) || transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; - else - return true; - } - - @Override - public ActionType getStartingActionType() { - return ActionType.EXECUTE; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class JadeContraIndicatedState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(JadeCompletedState.class); + + public void afterPropertiesSet() throws Exception { + ActionDefinition def = ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition(); + addAction(def); + } + + @Override + public void stop(Action action) { + super.execute(action); + log.info("Jade Stage {} is canceling", super.getStage().getName()); + if(areDependenciesCompleted() != null && areDependenciesCompleted()) { + castEvent(TransitionEvent.CANCEL); + } else { + castEvent(TransitionEvent.INVALID); + } + } + + @Override + public boolean isCompleted() { + return true; + } + + public String getName() { + return "Jade.ContraIndicated"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.CONTRAINDICATED) || transitionEvent.equals(TransitionEvent.VALID) || transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; + else + return true; + } + + @Override + public ActionType getStartingActionType() { + return ActionType.EXECUTE; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeInProgressState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeInProgressState.java index 9237c252c..d407964de 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeInProgressState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeInProgressState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -84,4 +93,4 @@ public String getName() { return "Jade.InProgress"; } -} \ No newline at end of file +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeNotApplicableState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeNotApplicableState.java index bc48dd3ad..7916c9a26 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeNotApplicableState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeNotApplicableState.java @@ -1,29 +1,38 @@ -package org.obiba.onyx.jade.engine.state; - -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.springframework.beans.factory.InitializingBean; - -public class JadeNotApplicableState extends AbstractStageState implements InitializingBean { - - public void afterPropertiesSet() throws Exception { - // TODO Auto-generated method stub - - } - - @Override - public boolean isCompleted() { - return true; - } - - public String getName() { - return "Jade.NotApplicable"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; - else - return true; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.engine.state; + +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.springframework.beans.factory.InitializingBean; + +public class JadeNotApplicableState extends AbstractStageState implements InitializingBean { + + public void afterPropertiesSet() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public boolean isCompleted() { + return true; + } + + public String getName() { + return "Jade.NotApplicable"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; + else + return true; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeReadyState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeReadyState.java index ecb341469..2af1594ff 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeReadyState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeReadyState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -57,4 +66,4 @@ protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { else return true; } -} \ No newline at end of file +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeSkippedState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeSkippedState.java index 82f4d069a..4fa25af2f 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeSkippedState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeSkippedState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -78,4 +87,4 @@ public ActionType getStartingActionType() { return ActionType.SKIP; } -} \ No newline at end of file +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyCondition.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyCondition.java index dea00b8e4..26f9d9db7 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyCondition.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyCondition.java @@ -1,73 +1,82 @@ -package org.obiba.onyx.jade.engine.state; - -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentService; - -/** - * jade specific stage dependency condition depending on the presence of runValues for the stage - * @author acarey - */ -public class JadeStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private InstrumentRunService instrumentRunService; - - private InstrumentService instrumentService; - - private String stageName; - - public JadeStageDependencyCondition() { - } - - public JadeStageDependencyCondition(String name) { - this.stageName = name; - } - - public void setInstrumentRunService(InstrumentRunService instrumentRunService) { - this.instrumentRunService = instrumentRunService; - } - - public void setInstrumentService(InstrumentService instrumentService) { - this.instrumentService = instrumentService; - } - - /** - * Returns a Boolean depending on the fact that the step is completed and also on its result - * Null if not completed - * True if completed and has InstrumentRunValues - * False if completed and does not have InstrumentRunValues - */ - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - IStageExecution stageExecution = activeInterviewService.getStageExecution(stageName); - - if(!stageExecution.isCompleted()) return null; - else { - InstrumentRun instrumentRun = instrumentRunService.getLastCompletedInstrumentRun(activeInterviewService.getParticipant(), instrumentService.getInstrumentType(stageName)); - - if(instrumentRun != null && instrumentRun.getInstrumentRunValues().size() > 0) return true; - else - return false; - } - } - - @Override - public boolean isDependentOn(String stageName) { - return this.stageName.equals(stageName); - } - - public String getStageName() { - return stageName; - } - - public void setStageName(String stageName) { - this.stageName = stageName; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.engine.state; + +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentService; + +/** + * jade specific stage dependency condition depending on the presence of runValues for the stage + * @author acarey + */ +public class JadeStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private InstrumentRunService instrumentRunService; + + private InstrumentService instrumentService; + + private String stageName; + + public JadeStageDependencyCondition() { + } + + public JadeStageDependencyCondition(String name) { + this.stageName = name; + } + + public void setInstrumentRunService(InstrumentRunService instrumentRunService) { + this.instrumentRunService = instrumentRunService; + } + + public void setInstrumentService(InstrumentService instrumentService) { + this.instrumentService = instrumentService; + } + + /** + * Returns a Boolean depending on the fact that the step is completed and also on its result + * Null if not completed + * True if completed and has InstrumentRunValues + * False if completed and does not have InstrumentRunValues + */ + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + IStageExecution stageExecution = activeInterviewService.getStageExecution(stageName); + + if(!stageExecution.isCompleted()) return null; + else { + InstrumentRun instrumentRun = instrumentRunService.getLastCompletedInstrumentRun(activeInterviewService.getParticipant(), instrumentService.getInstrumentType(stageName)); + + if(instrumentRun != null && instrumentRun.getInstrumentRunValues().size() > 0) return true; + else + return false; + } + } + + @Override + public boolean isDependentOn(String stageName) { + return this.stageName.equals(stageName); + } + + public String getStageName() { + return stageName; + } + + public void setStageName(String stageName) { + this.stageName = stageName; + } +} diff --git a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeWaitingState.java b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeWaitingState.java index 1a1e7910e..2826ab8eb 100644 --- a/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeWaitingState.java +++ b/onyx-modules/jade/jade-core/src/main/java/org/obiba/onyx/jade/engine/state/JadeWaitingState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.engine.state; import org.obiba.onyx.engine.Action; @@ -48,4 +57,4 @@ protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { return true; } -} \ No newline at end of file +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InputSourceTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InputSourceTest.java index b0c336f4b..f5fac6758 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InputSourceTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InputSourceTest.java @@ -1,116 +1,125 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import java.util.Date; - -import org.junit.Assert; -import org.junit.Test; -import org.obiba.core.service.EntityQueryService; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -public class InputSourceTest extends BaseDefaultSpringContextTestCase { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(InputSourceTest.class); - - @Autowired(required = true) - InputDataSourceVisitor inputDataSourceVisitor; - - @Autowired(required = true) - EntityQueryService queryService; - - @Test - @Dataset - public void testParticipantPropertyRetriever() { - Participant participant = queryService.get(Participant.class, 1l); - - InstrumentInputParameter param = new InstrumentInputParameter(); - ParticipantPropertySource participantPropertySource = new ParticipantPropertySource(); - participantPropertySource.setProperty("birthDate"); - param.setDataType(DataType.DATE); - param.setInputSource(participantPropertySource); - Data resultData = inputDataSourceVisitor.getData(participant, param); - Assert.assertNotNull("Result Data is null", resultData); - Assert.assertEquals("1979-09-04", resultData.getValueAsString()); - Assert.assertEquals(DataType.DATE, resultData.getType()); - - participantPropertySource.setProperty("lastName"); - param.setDataType(DataType.TEXT); - resultData = inputDataSourceVisitor.getData(participant, param); - Assert.assertNotNull("Result Data is null", resultData); - Assert.assertEquals("Dupont", resultData.getValue()); - Assert.assertEquals(DataType.TEXT, resultData.getType()); - - participantPropertySource.setProperty("gender"); - param.setDataType(DataType.TEXT); - resultData = inputDataSourceVisitor.getData(participant, param); - Assert.assertNotNull("Result Data is null", resultData); - Assert.assertEquals("FEMALE", resultData.getValue()); - Assert.assertEquals(DataType.TEXT, resultData.getType()); - } - - @Test - @Dataset - public void testOutputParameterRetriever() { - Participant participant = queryService.get(Participant.class, 1l); - InstrumentType instrumentType = queryService.get(InstrumentType.class, 2l); - - InstrumentInputParameter param = new InstrumentInputParameter(); - OutputParameterSource outputParameterSource = new OutputParameterSource(); - outputParameterSource.setParameterName("heigth"); - outputParameterSource.setInstrumentType(instrumentType); - param.setDataType(DataType.INTEGER); - param.setInputSource(outputParameterSource); - - Data resultData = inputDataSourceVisitor.getData(participant, param); - Assert.assertEquals(Long.valueOf(187), resultData.getValue()); - Assert.assertEquals(DataType.INTEGER, resultData.getType()); - } - - @Test - @Dataset - public void testInstrumentParameterValueConverter() { - Participant participant = queryService.get(Participant.class, 1l); - - // Testing date data - InstrumentRunValue sourceInstrumentRunValue = queryService.get(InstrumentRunValue.class, 5l); - InstrumentParameter targetInstrumentParameter = queryService.get(InstrumentParameter.class, 6l); - - InstrumentRunValue targetInstrumentRunValue = new InstrumentRunValue(); - targetInstrumentRunValue.setInstrumentParameter(targetInstrumentParameter); - - if(sourceInstrumentRunValue.getData().getValue() == null) { - sourceInstrumentRunValue.setData(new Data(DataType.DATE, participant.getBirthDate())); - } - Date date = sourceInstrumentRunValue.getValue(); - log.info("date=" + date); - - DateParameterValueConverter dateConverter = new DateParameterValueConverter(); - dateConverter.convert(targetInstrumentRunValue, sourceInstrumentRunValue); - - InstrumentParameter finalInstrumentParameter = queryService.get(InstrumentParameter.class, 8l); - InstrumentRunValue finalInstrumentRunValue = new InstrumentRunValue(); - finalInstrumentRunValue.setInstrumentParameter(finalInstrumentParameter); - - UnitParameterValueConverter unitConverter = new UnitParameterValueConverter(); - unitConverter.convert(finalInstrumentRunValue, targetInstrumentRunValue); - Assert.assertEquals(Long.valueOf("29"), finalInstrumentRunValue.getValue()); - - // Testing metric data - sourceInstrumentRunValue = queryService.get(InstrumentRunValue.class, 1l); - targetInstrumentParameter = queryService.get(InstrumentParameter.class, 3l); - targetInstrumentRunValue.setInstrumentParameter(targetInstrumentParameter); - - unitConverter.convert(targetInstrumentRunValue, sourceInstrumentRunValue); - Assert.assertEquals(Double.valueOf("1.85"), targetInstrumentRunValue.getValue()); - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import java.util.Date; + +import org.junit.Assert; +import org.junit.Test; +import org.obiba.core.service.EntityQueryService; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.InputDataSourceVisitor; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +public class InputSourceTest extends BaseDefaultSpringContextTestCase { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(InputSourceTest.class); + + @Autowired(required = true) + InputDataSourceVisitor inputDataSourceVisitor; + + @Autowired(required = true) + EntityQueryService queryService; + + @Test + @Dataset + public void testParticipantPropertyRetriever() { + Participant participant = queryService.get(Participant.class, 1l); + + InstrumentInputParameter param = new InstrumentInputParameter(); + ParticipantPropertySource participantPropertySource = new ParticipantPropertySource(); + participantPropertySource.setProperty("birthDate"); + param.setDataType(DataType.DATE); + param.setInputSource(participantPropertySource); + Data resultData = inputDataSourceVisitor.getData(participant, param); + Assert.assertNotNull("Result Data is null", resultData); + Assert.assertEquals("1979-09-04", resultData.getValueAsString()); + Assert.assertEquals(DataType.DATE, resultData.getType()); + + participantPropertySource.setProperty("lastName"); + param.setDataType(DataType.TEXT); + resultData = inputDataSourceVisitor.getData(participant, param); + Assert.assertNotNull("Result Data is null", resultData); + Assert.assertEquals("Dupont", resultData.getValue()); + Assert.assertEquals(DataType.TEXT, resultData.getType()); + + participantPropertySource.setProperty("gender"); + param.setDataType(DataType.TEXT); + resultData = inputDataSourceVisitor.getData(participant, param); + Assert.assertNotNull("Result Data is null", resultData); + Assert.assertEquals("FEMALE", resultData.getValue()); + Assert.assertEquals(DataType.TEXT, resultData.getType()); + } + + @Test + @Dataset + public void testOutputParameterRetriever() { + Participant participant = queryService.get(Participant.class, 1l); + InstrumentType instrumentType = queryService.get(InstrumentType.class, 2l); + + InstrumentInputParameter param = new InstrumentInputParameter(); + OutputParameterSource outputParameterSource = new OutputParameterSource(); + outputParameterSource.setParameterName("heigth"); + outputParameterSource.setInstrumentType(instrumentType); + param.setDataType(DataType.INTEGER); + param.setInputSource(outputParameterSource); + + Data resultData = inputDataSourceVisitor.getData(participant, param); + Assert.assertEquals(Long.valueOf(187), resultData.getValue()); + Assert.assertEquals(DataType.INTEGER, resultData.getType()); + } + + @Test + @Dataset + public void testInstrumentParameterValueConverter() { + Participant participant = queryService.get(Participant.class, 1l); + + // Testing date data + InstrumentRunValue sourceInstrumentRunValue = queryService.get(InstrumentRunValue.class, 5l); + InstrumentParameter targetInstrumentParameter = queryService.get(InstrumentParameter.class, 6l); + + InstrumentRunValue targetInstrumentRunValue = new InstrumentRunValue(); + targetInstrumentRunValue.setInstrumentParameter(targetInstrumentParameter); + + if(sourceInstrumentRunValue.getData().getValue() == null) { + sourceInstrumentRunValue.setData(new Data(DataType.DATE, participant.getBirthDate())); + } + Date date = sourceInstrumentRunValue.getValue(); + log.info("date=" + date); + + DateParameterValueConverter dateConverter = new DateParameterValueConverter(); + dateConverter.convert(targetInstrumentRunValue, sourceInstrumentRunValue); + + InstrumentParameter finalInstrumentParameter = queryService.get(InstrumentParameter.class, 8l); + InstrumentRunValue finalInstrumentRunValue = new InstrumentRunValue(); + finalInstrumentRunValue.setInstrumentParameter(finalInstrumentParameter); + + UnitParameterValueConverter unitConverter = new UnitParameterValueConverter(); + unitConverter.convert(finalInstrumentRunValue, targetInstrumentRunValue); + Assert.assertEquals(Long.valueOf("29"), finalInstrumentRunValue.getValue()); + + // Testing metric data + sourceInstrumentRunValue = queryService.get(InstrumentRunValue.class, 1l); + targetInstrumentParameter = queryService.get(InstrumentParameter.class, 3l); + targetInstrumentRunValue.setInstrumentParameter(targetInstrumentParameter); + + unitConverter.convert(targetInstrumentRunValue, sourceInstrumentRunValue); + Assert.assertEquals(Double.valueOf("1.85"), targetInstrumentRunValue.getValue()); + } + +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterTest.java index bb287866e..0529e685f 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/InstrumentParameterTest.java @@ -1,89 +1,98 @@ -package org.obiba.onyx.jade.core.domain.instrument; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; - -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.wicket.test.ExtendedApplicationContextMock; - -public class InstrumentParameterTest { - - private ExtendedApplicationContextMock applicationContextMock; - - private UserSessionService userSessionServiceMock; - - @Before - public void setUp() { - applicationContextMock = new ExtendedApplicationContextMock(); - - userSessionServiceMock = createMock(UserSessionService.class); - applicationContextMock.putBean("userSessionService", userSessionServiceMock); - } - - /** - * Tests that the returned instrument parameter description is localized. - */ - @Test - public void testGetDescription() { - // Will test with an InstrumentOutputParameter object, since - // InstrumentParameter is abstract. Note: InstrumentInputParameter - // inherits the same implementation of getDescription() so there is - // no need to repeat the test for that type of object. - InstrumentOutputParameter outputParam = new InstrumentOutputParameter(); - - outputParam.setApplicationContext(applicationContextMock); - outputParam.setUserSessionService(userSessionServiceMock); - - String unLocalizedDescription = "First_Height_Measurement"; - outputParam.setDescription(unLocalizedDescription); - - // - // Test in English locale ("en"). - // - Locale englishLocale = new Locale("en"); - - String expectedEnglishLocalizedDescription = "First Height Measurement"; - applicationContextMock.setMessage(expectedEnglishLocalizedDescription); - - expect(userSessionServiceMock.getLocale()).andReturn(englishLocale); - - replay(userSessionServiceMock); - - String actualEnglishLocalizedDescription = outputParam.getDescription(); - - verify(userSessionServiceMock); - - Assert.assertEquals(expectedEnglishLocalizedDescription, actualEnglishLocalizedDescription); - - // Reset userSessionServiceMock (otherwise in the next part of the test the calls to getLocale() - // won't match expectations). - reset(userSessionServiceMock); - - // - // Test in French locale ("fr"). - // - Locale frenchLocale = new Locale("fr"); - - //TODO: Substitute true French translation when it is added to the resource bundle - String expectedFrenchLocalizedDescription = "fr:First Height Measurement"; - applicationContextMock.setMessage(expectedFrenchLocalizedDescription); - - expect(userSessionServiceMock.getLocale()).andReturn(frenchLocale); - - replay(userSessionServiceMock); - - String actualFrenchLocalizedDescription = outputParam.getDescription(); - - verify(userSessionServiceMock); - - Assert.assertEquals(expectedFrenchLocalizedDescription, actualFrenchLocalizedDescription); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; +import static org.easymock.EasyMock.verify; + +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.wicket.test.ExtendedApplicationContextMock; + +public class InstrumentParameterTest { + + private ExtendedApplicationContextMock applicationContextMock; + + private UserSessionService userSessionServiceMock; + + @Before + public void setUp() { + applicationContextMock = new ExtendedApplicationContextMock(); + + userSessionServiceMock = createMock(UserSessionService.class); + applicationContextMock.putBean("userSessionService", userSessionServiceMock); + } + + /** + * Tests that the returned instrument parameter description is localized. + */ + @Test + public void testGetDescription() { + // Will test with an InstrumentOutputParameter object, since + // InstrumentParameter is abstract. Note: InstrumentInputParameter + // inherits the same implementation of getDescription() so there is + // no need to repeat the test for that type of object. + InstrumentOutputParameter outputParam = new InstrumentOutputParameter(); + + outputParam.setApplicationContext(applicationContextMock); + outputParam.setUserSessionService(userSessionServiceMock); + + String unLocalizedDescription = "First_Height_Measurement"; + outputParam.setDescription(unLocalizedDescription); + + // + // Test in English locale ("en"). + // + Locale englishLocale = new Locale("en"); + + String expectedEnglishLocalizedDescription = "First Height Measurement"; + applicationContextMock.setMessage(expectedEnglishLocalizedDescription); + + expect(userSessionServiceMock.getLocale()).andReturn(englishLocale); + + replay(userSessionServiceMock); + + String actualEnglishLocalizedDescription = outputParam.getDescription(); + + verify(userSessionServiceMock); + + Assert.assertEquals(expectedEnglishLocalizedDescription, actualEnglishLocalizedDescription); + + // Reset userSessionServiceMock (otherwise in the next part of the test the calls to getLocale() + // won't match expectations). + reset(userSessionServiceMock); + + // + // Test in French locale ("fr"). + // + Locale frenchLocale = new Locale("fr"); + + //TODO: Substitute true French translation when it is added to the resource bundle + String expectedFrenchLocalizedDescription = "fr:First Height Measurement"; + applicationContextMock.setMessage(expectedFrenchLocalizedDescription); + + expect(userSessionServiceMock.getLocale()).andReturn(frenchLocale); + + replay(userSessionServiceMock); + + String actualFrenchLocalizedDescription = outputParam.getDescription(); + + verify(userSessionServiceMock); + + Assert.assertEquals(expectedFrenchLocalizedDescription, actualFrenchLocalizedDescription); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheckTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheckTest.java index f00dc8979..51d481728 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheckTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsParameterCheckTest.java @@ -1,124 +1,133 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import static org.easymock.EasyMock.*; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -public class EqualsParameterCheckTest { - - private EqualsParameterCheck equalsParameterCheck; - - private ParticipantInterview interview; - - private InstrumentRun instrumentRun; - - private InstrumentType instrumentType; - - private Instrument instrument; - - private InstrumentParameter checkedParameter; - - private InstrumentParameter otherParameter; - - private InstrumentRunService instrumentRunServiceMock; - - private ActiveInstrumentRunService activeInstrumentRunServiceMock; - - @Before - public void setUp() { - equalsParameterCheck = new EqualsParameterCheck(); - - interview = new ParticipantInterview(); - - instrumentType = new InstrumentType(); - - instrument = new Instrument(); - instrument.setInstrumentType(instrumentType); - - instrumentRun = new InstrumentRun(); - instrumentRun.setParticipantInterview(interview); - instrumentRun.setInstrument(instrument); - - checkedParameter = new InstrumentOutputParameter(); - checkedParameter.setName("checkedParamName"); - - otherParameter = new InstrumentInputParameter(); - otherParameter.setName("otherParamName"); - - equalsParameterCheck.setTargetParameter(checkedParameter); - equalsParameterCheck.setParameter(otherParameter); - - instrumentRunServiceMock = createMock(InstrumentRunService.class); - - activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); - } - - /** - * Tests equal DataType.INTEGER parameters. - */ - @Test - public void testIntegerParametersEqual() { - checkedParameter.setDataType(DataType.INTEGER); - otherParameter.setDataType(DataType.INTEGER); - - // Initialize checked parameter's run value. - Data checkedData = DataBuilder.buildInteger(100l); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildInteger(100l); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(equalsParameterCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests unequal DataType.INTEGER parameters. - */ - @Test - public void testIntegerParametersUnequal() { - checkedParameter.setDataType(DataType.INTEGER); - otherParameter.setDataType(DataType.INTEGER); - - // Initialize checked parameter's run value. - Data checkedData = DataBuilder.buildInteger(100l); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildInteger(200l); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(equalsParameterCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import static org.easymock.EasyMock.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +public class EqualsParameterCheckTest { + + private EqualsParameterCheck equalsParameterCheck; + + private ParticipantInterview interview; + + private InstrumentRun instrumentRun; + + private InstrumentType instrumentType; + + private Instrument instrument; + + private InstrumentParameter checkedParameter; + + private InstrumentParameter otherParameter; + + private InstrumentRunService instrumentRunServiceMock; + + private ActiveInstrumentRunService activeInstrumentRunServiceMock; + + @Before + public void setUp() { + equalsParameterCheck = new EqualsParameterCheck(); + + interview = new ParticipantInterview(); + + instrumentType = new InstrumentType(); + + instrument = new Instrument(); + instrument.setInstrumentType(instrumentType); + + instrumentRun = new InstrumentRun(); + instrumentRun.setParticipantInterview(interview); + instrumentRun.setInstrument(instrument); + + checkedParameter = new InstrumentOutputParameter(); + checkedParameter.setName("checkedParamName"); + + otherParameter = new InstrumentInputParameter(); + otherParameter.setName("otherParamName"); + + equalsParameterCheck.setTargetParameter(checkedParameter); + equalsParameterCheck.setParameter(otherParameter); + + instrumentRunServiceMock = createMock(InstrumentRunService.class); + + activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); + } + + /** + * Tests equal DataType.INTEGER parameters. + */ + @Test + public void testIntegerParametersEqual() { + checkedParameter.setDataType(DataType.INTEGER); + otherParameter.setDataType(DataType.INTEGER); + + // Initialize checked parameter's run value. + Data checkedData = DataBuilder.buildInteger(100l); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildInteger(100l); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(equalsParameterCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests unequal DataType.INTEGER parameters. + */ + @Test + public void testIntegerParametersUnequal() { + checkedParameter.setDataType(DataType.INTEGER); + otherParameter.setDataType(DataType.INTEGER); + + // Initialize checked parameter's run value. + Data checkedData = DataBuilder.buildInteger(100l); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildInteger(200l); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(equalsParameterCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheckTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheckTest.java index 6ee4ecb2f..d9b380e89 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheckTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/EqualsValueCheckTest.java @@ -1,218 +1,227 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -public class EqualsValueCheckTest { - - private EqualsValueCheck equalsValueCheck; - - private InstrumentParameter instrumentParameter; - - @Before - public void setUp() { - equalsValueCheck = new EqualsValueCheck(); - - instrumentParameter = new InstrumentInputParameter(); - equalsValueCheck.setTargetParameter(instrumentParameter); - } - - /** - * Tests equal DataType.BOOLEAN values. - */ - @Test - public void testCheckParameterValueBoolean() { - instrumentParameter.setDataType(DataType.BOOLEAN); - - // Test with run value TRUE. - Data trueData = DataBuilder.buildBoolean(Boolean.TRUE); - - equalsValueCheck.setBooleanValue(Boolean.TRUE); - Assert.assertTrue(equalsValueCheck.checkParameterValue(trueData, null, null)); - - // Test with run value FALSE. - Data falseData = DataBuilder.buildBoolean(Boolean.FALSE); - - equalsValueCheck.setBooleanValue(Boolean.FALSE); - Assert.assertTrue(equalsValueCheck.checkParameterValue(falseData, null, null)); - } - - /** - * Tests unequal DataType.BOOLEAN values. - */ - @Test - public void testCheckParameterValueBooleanUnequal() { - instrumentParameter.setDataType(DataType.BOOLEAN); - - // Test with run value TRUE. - Data trueData = DataBuilder.buildBoolean(Boolean.TRUE); - - equalsValueCheck.setBooleanValue(false); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(trueData, null, null)); - - // Test with run value FALSE. - Data falseData = DataBuilder.buildBoolean(Boolean.FALSE); - - equalsValueCheck.setBooleanValue(true); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(falseData, null, null)); - } - - /** - * Tests equal DataType.INTEGER values. - */ - @Test - public void testCheckParameterValueInteger() { - instrumentParameter.setDataType(DataType.INTEGER); - - // Test run value equals 1. - Data oneData = DataBuilder.buildInteger(Long.valueOf(1)); - - equalsValueCheck.setIntegerValue(1l); - Assert.assertTrue(equalsValueCheck.checkParameterValue(oneData, null, null)); - - // Test run value equals Long.MAX_VALUE. - Data maxIntData = DataBuilder.buildInteger(Long.MAX_VALUE); - - equalsValueCheck.setIntegerValue(Long.MAX_VALUE); - Assert.assertTrue(equalsValueCheck.checkParameterValue(maxIntData, null, null)); - } - - /** - * Tests unequal DataType.INTEGER values. - */ - @Test - public void testCheckParameterValueIntegerUnequal() { - instrumentParameter.setDataType(DataType.INTEGER); - - // Test run value equals 1. - Data oneData = DataBuilder.buildInteger(Long.valueOf(1)); - - equalsValueCheck.setData(DataBuilder.buildInteger(Long.MAX_VALUE)); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(oneData, null, null)); - - // Test run value equals Long.MAX_VALUE. - Data maxIntData = DataBuilder.buildInteger(Long.MAX_VALUE); - - equalsValueCheck.setData(DataBuilder.buildInteger(Long.valueOf(1))); - Assert.assertFalse(equalsValueCheck.checkParameterValue(maxIntData, null, null)); - } - - /** - * Tests equal DataType.DECIMAL values. - */ - @Test - public void testCheckParameterValueDecimal() { - instrumentParameter.setDataType(DataType.DECIMAL); - - // Test run value equals 1.5. - Data onePointFiveData = DataBuilder.buildDecimal(Double.valueOf(1.5)); - - equalsValueCheck.setData(onePointFiveData); - Assert.assertTrue(equalsValueCheck.checkParameterValue(onePointFiveData, null, null)); - - // Test run value equals Double.MAX_VALUE. - Data maxDecimalData = DataBuilder.buildDecimal(Double.MAX_VALUE); - - equalsValueCheck.setData(maxDecimalData); - Assert.assertTrue(equalsValueCheck.checkParameterValue(maxDecimalData, null, null)); - } - - /** - * Tests unequal DataType.DECIMAL values. - */ - @Test - public void testCheckParameterValueDecimalUnequal() { - instrumentParameter.setDataType(DataType.DECIMAL); - - // Test run value equals 1.5. - Data onePointFiveData = DataBuilder.buildDecimal(Double.valueOf(1.5)); - - equalsValueCheck.setData(DataBuilder.buildDecimal(Double.MIN_VALUE)); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(onePointFiveData, null, null)); - - // Test run value equals Double.MAX_VALUE. - Data maxDecimalData = DataBuilder.buildDecimal(Double.MAX_VALUE); - - equalsValueCheck.setData(DataBuilder.buildDecimal(Double.valueOf(1.5))); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(maxDecimalData, null, null)); - } - - /** - * Tests equal DataType.TEXT values. - */ - @Test - public void testCheckParameterValueText() { - instrumentParameter.setDataType(DataType.TEXT); - - // Test run value equals "Foo". - Data fooData = DataBuilder.buildText("Foo"); - - equalsValueCheck.setData(fooData); - Assert.assertTrue(equalsValueCheck.checkParameterValue(fooData, null, null)); - } - - /** - * Tests unequal DataType.TEXT values. - */ - @Test - public void testCheckParameterValueTextUnequal() { - instrumentParameter.setDataType(DataType.TEXT); - - // Test run value equals "Foo". - Data fooData = DataBuilder.buildText("Foo"); - - equalsValueCheck.setData(new Data(DataType.TEXT, "Bar")); // unequal - Assert.assertFalse(equalsValueCheck.checkParameterValue(fooData, null, null)); - } - - /** - * Tests equal null values (i.e., run value is null, so is check value). - */ - @Test - public void testCheckParameterValueNull() { - // Any type will do for this test, since the value will be null. - instrumentParameter.setDataType(DataType.TEXT); - - // Test run value is null. - Data nullData = DataBuilder.buildText(null); - - equalsValueCheck.setData(new Data(DataType.TEXT, null)); - Assert.assertTrue(equalsValueCheck.checkParameterValue(nullData, null, null)); - } - - /** - * Tests run value null, check value not null. - */ - @Test - public void testRunValueNullCheckValueNotNull() { - // Any type will do for this test, since the value will be null. - instrumentParameter.setDataType(DataType.TEXT); - - // Test run value is null. - Data nullData = DataBuilder.buildText(null); - - equalsValueCheck.setData(new Data(DataType.TEXT, "Foo")); // not null - Assert.assertFalse(equalsValueCheck.checkParameterValue(nullData, null, null)); - } - - /** - * Tests run value not null, check value null. - */ - @Test - public void testRunValueNotNullCheckValueNull() { - // Any type will do for this test, since the value will be null. - instrumentParameter.setDataType(DataType.TEXT); - - // Test run value is not null. - Data fooData = DataBuilder.buildText("Foo"); - - equalsValueCheck.setData(new Data(DataType.TEXT, null)); // null - Assert.assertFalse(equalsValueCheck.checkParameterValue(fooData, null, null)); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +public class EqualsValueCheckTest { + + private EqualsValueCheck equalsValueCheck; + + private InstrumentParameter instrumentParameter; + + @Before + public void setUp() { + equalsValueCheck = new EqualsValueCheck(); + + instrumentParameter = new InstrumentInputParameter(); + equalsValueCheck.setTargetParameter(instrumentParameter); + } + + /** + * Tests equal DataType.BOOLEAN values. + */ + @Test + public void testCheckParameterValueBoolean() { + instrumentParameter.setDataType(DataType.BOOLEAN); + + // Test with run value TRUE. + Data trueData = DataBuilder.buildBoolean(Boolean.TRUE); + + equalsValueCheck.setBooleanValue(Boolean.TRUE); + Assert.assertTrue(equalsValueCheck.checkParameterValue(trueData, null, null)); + + // Test with run value FALSE. + Data falseData = DataBuilder.buildBoolean(Boolean.FALSE); + + equalsValueCheck.setBooleanValue(Boolean.FALSE); + Assert.assertTrue(equalsValueCheck.checkParameterValue(falseData, null, null)); + } + + /** + * Tests unequal DataType.BOOLEAN values. + */ + @Test + public void testCheckParameterValueBooleanUnequal() { + instrumentParameter.setDataType(DataType.BOOLEAN); + + // Test with run value TRUE. + Data trueData = DataBuilder.buildBoolean(Boolean.TRUE); + + equalsValueCheck.setBooleanValue(false); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(trueData, null, null)); + + // Test with run value FALSE. + Data falseData = DataBuilder.buildBoolean(Boolean.FALSE); + + equalsValueCheck.setBooleanValue(true); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(falseData, null, null)); + } + + /** + * Tests equal DataType.INTEGER values. + */ + @Test + public void testCheckParameterValueInteger() { + instrumentParameter.setDataType(DataType.INTEGER); + + // Test run value equals 1. + Data oneData = DataBuilder.buildInteger(Long.valueOf(1)); + + equalsValueCheck.setIntegerValue(1l); + Assert.assertTrue(equalsValueCheck.checkParameterValue(oneData, null, null)); + + // Test run value equals Long.MAX_VALUE. + Data maxIntData = DataBuilder.buildInteger(Long.MAX_VALUE); + + equalsValueCheck.setIntegerValue(Long.MAX_VALUE); + Assert.assertTrue(equalsValueCheck.checkParameterValue(maxIntData, null, null)); + } + + /** + * Tests unequal DataType.INTEGER values. + */ + @Test + public void testCheckParameterValueIntegerUnequal() { + instrumentParameter.setDataType(DataType.INTEGER); + + // Test run value equals 1. + Data oneData = DataBuilder.buildInteger(Long.valueOf(1)); + + equalsValueCheck.setData(DataBuilder.buildInteger(Long.MAX_VALUE)); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(oneData, null, null)); + + // Test run value equals Long.MAX_VALUE. + Data maxIntData = DataBuilder.buildInteger(Long.MAX_VALUE); + + equalsValueCheck.setData(DataBuilder.buildInteger(Long.valueOf(1))); + Assert.assertFalse(equalsValueCheck.checkParameterValue(maxIntData, null, null)); + } + + /** + * Tests equal DataType.DECIMAL values. + */ + @Test + public void testCheckParameterValueDecimal() { + instrumentParameter.setDataType(DataType.DECIMAL); + + // Test run value equals 1.5. + Data onePointFiveData = DataBuilder.buildDecimal(Double.valueOf(1.5)); + + equalsValueCheck.setData(onePointFiveData); + Assert.assertTrue(equalsValueCheck.checkParameterValue(onePointFiveData, null, null)); + + // Test run value equals Double.MAX_VALUE. + Data maxDecimalData = DataBuilder.buildDecimal(Double.MAX_VALUE); + + equalsValueCheck.setData(maxDecimalData); + Assert.assertTrue(equalsValueCheck.checkParameterValue(maxDecimalData, null, null)); + } + + /** + * Tests unequal DataType.DECIMAL values. + */ + @Test + public void testCheckParameterValueDecimalUnequal() { + instrumentParameter.setDataType(DataType.DECIMAL); + + // Test run value equals 1.5. + Data onePointFiveData = DataBuilder.buildDecimal(Double.valueOf(1.5)); + + equalsValueCheck.setData(DataBuilder.buildDecimal(Double.MIN_VALUE)); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(onePointFiveData, null, null)); + + // Test run value equals Double.MAX_VALUE. + Data maxDecimalData = DataBuilder.buildDecimal(Double.MAX_VALUE); + + equalsValueCheck.setData(DataBuilder.buildDecimal(Double.valueOf(1.5))); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(maxDecimalData, null, null)); + } + + /** + * Tests equal DataType.TEXT values. + */ + @Test + public void testCheckParameterValueText() { + instrumentParameter.setDataType(DataType.TEXT); + + // Test run value equals "Foo". + Data fooData = DataBuilder.buildText("Foo"); + + equalsValueCheck.setData(fooData); + Assert.assertTrue(equalsValueCheck.checkParameterValue(fooData, null, null)); + } + + /** + * Tests unequal DataType.TEXT values. + */ + @Test + public void testCheckParameterValueTextUnequal() { + instrumentParameter.setDataType(DataType.TEXT); + + // Test run value equals "Foo". + Data fooData = DataBuilder.buildText("Foo"); + + equalsValueCheck.setData(new Data(DataType.TEXT, "Bar")); // unequal + Assert.assertFalse(equalsValueCheck.checkParameterValue(fooData, null, null)); + } + + /** + * Tests equal null values (i.e., run value is null, so is check value). + */ + @Test + public void testCheckParameterValueNull() { + // Any type will do for this test, since the value will be null. + instrumentParameter.setDataType(DataType.TEXT); + + // Test run value is null. + Data nullData = DataBuilder.buildText(null); + + equalsValueCheck.setData(new Data(DataType.TEXT, null)); + Assert.assertTrue(equalsValueCheck.checkParameterValue(nullData, null, null)); + } + + /** + * Tests run value null, check value not null. + */ + @Test + public void testRunValueNullCheckValueNotNull() { + // Any type will do for this test, since the value will be null. + instrumentParameter.setDataType(DataType.TEXT); + + // Test run value is null. + Data nullData = DataBuilder.buildText(null); + + equalsValueCheck.setData(new Data(DataType.TEXT, "Foo")); // not null + Assert.assertFalse(equalsValueCheck.checkParameterValue(nullData, null, null)); + } + + /** + * Tests run value not null, check value null. + */ + @Test + public void testRunValueNotNullCheckValueNull() { + // Any type will do for this test, since the value will be null. + instrumentParameter.setDataType(DataType.TEXT); + + // Test run value is not null. + Data fooData = DataBuilder.buildText("Foo"); + + equalsValueCheck.setData(new Data(DataType.TEXT, null)); // null + Assert.assertFalse(equalsValueCheck.checkParameterValue(fooData, null, null)); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheckTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheckTest.java index 097c3eba7..6b378c24b 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheckTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/ParameterSpreadCheckTest.java @@ -1,321 +1,330 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import static org.easymock.EasyMock.*; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -public class ParameterSpreadCheckTest { - - private ParameterSpreadCheck parameterSpreadCheck; - - private Participant participant; - - private ParticipantInterview interview; - - private InstrumentRun instrumentRun; - - private InstrumentType instrumentType; - - private Instrument instrument; - - private InstrumentParameter checkedParameter; - - private InstrumentParameter otherParameter; - - private InstrumentRunService instrumentRunServiceMock; - - private ActiveInstrumentRunService activeInstrumentRunServiceMock; - - @Before - public void setUp() { - parameterSpreadCheck = new ParameterSpreadCheck(); - - participant = new Participant(); - participant.setGender(Gender.MALE); - - interview = new ParticipantInterview(); - interview.setParticipant(participant); - - instrumentType = new InstrumentType(); - - instrument = new Instrument(); - instrument.setInstrumentType(instrumentType); - - instrumentRun = new InstrumentRun(); - instrumentRun.setParticipantInterview(interview); - instrumentRun.setInstrument(instrument); - - checkedParameter = new InstrumentOutputParameter(); - otherParameter = new InstrumentInputParameter(); - - parameterSpreadCheck.setTargetParameter(checkedParameter); - parameterSpreadCheck.setParameter(otherParameter); - - instrumentRunServiceMock = createMock(InstrumentRunService.class); - - activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); - } - - /** - * Tests DataType.INTEGER parameters with the same value. - */ - @Test - public void testIntegerParametersWithSameValue() { - checkedParameter.setDataType(DataType.INTEGER); - otherParameter.setDataType(DataType.INTEGER); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize checked parameter's run value. - Data checkedData = DataBuilder.buildInteger(100l); - - // Test with other parameter's run value set to the SAME value. - Data otherData = DataBuilder.buildInteger(100l); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.INTEGER parameters within the required spread. - */ - @Test - public void testIntegerParametersWithinSpread() { - checkedParameter.setDataType(DataType.INTEGER); - otherParameter.setDataType(DataType.INTEGER); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildInteger(100l); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - // Test with checked parameter's run value set to MINIMUM value within spread. - Data checkedDataMin = DataBuilder.buildInteger(95l); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with checked parameter's run value set to MAXIMUM value within spread. - Data checkedDataMax = DataBuilder.buildInteger(105l); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.INTEGER parameters outside the required spread. - */ - @Test - public void testIntegerParametersOutsideSpread() { - checkedParameter.setDataType(DataType.INTEGER); - otherParameter.setDataType(DataType.INTEGER); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildInteger(100l); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - // Test with checked parameter's run value set to LESS than the minimum value in spread. - Data checkedDataMin = DataBuilder.buildInteger(94l); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with checked parameter's run value set to MORE than the maximum value in spread. - Data checkedDataMax = DataBuilder.buildInteger(106l); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL parameters with the same value. - */ - @Test - public void testDecimalParametersWithSameValue() { - checkedParameter.setDataType(DataType.DECIMAL); - otherParameter.setDataType(DataType.DECIMAL); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize checked parameter's run value. - Data checkedData = DataBuilder.buildDecimal(100.0); - - // Test with other parameter's run value set to the SAME value. - Data otherData = DataBuilder.buildDecimal(100.0); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL parameters within the required spread. - */ - @Test - public void testDecimalParametersWithinSpread() { - checkedParameter.setDataType(DataType.DECIMAL); - otherParameter.setDataType(DataType.DECIMAL); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildDecimal(100.0); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - // Test with checked parameter's run value set to MINIMUM value within spread. - Data checkedDataMin = DataBuilder.buildDecimal(95.0); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with checked parameter's run value set to MAXIMUM value within spread. - Data checkedDataMax = DataBuilder.buildDecimal(105.0); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL parameters outside the required spread. - */ - @Test - public void testDecimalParametersOutsideSpread() { - checkedParameter.setDataType(DataType.DECIMAL); - otherParameter.setDataType(DataType.DECIMAL); - - // Set a spread of 5%. - parameterSpreadCheck.setPercent(5); - - // Initialize other parameter's run value. - Data otherData = DataBuilder.buildDecimal(100.0); - - InstrumentRunValue otherRunValue = new InstrumentRunValue(); - otherRunValue.setInstrumentParameter(otherParameter); - otherRunValue.setData(otherData); - - // Test with checked parameter's run value set to LESS than the minimum value in spread. - Data checkedDataMin = DataBuilder.buildDecimal(94.0); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with checked parameter's run value set to MORE than the maximum value in spread. - Data checkedDataMax = DataBuilder.buildDecimal(106.0); - - expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import static org.easymock.EasyMock.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +public class ParameterSpreadCheckTest { + + private ParameterSpreadCheck parameterSpreadCheck; + + private Participant participant; + + private ParticipantInterview interview; + + private InstrumentRun instrumentRun; + + private InstrumentType instrumentType; + + private Instrument instrument; + + private InstrumentParameter checkedParameter; + + private InstrumentParameter otherParameter; + + private InstrumentRunService instrumentRunServiceMock; + + private ActiveInstrumentRunService activeInstrumentRunServiceMock; + + @Before + public void setUp() { + parameterSpreadCheck = new ParameterSpreadCheck(); + + participant = new Participant(); + participant.setGender(Gender.MALE); + + interview = new ParticipantInterview(); + interview.setParticipant(participant); + + instrumentType = new InstrumentType(); + + instrument = new Instrument(); + instrument.setInstrumentType(instrumentType); + + instrumentRun = new InstrumentRun(); + instrumentRun.setParticipantInterview(interview); + instrumentRun.setInstrument(instrument); + + checkedParameter = new InstrumentOutputParameter(); + otherParameter = new InstrumentInputParameter(); + + parameterSpreadCheck.setTargetParameter(checkedParameter); + parameterSpreadCheck.setParameter(otherParameter); + + instrumentRunServiceMock = createMock(InstrumentRunService.class); + + activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); + } + + /** + * Tests DataType.INTEGER parameters with the same value. + */ + @Test + public void testIntegerParametersWithSameValue() { + checkedParameter.setDataType(DataType.INTEGER); + otherParameter.setDataType(DataType.INTEGER); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize checked parameter's run value. + Data checkedData = DataBuilder.buildInteger(100l); + + // Test with other parameter's run value set to the SAME value. + Data otherData = DataBuilder.buildInteger(100l); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.INTEGER parameters within the required spread. + */ + @Test + public void testIntegerParametersWithinSpread() { + checkedParameter.setDataType(DataType.INTEGER); + otherParameter.setDataType(DataType.INTEGER); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildInteger(100l); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + // Test with checked parameter's run value set to MINIMUM value within spread. + Data checkedDataMin = DataBuilder.buildInteger(95l); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with checked parameter's run value set to MAXIMUM value within spread. + Data checkedDataMax = DataBuilder.buildInteger(105l); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.INTEGER parameters outside the required spread. + */ + @Test + public void testIntegerParametersOutsideSpread() { + checkedParameter.setDataType(DataType.INTEGER); + otherParameter.setDataType(DataType.INTEGER); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildInteger(100l); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + // Test with checked parameter's run value set to LESS than the minimum value in spread. + Data checkedDataMin = DataBuilder.buildInteger(94l); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with checked parameter's run value set to MORE than the maximum value in spread. + Data checkedDataMax = DataBuilder.buildInteger(106l); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL parameters with the same value. + */ + @Test + public void testDecimalParametersWithSameValue() { + checkedParameter.setDataType(DataType.DECIMAL); + otherParameter.setDataType(DataType.DECIMAL); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize checked parameter's run value. + Data checkedData = DataBuilder.buildDecimal(100.0); + + // Test with other parameter's run value set to the SAME value. + Data otherData = DataBuilder.buildDecimal(100.0); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedData, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL parameters within the required spread. + */ + @Test + public void testDecimalParametersWithinSpread() { + checkedParameter.setDataType(DataType.DECIMAL); + otherParameter.setDataType(DataType.DECIMAL); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildDecimal(100.0); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + // Test with checked parameter's run value set to MINIMUM value within spread. + Data checkedDataMin = DataBuilder.buildDecimal(95.0); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with checked parameter's run value set to MAXIMUM value within spread. + Data checkedDataMax = DataBuilder.buildDecimal(105.0); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL parameters outside the required spread. + */ + @Test + public void testDecimalParametersOutsideSpread() { + checkedParameter.setDataType(DataType.DECIMAL); + otherParameter.setDataType(DataType.DECIMAL); + + // Set a spread of 5%. + parameterSpreadCheck.setPercent(5); + + // Initialize other parameter's run value. + Data otherData = DataBuilder.buildDecimal(100.0); + + InstrumentRunValue otherRunValue = new InstrumentRunValue(); + otherRunValue.setInstrumentParameter(otherParameter); + otherRunValue.setData(otherData); + + // Test with checked parameter's run value set to LESS than the minimum value in spread. + Data checkedDataMin = DataBuilder.buildDecimal(94.0); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMin, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with checked parameter's run value set to MORE than the maximum value in spread. + Data checkedDataMax = DataBuilder.buildDecimal(106.0); + + expect(activeInstrumentRunServiceMock.getInputInstrumentRunValue(otherParameter.getName())).andReturn(otherRunValue); + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(parameterSpreadCheck.checkParameterValue(checkedDataMax, instrumentRunServiceMock, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheckTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheckTest.java index 4f5e4ab95..75e752201 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheckTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/domain/instrument/validation/RangeCheckTest.java @@ -1,315 +1,324 @@ -package org.obiba.onyx.jade.core.domain.instrument.validation; - -import static org.easymock.EasyMock.*; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -public class RangeCheckTest { - - private RangeCheck rangeCheck; - - private Participant participant; - - private InstrumentParameter instrumentParameter; - - private ActiveInstrumentRunService activeInstrumentRunServiceMock; - - @Before - public void setUp() { - rangeCheck = new RangeCheck(); - - participant = new Participant(); - participant.setGender(Gender.MALE); - - instrumentParameter = new InstrumentInputParameter(); - rangeCheck.setTargetParameter(instrumentParameter); - - activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); - } - - /** - * Tests DataType.INTEGER value within range. - */ - @Test - public void testIntegerWithinRange() { - instrumentParameter.setDataType(DataType.INTEGER); - - long minValue = 100l; - long maxValue = 200l; - - rangeCheck.setIntegerMinValueMale(minValue); - rangeCheck.setIntegerMaxValueMale(maxValue); - - // Test with run value in the middle of the range. - Data middleData = DataBuilder.buildInteger(150l); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(middleData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value equal to the minimum. - Data minData = DataBuilder.buildInteger(100l); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value equal to the maximum. - Data maxData = DataBuilder.buildInteger(200l); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.INTEGER value out of range. - */ - @Test - public void testIntegerOutOfRange() { - instrumentParameter.setDataType(DataType.INTEGER); - - long minValue = 100l; - long maxValue = 200l; - - rangeCheck.setIntegerMinValueMale(minValue); - rangeCheck.setIntegerMaxValueMale(maxValue); - - // Test with run value less than the minimum. - Data tooSmallData = DataBuilder.buildInteger(99l); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(rangeCheck.checkParameterValue(tooSmallData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value greater than the maximum. - Data tooBigData = DataBuilder.buildInteger(201l); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(rangeCheck.checkParameterValue(tooBigData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.INTEGER value with a range that has a maximum but no - * minimum. - */ - @Test - public void testIntegerNoMinimum() { - instrumentParameter.setDataType(DataType.INTEGER); - - rangeCheck.setIntegerMinValueMale(null); - rangeCheck.setIntegerMaxValueMale(200l); - - // Test run value of Long.MIN_VALUE. - Data minData = DataBuilder.buildInteger(Long.MIN_VALUE); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.INTEGER value with a range that has a minimum but no - * maximum. - */ - @Test - public void testIntegerNoMaximum() { - instrumentParameter.setDataType(DataType.INTEGER); - - rangeCheck.setIntegerMinValueMale(100l); - rangeCheck.setIntegerMaxValueMale(null); - - // Test run value of Long.MAX_VALUE. - Data maxData = DataBuilder.buildInteger(Long.MAX_VALUE); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL value within range. - */ - @Test - public void testDecimalWithinRange() { - instrumentParameter.setDataType(DataType.DECIMAL); - - double minValue = 100.0; - double maxValue = 200.0; - - rangeCheck.setDecimalMinValueMale(minValue); - rangeCheck.setDecimalMaxValueMale(maxValue); - - // Test with run value in the middle of the range. - Data middleData = DataBuilder.buildDecimal(150.0); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(middleData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value equal to the minimum. - Data minData = DataBuilder.buildDecimal(100.0); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value equal to the maximum. - Data maxData = DataBuilder.buildDecimal(200.0); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL value out of range. - */ - @Test - public void testDecimalOutOfRange() { - instrumentParameter.setDataType(DataType.DECIMAL); - - double minValue = 100.0; - double maxValue = 200.0; - - rangeCheck.setDecimalMinValueMale(minValue); - rangeCheck.setDecimalMaxValueMale(maxValue); - - // Test with run value less than the minimum. - Data tooSmallData = DataBuilder.buildDecimal(99.0); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(rangeCheck.checkParameterValue(tooSmallData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - - // Reset mocks. - reset(activeInstrumentRunServiceMock); - - // Test with run value greater than the maximum. - Data tooBigData = DataBuilder.buildDecimal(201.0); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertFalse(rangeCheck.checkParameterValue(tooBigData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL value with a range that has a maximum but no - * minimum. - */ - @Test - public void testDecimalNoMinimum() { - instrumentParameter.setDataType(DataType.DECIMAL); - - rangeCheck.setDecimalMinValueMale(null); - rangeCheck.setDecimalMaxValueMale(200.0); - - // Test run value of Double.MIN_VALUE. - Data minData = DataBuilder.buildDecimal(Double.MIN_VALUE); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } - - /** - * Tests DataType.DECIMAL value with a range that has a minimum but no - * maximum. - */ - @Test - public void testDecimalNoMaximum() { - instrumentParameter.setDataType(DataType.DECIMAL); - - rangeCheck.setDecimalMinValueMale(100.0); - rangeCheck.setDecimalMaxValueMale(null); - - // Test run value of Double.MAX_VALUE. - Data maxData = DataBuilder.buildDecimal(Double.MAX_VALUE); - - expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); - - replay(activeInstrumentRunServiceMock); - - Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); - - verify(activeInstrumentRunServiceMock); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.domain.instrument.validation; + +import static org.easymock.EasyMock.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentInputParameter; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentParameter; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +public class RangeCheckTest { + + private RangeCheck rangeCheck; + + private Participant participant; + + private InstrumentParameter instrumentParameter; + + private ActiveInstrumentRunService activeInstrumentRunServiceMock; + + @Before + public void setUp() { + rangeCheck = new RangeCheck(); + + participant = new Participant(); + participant.setGender(Gender.MALE); + + instrumentParameter = new InstrumentInputParameter(); + rangeCheck.setTargetParameter(instrumentParameter); + + activeInstrumentRunServiceMock = createMock(ActiveInstrumentRunService.class); + } + + /** + * Tests DataType.INTEGER value within range. + */ + @Test + public void testIntegerWithinRange() { + instrumentParameter.setDataType(DataType.INTEGER); + + long minValue = 100l; + long maxValue = 200l; + + rangeCheck.setIntegerMinValueMale(minValue); + rangeCheck.setIntegerMaxValueMale(maxValue); + + // Test with run value in the middle of the range. + Data middleData = DataBuilder.buildInteger(150l); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(middleData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value equal to the minimum. + Data minData = DataBuilder.buildInteger(100l); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value equal to the maximum. + Data maxData = DataBuilder.buildInteger(200l); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.INTEGER value out of range. + */ + @Test + public void testIntegerOutOfRange() { + instrumentParameter.setDataType(DataType.INTEGER); + + long minValue = 100l; + long maxValue = 200l; + + rangeCheck.setIntegerMinValueMale(minValue); + rangeCheck.setIntegerMaxValueMale(maxValue); + + // Test with run value less than the minimum. + Data tooSmallData = DataBuilder.buildInteger(99l); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(rangeCheck.checkParameterValue(tooSmallData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value greater than the maximum. + Data tooBigData = DataBuilder.buildInteger(201l); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(rangeCheck.checkParameterValue(tooBigData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.INTEGER value with a range that has a maximum but no + * minimum. + */ + @Test + public void testIntegerNoMinimum() { + instrumentParameter.setDataType(DataType.INTEGER); + + rangeCheck.setIntegerMinValueMale(null); + rangeCheck.setIntegerMaxValueMale(200l); + + // Test run value of Long.MIN_VALUE. + Data minData = DataBuilder.buildInteger(Long.MIN_VALUE); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.INTEGER value with a range that has a minimum but no + * maximum. + */ + @Test + public void testIntegerNoMaximum() { + instrumentParameter.setDataType(DataType.INTEGER); + + rangeCheck.setIntegerMinValueMale(100l); + rangeCheck.setIntegerMaxValueMale(null); + + // Test run value of Long.MAX_VALUE. + Data maxData = DataBuilder.buildInteger(Long.MAX_VALUE); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL value within range. + */ + @Test + public void testDecimalWithinRange() { + instrumentParameter.setDataType(DataType.DECIMAL); + + double minValue = 100.0; + double maxValue = 200.0; + + rangeCheck.setDecimalMinValueMale(minValue); + rangeCheck.setDecimalMaxValueMale(maxValue); + + // Test with run value in the middle of the range. + Data middleData = DataBuilder.buildDecimal(150.0); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(middleData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value equal to the minimum. + Data minData = DataBuilder.buildDecimal(100.0); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value equal to the maximum. + Data maxData = DataBuilder.buildDecimal(200.0); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL value out of range. + */ + @Test + public void testDecimalOutOfRange() { + instrumentParameter.setDataType(DataType.DECIMAL); + + double minValue = 100.0; + double maxValue = 200.0; + + rangeCheck.setDecimalMinValueMale(minValue); + rangeCheck.setDecimalMaxValueMale(maxValue); + + // Test with run value less than the minimum. + Data tooSmallData = DataBuilder.buildDecimal(99.0); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(rangeCheck.checkParameterValue(tooSmallData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + + // Reset mocks. + reset(activeInstrumentRunServiceMock); + + // Test with run value greater than the maximum. + Data tooBigData = DataBuilder.buildDecimal(201.0); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertFalse(rangeCheck.checkParameterValue(tooBigData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL value with a range that has a maximum but no + * minimum. + */ + @Test + public void testDecimalNoMinimum() { + instrumentParameter.setDataType(DataType.DECIMAL); + + rangeCheck.setDecimalMinValueMale(null); + rangeCheck.setDecimalMaxValueMale(200.0); + + // Test run value of Double.MIN_VALUE. + Data minData = DataBuilder.buildDecimal(Double.MIN_VALUE); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(minData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } + + /** + * Tests DataType.DECIMAL value with a range that has a minimum but no + * maximum. + */ + @Test + public void testDecimalNoMaximum() { + instrumentParameter.setDataType(DataType.DECIMAL); + + rangeCheck.setDecimalMinValueMale(100.0); + rangeCheck.setDecimalMaxValueMale(null); + + // Test run value of Double.MAX_VALUE. + Data maxData = DataBuilder.buildDecimal(Double.MAX_VALUE); + + expect(activeInstrumentRunServiceMock.getParticipant()).andReturn(participant); + + replay(activeInstrumentRunServiceMock); + + Assert.assertTrue(rangeCheck.checkParameterValue(maxData, null, activeInstrumentRunServiceMock)); + + verify(activeInstrumentRunServiceMock); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/service/InstrumentServiceTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/service/InstrumentServiceTest.java index 458444d2d..0bcaf5b90 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/service/InstrumentServiceTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/core/service/InstrumentServiceTest.java @@ -1,54 +1,63 @@ -package org.obiba.onyx.jade.core.service; - -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.service.InstrumentService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class InstrumentServiceTest extends BaseDefaultSpringContextTestCase { - - @Autowired(required=true) - PersistenceManager persistenceManager; - - @Autowired(required=true) - InstrumentService instrumentService; - - @Test - @Dataset - public void testInstrumentType() { - InstrumentType type1 = instrumentService.createInstrumentType("BLP", "Blood pressure"); - - flushCache(); - - type1 = persistenceManager.get(InstrumentType.class, type1.getId()); - Assert.assertTrue("No type 1", type1 != null); - - List instruments = instrumentService.getInstruments("STA"); - Assert.assertEquals("Wrong STA instrument count", 2, instruments.size()); - } - - @Test - @Dataset - public void testInstrumentTypeDependencies() { - - Assert.assertEquals("Wrong STA depends on count", 0, instrumentService.getInstrumentType("STA").getDependsOnTypes().size()); - Assert.assertEquals("Wrong STA dependent count", 2, instrumentService.getInstrumentType("STA").getDependentTypes().size()); - - Assert.assertEquals("Wrong STA depends on count", 1, instrumentService.getInstrumentType("BIM").getDependsOnTypes().size()); - Assert.assertEquals("Wrong STA dependent count", 1, instrumentService.getInstrumentType("BIM").getDependentTypes().size()); - - Assert.assertEquals("Wrong STA depends on count", 2, instrumentService.getInstrumentType("SPI").getDependsOnTypes().size()); - Assert.assertEquals("Wrong STA dependent count", 0, instrumentService.getInstrumentType("SPI").getDependentTypes().size()); - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.core.service; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.service.InstrumentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class InstrumentServiceTest extends BaseDefaultSpringContextTestCase { + + @Autowired(required=true) + PersistenceManager persistenceManager; + + @Autowired(required=true) + InstrumentService instrumentService; + + @Test + @Dataset + public void testInstrumentType() { + InstrumentType type1 = instrumentService.createInstrumentType("BLP", "Blood pressure"); + + flushCache(); + + type1 = persistenceManager.get(InstrumentType.class, type1.getId()); + Assert.assertTrue("No type 1", type1 != null); + + List instruments = instrumentService.getInstruments("STA"); + Assert.assertEquals("Wrong STA instrument count", 2, instruments.size()); + } + + @Test + @Dataset + public void testInstrumentTypeDependencies() { + + Assert.assertEquals("Wrong STA depends on count", 0, instrumentService.getInstrumentType("STA").getDependsOnTypes().size()); + Assert.assertEquals("Wrong STA dependent count", 2, instrumentService.getInstrumentType("STA").getDependentTypes().size()); + + Assert.assertEquals("Wrong STA depends on count", 1, instrumentService.getInstrumentType("BIM").getDependsOnTypes().size()); + Assert.assertEquals("Wrong STA dependent count", 1, instrumentService.getInstrumentType("BIM").getDependentTypes().size()); + + Assert.assertEquals("Wrong STA depends on count", 2, instrumentService.getInstrumentType("SPI").getDependsOnTypes().size()); + Assert.assertEquals("Wrong STA dependent count", 0, instrumentService.getInstrumentType("SPI").getDependentTypes().size()); + + } + +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeSkippedStateTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeSkippedStateTest.java index 694ba3a51..c01d37d43 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeSkippedStateTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeSkippedStateTest.java @@ -1,53 +1,62 @@ -package org.obiba.onyx.jade.engine.state; - -import static org.easymock.EasyMock.*; - -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Test; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.engine.Action; -import org.springframework.context.ApplicationContext; - -public class JadeSkippedStateTest { - - /** - * Tests that the state's message includes the name of the state followed by the - * reason the state was reached, between parentheses. - */ - @Test - public void testMessageIncludesReasonIfThereIsOne() { - String state = "Jade.Skipped"; - String reasonSkipped = "DEFECTIVE_INSTRUMENT"; - Locale locale = new Locale("en"); - - JadeSkippedState skippedState = new JadeSkippedState(); - - UserSessionService userSessionServiceMock = createMock(UserSessionService.class); - skippedState.setUserSessionService(userSessionServiceMock); - - expect(userSessionServiceMock.getLocale()).andReturn(locale); - - ApplicationContext applicationContextMock = createMock(ApplicationContext.class); - skippedState.setApplicationContext(applicationContextMock); - - expect(applicationContextMock.getMessage(state, null, locale)).andReturn("Skipped"); - expect(applicationContextMock.getMessage(reasonSkipped, null, locale)).andReturn("Defective instrument"); - - Action reasonSkippedAction = new Action(); - reasonSkippedAction.setEventReason(reasonSkipped); - skippedState.setReason(reasonSkippedAction); - - replay(userSessionServiceMock); - replay(applicationContextMock); - - String message = skippedState.getMessage(); - - verify(userSessionServiceMock); - verify(applicationContextMock); - - String expectedMessage = "Skipped (Defective instrument)"; - Assert.assertEquals(expectedMessage, message); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.engine.state; + +import static org.easymock.EasyMock.*; + +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Test; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.engine.Action; +import org.springframework.context.ApplicationContext; + +public class JadeSkippedStateTest { + + /** + * Tests that the state's message includes the name of the state followed by the + * reason the state was reached, between parentheses. + */ + @Test + public void testMessageIncludesReasonIfThereIsOne() { + String state = "Jade.Skipped"; + String reasonSkipped = "DEFECTIVE_INSTRUMENT"; + Locale locale = new Locale("en"); + + JadeSkippedState skippedState = new JadeSkippedState(); + + UserSessionService userSessionServiceMock = createMock(UserSessionService.class); + skippedState.setUserSessionService(userSessionServiceMock); + + expect(userSessionServiceMock.getLocale()).andReturn(locale); + + ApplicationContext applicationContextMock = createMock(ApplicationContext.class); + skippedState.setApplicationContext(applicationContextMock); + + expect(applicationContextMock.getMessage(state, null, locale)).andReturn("Skipped"); + expect(applicationContextMock.getMessage(reasonSkipped, null, locale)).andReturn("Defective instrument"); + + Action reasonSkippedAction = new Action(); + reasonSkippedAction.setEventReason(reasonSkipped); + skippedState.setReason(reasonSkippedAction); + + replay(userSessionServiceMock); + replay(applicationContextMock); + + String message = skippedState.getMessage(); + + verify(userSessionServiceMock); + verify(applicationContextMock); + + String expectedMessage = "Skipped (Defective instrument)"; + Assert.assertEquals(expectedMessage, message); + } +} diff --git a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyConditionTest.java b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyConditionTest.java index e7a3b488f..7b16571b1 100644 --- a/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyConditionTest.java +++ b/onyx-modules/jade/jade-core/src/test/java/org/obiba/onyx/jade/engine/state/JadeStageDependencyConditionTest.java @@ -1,170 +1,179 @@ -package org.obiba.onyx.jade.engine.state; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import junit.framework.Assert; - -import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.InstrumentRunService; -import org.obiba.onyx.jade.core.service.InstrumentService; - -public class JadeStageDependencyConditionTest { - - private ActiveInterviewService activeInterviewServiceMock; - - private InstrumentService instrumentServiceMock; - - private InstrumentRunService instrumentRunServiceMock; - - private JadeStageDependencyCondition dependencyCondition; - - @Before - public void setup() { - - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - instrumentServiceMock = createMock(InstrumentService.class); - instrumentRunServiceMock = createMock(InstrumentRunService.class); - - dependencyCondition = new JadeStageDependencyCondition(); - dependencyCondition.setStageName("stageMock"); - dependencyCondition.setInstrumentService(instrumentServiceMock); - dependencyCondition.setInstrumentRunService(instrumentRunServiceMock); - - } - - @Test - public void testUncompletedCondition() { - - IStageExecution stageExecution = new StageExecutionContext() { - @Override - public String getName() { - return "stageMock"; - }; - - @Override - public boolean isCompleted() { - return false; - }; - }; - - expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); - - replay(activeInterviewServiceMock); - - Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); - - verify(activeInterviewServiceMock); - - Assert.assertEquals(null, conditionResult); - } - - @Test - public void testCompletedNoResultCondition() { - - IStageExecution stageExecution = new StageExecutionContext() { - @Override - public String getName() { - return "stageMock"; - }; - - @Override - public boolean isCompleted() { - return true; - }; - }; - - expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); - expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); - expect(instrumentServiceMock.getInstrumentType("stageMock")).andReturn(newTestInstrumentType()); - expect(instrumentRunServiceMock.getLastCompletedInstrumentRun((Participant) EasyMock.anyObject(), (InstrumentType) EasyMock.anyObject())).andReturn(newTestInstrumentRun(false)); - - replay(activeInterviewServiceMock); - replay(instrumentServiceMock); - replay(instrumentRunServiceMock); - - Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); - - verify(activeInterviewServiceMock); - verify(instrumentServiceMock); - verify(instrumentRunServiceMock); - - Assert.assertEquals((Boolean) false, conditionResult); - } - - @Test - public void testCompletedWithResultCondition() { - - IStageExecution stageExecution = new StageExecutionContext() { - @Override - public String getName() { - return "stageMock"; - }; - - @Override - public boolean isCompleted() { - return true; - }; - }; - - expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); - expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); - expect(instrumentServiceMock.getInstrumentType("stageMock")).andReturn(newTestInstrumentType()); - expect(instrumentRunServiceMock.getLastCompletedInstrumentRun((Participant) EasyMock.anyObject(), (InstrumentType) EasyMock.anyObject())).andReturn(newTestInstrumentRun(true)); - - replay(activeInterviewServiceMock); - replay(instrumentServiceMock); - replay(instrumentRunServiceMock); - - Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); - - verify(activeInterviewServiceMock); - verify(instrumentServiceMock); - verify(instrumentRunServiceMock); - - Assert.assertEquals((Boolean) true, conditionResult); - } - - private Participant newTestParticipant() { - Participant p = new Participant(); - - p.setId("1"); - p.setBarcode("1"); - p.setFirstName("Suzan"); - p.setLastName("Tremblay"); - p.setGender(Gender.FEMALE); - - return (p); - } - - private InstrumentType newTestInstrumentType() { - InstrumentType iT = new InstrumentType(); - - iT.setName("stageMock"); - - return (iT); - } - - private InstrumentRun newTestInstrumentRun(boolean wantResults) { - InstrumentRun iR = new InstrumentRun(); - - if(wantResults == true) { - iR.addInstrumentRunValue(new InstrumentRunValue()); - } - - return (iR); - }; -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.engine.state; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import junit.framework.Assert; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.InstrumentRunService; +import org.obiba.onyx.jade.core.service.InstrumentService; + +public class JadeStageDependencyConditionTest { + + private ActiveInterviewService activeInterviewServiceMock; + + private InstrumentService instrumentServiceMock; + + private InstrumentRunService instrumentRunServiceMock; + + private JadeStageDependencyCondition dependencyCondition; + + @Before + public void setup() { + + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + instrumentServiceMock = createMock(InstrumentService.class); + instrumentRunServiceMock = createMock(InstrumentRunService.class); + + dependencyCondition = new JadeStageDependencyCondition(); + dependencyCondition.setStageName("stageMock"); + dependencyCondition.setInstrumentService(instrumentServiceMock); + dependencyCondition.setInstrumentRunService(instrumentRunServiceMock); + + } + + @Test + public void testUncompletedCondition() { + + IStageExecution stageExecution = new StageExecutionContext() { + @Override + public String getName() { + return "stageMock"; + }; + + @Override + public boolean isCompleted() { + return false; + }; + }; + + expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); + + replay(activeInterviewServiceMock); + + Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); + + verify(activeInterviewServiceMock); + + Assert.assertEquals(null, conditionResult); + } + + @Test + public void testCompletedNoResultCondition() { + + IStageExecution stageExecution = new StageExecutionContext() { + @Override + public String getName() { + return "stageMock"; + }; + + @Override + public boolean isCompleted() { + return true; + }; + }; + + expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); + expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); + expect(instrumentServiceMock.getInstrumentType("stageMock")).andReturn(newTestInstrumentType()); + expect(instrumentRunServiceMock.getLastCompletedInstrumentRun((Participant) EasyMock.anyObject(), (InstrumentType) EasyMock.anyObject())).andReturn(newTestInstrumentRun(false)); + + replay(activeInterviewServiceMock); + replay(instrumentServiceMock); + replay(instrumentRunServiceMock); + + Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); + + verify(activeInterviewServiceMock); + verify(instrumentServiceMock); + verify(instrumentRunServiceMock); + + Assert.assertEquals((Boolean) false, conditionResult); + } + + @Test + public void testCompletedWithResultCondition() { + + IStageExecution stageExecution = new StageExecutionContext() { + @Override + public String getName() { + return "stageMock"; + }; + + @Override + public boolean isCompleted() { + return true; + }; + }; + + expect(activeInterviewServiceMock.getStageExecution("stageMock")).andReturn(stageExecution); + expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); + expect(instrumentServiceMock.getInstrumentType("stageMock")).andReturn(newTestInstrumentType()); + expect(instrumentRunServiceMock.getLastCompletedInstrumentRun((Participant) EasyMock.anyObject(), (InstrumentType) EasyMock.anyObject())).andReturn(newTestInstrumentRun(true)); + + replay(activeInterviewServiceMock); + replay(instrumentServiceMock); + replay(instrumentRunServiceMock); + + Boolean conditionResult = dependencyCondition.isDependencySatisfied(activeInterviewServiceMock); + + verify(activeInterviewServiceMock); + verify(instrumentServiceMock); + verify(instrumentRunServiceMock); + + Assert.assertEquals((Boolean) true, conditionResult); + } + + private Participant newTestParticipant() { + Participant p = new Participant(); + + p.setId("1"); + p.setBarcode("1"); + p.setFirstName("Suzan"); + p.setLastName("Tremblay"); + p.setGender(Gender.FEMALE); + + return (p); + } + + private InstrumentType newTestInstrumentType() { + InstrumentType iT = new InstrumentType(); + + iT.setName("stageMock"); + + return (iT); + } + + private InstrumentRun newTestInstrumentRun(boolean wantResults) { + InstrumentRun iR = new InstrumentRun(); + + if(wantResults == true) { + iR.addInstrumentRunValue(new InstrumentRunValue()); + } + + return (iR); + }; +} diff --git a/onyx-modules/jade/jade-remote-api/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionService.java b/onyx-modules/jade/jade-remote-api/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionService.java index 505e64caa..a88489d11 100644 --- a/onyx-modules/jade/jade-remote-api/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionService.java +++ b/onyx-modules/jade/jade-remote-api/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionService.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.jade.instrument.service; import java.util.Date; diff --git a/onyx-modules/jade/jade-remote-server/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceImpl.java b/onyx-modules/jade/jade-remote-server/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceImpl.java index e2e1a76f1..4017d16b2 100644 --- a/onyx-modules/jade/jade-remote-server/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceImpl.java +++ b/onyx-modules/jade/jade-remote-server/src/main/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceImpl.java @@ -1,97 +1,106 @@ -package org.obiba.onyx.jade.instrument.service; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.obiba.onyx.util.data.Data; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class InstrumentExecutionServiceImpl extends PersistenceManagerAwareService implements InstrumentExecutionService { - - private static final Logger log = LoggerFactory.getLogger(InstrumentExecutionServiceImpl.class); - - private ActiveInstrumentRunService activeInstrumentRunService; - - public void setActiveInstrumentRunService(ActiveInstrumentRunService activeInstrumentRunService) { - this.activeInstrumentRunService = activeInstrumentRunService; - } - - private InstrumentRun getInstrumentRun() { - return activeInstrumentRunService.getInstrumentRun(); - } - - public String getInstrumentOperator() { - return getInstrumentRun().getUser().getFullName(); - } - - public String getParticipantFirstName() { - return (getInstrumentRun().getParticipantInterview().getParticipant().getFirstName()); - } - - public String getParticipantLastName() { - return (getInstrumentRun().getParticipantInterview().getParticipant().getLastName()); - } - - public Date getParticipantBirthDate() { - return (getInstrumentRun().getParticipantInterview().getParticipant().getBirthDate()); - } - - public String getParticipantGender() { - return (getInstrumentRun().getParticipantInterview().getParticipant().getGender().toString()); - } - - public String getParticipantID() { - return (getInstrumentRun().getParticipantInterview().getParticipant().getBarcode()); - } - - public Map getInputParametersValue(String... parameters) { - Map inputParametersValue = new HashMap(); - for(String parameterName : parameters) { - InstrumentRunValue inputParameterValue = activeInstrumentRunService.getInputInstrumentRunValue(parameterName); - inputParametersValue.put(inputParameterValue.getInstrumentParameter().getName(), inputParameterValue.getData()); - } - log.info("getInputParametersValue(" + parameters + ")=" + inputParametersValue); - return (inputParametersValue); - } - - public Data getInputParameterValue(String parameterName) { - return activeInstrumentRunService.getInputInstrumentRunValue(parameterName).getData(); - } - - public void addOutputParameterValues(Map values) { - for(Map.Entry entry : values.entrySet()) { - addOutputParameterValue(entry.getKey(), entry.getValue()); - } - } - - public void addOutputParameterValue(String name, Data value) { - log.info("addOutputParameterValue(" + name + ", " + value + ")"); - InstrumentRunValue outputParameterValue = activeInstrumentRunService.getOutputInstrumentRunValue(name); - outputParameterValue.setData(value); - getPersistenceManager().save(outputParameterValue); - } - - public void instrumentRunnerError(Exception error) { - InstrumentRun run = getInstrumentRun(); - Instrument instrument = run.getInstrument(); - User user = run.getUser(); - - log.error("Instrument runner error (run id={}) encountered on {} (Vendor={}, Model={}, Barcode={}) by {} (username={}) : ", new Object[] { run.getId(), instrument.getName(), instrument.getVendor(), instrument.getModel(), instrument.getBarcode(), user.getFullName(), user.getLogin() }); - log.error("Error stack trace:", error); - - run.setStatus(InstrumentRunStatus.IN_ERROR); - getPersistenceManager().save(run); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.obiba.onyx.util.data.Data; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class InstrumentExecutionServiceImpl extends PersistenceManagerAwareService implements InstrumentExecutionService { + + private static final Logger log = LoggerFactory.getLogger(InstrumentExecutionServiceImpl.class); + + private ActiveInstrumentRunService activeInstrumentRunService; + + public void setActiveInstrumentRunService(ActiveInstrumentRunService activeInstrumentRunService) { + this.activeInstrumentRunService = activeInstrumentRunService; + } + + private InstrumentRun getInstrumentRun() { + return activeInstrumentRunService.getInstrumentRun(); + } + + public String getInstrumentOperator() { + return getInstrumentRun().getUser().getFullName(); + } + + public String getParticipantFirstName() { + return (getInstrumentRun().getParticipantInterview().getParticipant().getFirstName()); + } + + public String getParticipantLastName() { + return (getInstrumentRun().getParticipantInterview().getParticipant().getLastName()); + } + + public Date getParticipantBirthDate() { + return (getInstrumentRun().getParticipantInterview().getParticipant().getBirthDate()); + } + + public String getParticipantGender() { + return (getInstrumentRun().getParticipantInterview().getParticipant().getGender().toString()); + } + + public String getParticipantID() { + return (getInstrumentRun().getParticipantInterview().getParticipant().getBarcode()); + } + + public Map getInputParametersValue(String... parameters) { + Map inputParametersValue = new HashMap(); + for(String parameterName : parameters) { + InstrumentRunValue inputParameterValue = activeInstrumentRunService.getInputInstrumentRunValue(parameterName); + inputParametersValue.put(inputParameterValue.getInstrumentParameter().getName(), inputParameterValue.getData()); + } + log.info("getInputParametersValue(" + parameters + ")=" + inputParametersValue); + return (inputParametersValue); + } + + public Data getInputParameterValue(String parameterName) { + return activeInstrumentRunService.getInputInstrumentRunValue(parameterName).getData(); + } + + public void addOutputParameterValues(Map values) { + for(Map.Entry entry : values.entrySet()) { + addOutputParameterValue(entry.getKey(), entry.getValue()); + } + } + + public void addOutputParameterValue(String name, Data value) { + log.info("addOutputParameterValue(" + name + ", " + value + ")"); + InstrumentRunValue outputParameterValue = activeInstrumentRunService.getOutputInstrumentRunValue(name); + outputParameterValue.setData(value); + getPersistenceManager().save(outputParameterValue); + } + + public void instrumentRunnerError(Exception error) { + InstrumentRun run = getInstrumentRun(); + Instrument instrument = run.getInstrument(); + User user = run.getUser(); + + log.error("Instrument runner error (run id={}) encountered on {} (Vendor={}, Model={}, Barcode={}) by {} (username={}) : ", new Object[] { run.getId(), instrument.getName(), instrument.getVendor(), instrument.getModel(), instrument.getBarcode(), user.getFullName(), user.getLogin() }); + log.error("Error stack trace:", error); + + run.setStatus(InstrumentRunStatus.IN_ERROR); + getPersistenceManager().save(run); + } + +} diff --git a/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceTest.java b/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceTest.java index b9d3cd8ae..fbc4748b6 100644 --- a/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceTest.java +++ b/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/InstrumentExecutionServiceTest.java @@ -1,93 +1,102 @@ -package org.obiba.onyx.jade.instrument.service; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.Dataset; -import org.obiba.core.test.spring.DbUnitAwareTestExecutionListener; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={"InstrumentExecutionServiceTest-context.xml"}) -@TransactionConfiguration(transactionManager="transactionManager") -@TestExecutionListeners(value={DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class,TransactionalTestExecutionListener.class,DbUnitAwareTestExecutionListener.class}) -public class InstrumentExecutionServiceTest { - - @Autowired(required=true) - PersistenceManager persistenceManager; - - @Autowired(required=true) - InstrumentExecutionService instrumentExecutionService; - - @Autowired(required=true) - ApplicationContext applicationContext; - - @Autowired(required=true) - ActiveInstrumentRunService activeInstrumentRunService; - - @Test - @Dataset - public void getOperator() { - Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); - Assert.assertEquals("tech technicien_1", instrumentExecutionService.getInstrumentOperator()); - } - - @Test - @Dataset - public void getParticipant() { - Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); - Assert.assertEquals("Dupont", instrumentExecutionService.getParticipantLastName()); - Assert.assertEquals("Laura", instrumentExecutionService.getParticipantFirstName()); - } - - @Test - @Dataset - public void updateInstrumentRunState() { -// Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); -// instrumentExecutionService.updateInstrumentRunState("IN_ERROR"); -// Assert.assertEquals("IN_ERROR", activeInstrumentRunService.getInstrumentRun().getStatus().toString()); - } - - @Test - @Dataset - public void addOutputParameterValues() { -// Map valuesMap = new HashMap(); -// valuesMap.put("density", new Data(DataType.INTEGER, Long.valueOf("125"))); -// valuesMap.put("strength", new Data(DataType.INTEGER, Long.valueOf("32"))); -// -// instrumentExecutionService.addOutputParameterValues(valuesMap); -// InstrumentRunValue template = new InstrumentRunValue(); -// template.setInstrumentRun(activeInstrumentRunService.getInstrumentRun()); -// List instrumentRunValues = persistenceManager.match(template); -// -// for (InstrumentRunValue instrumentRunValue : instrumentRunValues) { -// if (instrumentRunValue.getInstrumentParameter().getName().equals("density")) -// Assert.assertEquals(Long.valueOf("125"), instrumentRunValue.getData().getValue()); -// if (instrumentRunValue.getInstrumentParameter().getName().equals("strength")) -// Assert.assertEquals(Long.valueOf("32"), instrumentRunValue.getData().getValue()); -// } - } -} - - - - - - - - - - - - - +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.service; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.Dataset; +import org.obiba.core.test.spring.DbUnitAwareTestExecutionListener; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionConfiguration; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations={"InstrumentExecutionServiceTest-context.xml"}) +@TransactionConfiguration(transactionManager="transactionManager") +@TestExecutionListeners(value={DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class,TransactionalTestExecutionListener.class,DbUnitAwareTestExecutionListener.class}) +public class InstrumentExecutionServiceTest { + + @Autowired(required=true) + PersistenceManager persistenceManager; + + @Autowired(required=true) + InstrumentExecutionService instrumentExecutionService; + + @Autowired(required=true) + ApplicationContext applicationContext; + + @Autowired(required=true) + ActiveInstrumentRunService activeInstrumentRunService; + + @Test + @Dataset + public void getOperator() { + Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); + Assert.assertEquals("tech technicien_1", instrumentExecutionService.getInstrumentOperator()); + } + + @Test + @Dataset + public void getParticipant() { + Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); + Assert.assertEquals("Dupont", instrumentExecutionService.getParticipantLastName()); + Assert.assertEquals("Laura", instrumentExecutionService.getParticipantFirstName()); + } + + @Test + @Dataset + public void updateInstrumentRunState() { +// Assert.assertNotNull("No InstrumentRun", activeInstrumentRunService.getInstrumentRun()); +// instrumentExecutionService.updateInstrumentRunState("IN_ERROR"); +// Assert.assertEquals("IN_ERROR", activeInstrumentRunService.getInstrumentRun().getStatus().toString()); + } + + @Test + @Dataset + public void addOutputParameterValues() { +// Map valuesMap = new HashMap(); +// valuesMap.put("density", new Data(DataType.INTEGER, Long.valueOf("125"))); +// valuesMap.put("strength", new Data(DataType.INTEGER, Long.valueOf("32"))); +// +// instrumentExecutionService.addOutputParameterValues(valuesMap); +// InstrumentRunValue template = new InstrumentRunValue(); +// template.setInstrumentRun(activeInstrumentRunService.getInstrumentRun()); +// List instrumentRunValues = persistenceManager.match(template); +// +// for (InstrumentRunValue instrumentRunValue : instrumentRunValues) { +// if (instrumentRunValue.getInstrumentParameter().getName().equals("density")) +// Assert.assertEquals(Long.valueOf("125"), instrumentRunValue.getData().getValue()); +// if (instrumentRunValue.getInstrumentParameter().getName().equals("strength")) +// Assert.assertEquals(Long.valueOf("32"), instrumentRunValue.getData().getValue()); +// } + } +} + + + + + + + + + + + + + diff --git a/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/MockActiveInstrumentRunServiceImpl.java b/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/MockActiveInstrumentRunServiceImpl.java index 5179b13df..43a0b28ca 100644 --- a/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/MockActiveInstrumentRunServiceImpl.java +++ b/onyx-modules/jade/jade-remote-server/src/test/java/org/obiba/onyx/jade/instrument/service/MockActiveInstrumentRunServiceImpl.java @@ -1,125 +1,134 @@ -package org.obiba.onyx.jade.instrument.service; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; -import org.obiba.onyx.jade.core.domain.instrument.Instrument; -import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; -import org.obiba.onyx.jade.core.domain.run.InstrumentRun; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; -import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; -import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; -import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class MockActiveInstrumentRunServiceImpl extends PersistenceManagerAwareService implements ActiveInstrumentRunService { - - private InstrumentRun run = null; - - public void computeOutputParameters() { - } - - public InstrumentRun getInstrumentRun() { - if (run == null) { - //System.out.println("++++++++++++++++++++++++ run.count=" + getPersistenceManager().count(InstrumentRun.class)); - run = new InstrumentRun();//getPersistenceManager().get(InstrumentRun.class, 1l); - run.setUser(new User()); - run.getUser().setLastName("technicien_1"); - run.getUser().setFirstName("tech"); - run.setParticipantInterview(new ParticipantInterview()); - run.getParticipantInterview().setParticipant(new Participant()); - run.getParticipantInterview().getParticipant().setLastName("Dupont"); - run.getParticipantInterview().getParticipant().setFirstName("Laura"); - } - return run; - } - - public Participant getParticipant() { - return null; - } - - public void reset() { - } - - public InstrumentRun start(Participant participant, Instrument instrument) { - return null; - } - - public InstrumentRunValue getOutputInstrumentRunValue(String parameterName) { - // TODO Auto-generated method stub - return null; - } - - public InstrumentRunValue getInputInstrumentRunValue(String parameterName) { - // TODO Auto-generated method stub - return null; - } - - public Instrument getInstrument() { - // TODO Auto-generated method stub - return null; - } - - public InstrumentType getInstrumentType() { - // TODO Auto-generated method stub - return null; - } - - public void setInstrumentType(InstrumentType instrumentType) { - // TODO Auto-generated method stub - - } - - public ContraIndication getContraIndication() { - // TODO Auto-generated method stub - return null; - } - - public void setContraIndication(ContraIndication contraIndication) { - // TODO Auto-generated method stub - - } - - public void update(InstrumentRun currentRun) { - // TODO Auto-generated method stub - - } - - public String getOtherContraIndication() { - // TODO Auto-generated method stub - return null; - } - - public void setOtherContraIndication(String otherContraIndication) { - // TODO Auto-generated method stub - - } - - public InstrumentRunStatus getInstrumentRunStatus() { - // TODO Auto-generated method stub - return null; - } - - public void setInstrumentRunStatus(InstrumentRunStatus status) { - // TODO Auto-generated method stub - - } - - public void update(InstrumentRunValue currentRunValue) { - // TODO Auto-generated method stub - - } - - public void end() { - // TODO Auto-generated method stub - - } - - public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName) { - // TODO Auto-generated method stub - return null; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.jade.instrument.service; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.jade.core.domain.instrument.ContraIndication; +import org.obiba.onyx.jade.core.domain.instrument.Instrument; +import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; +import org.obiba.onyx.jade.core.domain.run.InstrumentRun; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunStatus; +import org.obiba.onyx.jade.core.domain.run.InstrumentRunValue; +import org.obiba.onyx.jade.core.domain.run.ParticipantInterview; +import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class MockActiveInstrumentRunServiceImpl extends PersistenceManagerAwareService implements ActiveInstrumentRunService { + + private InstrumentRun run = null; + + public void computeOutputParameters() { + } + + public InstrumentRun getInstrumentRun() { + if (run == null) { + //System.out.println("++++++++++++++++++++++++ run.count=" + getPersistenceManager().count(InstrumentRun.class)); + run = new InstrumentRun();//getPersistenceManager().get(InstrumentRun.class, 1l); + run.setUser(new User()); + run.getUser().setLastName("technicien_1"); + run.getUser().setFirstName("tech"); + run.setParticipantInterview(new ParticipantInterview()); + run.getParticipantInterview().setParticipant(new Participant()); + run.getParticipantInterview().getParticipant().setLastName("Dupont"); + run.getParticipantInterview().getParticipant().setFirstName("Laura"); + } + return run; + } + + public Participant getParticipant() { + return null; + } + + public void reset() { + } + + public InstrumentRun start(Participant participant, Instrument instrument) { + return null; + } + + public InstrumentRunValue getOutputInstrumentRunValue(String parameterName) { + // TODO Auto-generated method stub + return null; + } + + public InstrumentRunValue getInputInstrumentRunValue(String parameterName) { + // TODO Auto-generated method stub + return null; + } + + public Instrument getInstrument() { + // TODO Auto-generated method stub + return null; + } + + public InstrumentType getInstrumentType() { + // TODO Auto-generated method stub + return null; + } + + public void setInstrumentType(InstrumentType instrumentType) { + // TODO Auto-generated method stub + + } + + public ContraIndication getContraIndication() { + // TODO Auto-generated method stub + return null; + } + + public void setContraIndication(ContraIndication contraIndication) { + // TODO Auto-generated method stub + + } + + public void update(InstrumentRun currentRun) { + // TODO Auto-generated method stub + + } + + public String getOtherContraIndication() { + // TODO Auto-generated method stub + return null; + } + + public void setOtherContraIndication(String otherContraIndication) { + // TODO Auto-generated method stub + + } + + public InstrumentRunStatus getInstrumentRunStatus() { + // TODO Auto-generated method stub + return null; + } + + public void setInstrumentRunStatus(InstrumentRunStatus status) { + // TODO Auto-generated method stub + + } + + public void update(InstrumentRunValue currentRunValue) { + // TODO Auto-generated method stub + + } + + public void end() { + // TODO Auto-generated method stub + + } + + public InstrumentRunValue getInterpretativeInstrumentRunValue(String parameterName) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/ActiveConsentService.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/ActiveConsentService.java index 1bf918bd6..8e6242d37 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/ActiveConsentService.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/ActiveConsentService.java @@ -1,14 +1,23 @@ -package org.obiba.onyx.marble.core.service; - -import org.obiba.onyx.marble.domain.consent.Consent; -import org.obiba.onyx.marble.domain.consent.ConsentMode; - -public interface ActiveConsentService { - - public Consent getConsent(); - - public void setConsent(Consent consent); - - public ConsentMode getMode(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.service; + +import org.obiba.onyx.marble.domain.consent.Consent; +import org.obiba.onyx.marble.domain.consent.ConsentMode; + +public interface ActiveConsentService { + + public Consent getConsent(); + + public void setConsent(Consent consent); + + public ConsentMode getMode(); + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/impl/DefaultActiveConsentServiceImpl.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/impl/DefaultActiveConsentServiceImpl.java index 4e84ee26c..14ec34e50 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/impl/DefaultActiveConsentServiceImpl.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/service/impl/DefaultActiveConsentServiceImpl.java @@ -1,29 +1,38 @@ -package org.obiba.onyx.marble.core.service.impl; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.marble.domain.consent.Consent; -import org.obiba.onyx.marble.domain.consent.ConsentMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultActiveConsentServiceImpl extends PersistenceManagerAwareService implements ActiveConsentService { - - private static final Logger log = LoggerFactory.getLogger(DefaultActiveConsentServiceImpl.class); - - private Consent consent; - - public void setConsent(Consent consent) { - this.consent = consent; - } - - public Consent getConsent() { - return consent; - } - - public ConsentMode getMode() { - return consent.getMode(); - } - - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.service.impl; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.marble.domain.consent.Consent; +import org.obiba.onyx.marble.domain.consent.ConsentMode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DefaultActiveConsentServiceImpl extends PersistenceManagerAwareService implements ActiveConsentService { + + private static final Logger log = LoggerFactory.getLogger(DefaultActiveConsentServiceImpl.class); + + private Consent consent; + + public void setConsent(Consent consent) { + this.consent = consent; + } + + public Consent getConsent() { + return consent; + } + + public ConsentMode getMode() { + return consent.getMode(); + } + + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/MarblePanel.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/MarblePanel.java index 3cd2767de..5e5f36c7c 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/MarblePanel.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/MarblePanel.java @@ -1,139 +1,148 @@ -package org.obiba.onyx.marble.core.wicket; - -import java.io.Serializable; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.marble.core.wicket.wizard.ConsentWizardForm; -import org.obiba.onyx.marble.domain.consent.Consent; -import org.obiba.onyx.wicket.IEngineComponentAware; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MarblePanel extends Panel implements IEngineComponentAware { - - private static final long serialVersionUID = 1L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(MarblePanel.class); - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private ActionWindow actionWindow; - - private FeedbackPanel feedbackPanel; - - private MarbleModel model; - - Consent interviewConsent; - - @SuppressWarnings("serial") - public MarblePanel(String id, Stage stage) { - super(id); - - Consent interviewConsent = new Consent(); - interviewConsent.setInterview(activeInterviewService.getInterview()); - - model = new MarbleModel(new StageModel(moduleRegistry, stage.getName()), new Model(interviewConsent)); - - add(new WizardPanel("content", model.getConsentModel()) { - - @Override - public WizardForm createForm(String componentId) { - return new ConsentWizardForm(componentId, getModel()) { - - @Override - public void onCancel(AjaxRequestTarget target) { - IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); - ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); - if(actionDef != null) { - actionWindow.show(target, model.getStageModel(), actionDef); - } - } - - @Override - public void onFinish(AjaxRequestTarget target, Form form) { - IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); - ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); - if(actionDef != null) { - actionWindow.show(target, model.getStageModel(), actionDef); - } - } - - @Override - public void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedbackPanel); - } - - @Override - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - }; - } - - }); - } - - @SuppressWarnings("serial") - private class MarbleModel implements Serializable { - private IModel consentModel; - - private IModel stageModel; - - public MarbleModel(IModel stageModel, IModel consentModel) { - this.consentModel = consentModel; - this.stageModel = stageModel; - } - - public Consent getConsent() { - return (Consent)consentModel.getObject(); - } - - public IModel getConsentModel() { - return consentModel; - } - - public Stage getStage() { - return (Stage) stageModel.getObject(); - } - - public IModel getStageModel() { - return stageModel; - } - - } - - public void setActionWindwon(ActionWindow window) { - this.actionWindow = window; - } - - public void setFeedbackPanel(FeedbackPanel feedbackPanel) { - this.feedbackPanel = feedbackPanel; - } - - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket; + +import java.io.Serializable; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.marble.core.wicket.wizard.ConsentWizardForm; +import org.obiba.onyx.marble.domain.consent.Consent; +import org.obiba.onyx.wicket.IEngineComponentAware; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MarblePanel extends Panel implements IEngineComponentAware { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(MarblePanel.class); + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private ActionWindow actionWindow; + + private FeedbackPanel feedbackPanel; + + private MarbleModel model; + + Consent interviewConsent; + + @SuppressWarnings("serial") + public MarblePanel(String id, Stage stage) { + super(id); + + Consent interviewConsent = new Consent(); + interviewConsent.setInterview(activeInterviewService.getInterview()); + + model = new MarbleModel(new StageModel(moduleRegistry, stage.getName()), new Model(interviewConsent)); + + add(new WizardPanel("content", model.getConsentModel()) { + + @Override + public WizardForm createForm(String componentId) { + return new ConsentWizardForm(componentId, getModel()) { + + @Override + public void onCancel(AjaxRequestTarget target) { + IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); + ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); + if(actionDef != null) { + actionWindow.show(target, model.getStageModel(), actionDef); + } + } + + @Override + public void onFinish(AjaxRequestTarget target, Form form) { + IStageExecution exec = activeInterviewService.getStageExecution(model.getStage()); + ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); + if(actionDef != null) { + actionWindow.show(target, model.getStageModel(), actionDef); + } + } + + @Override + public void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedbackPanel); + } + + @Override + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + }; + } + + }); + } + + @SuppressWarnings("serial") + private class MarbleModel implements Serializable { + private IModel consentModel; + + private IModel stageModel; + + public MarbleModel(IModel stageModel, IModel consentModel) { + this.consentModel = consentModel; + this.stageModel = stageModel; + } + + public Consent getConsent() { + return (Consent)consentModel.getObject(); + } + + public IModel getConsentModel() { + return consentModel; + } + + public Stage getStage() { + return (Stage) stageModel.getObject(); + } + + public IModel getStageModel() { + return stageModel; + } + + } + + public void setActionWindwon(ActionWindow window) { + this.actionWindow = window; + } + + public void setFeedbackPanel(FeedbackPanel feedbackPanel) { + this.feedbackPanel = feedbackPanel; + } + + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentConfirmationPanel.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentConfirmationPanel.java index 43481092a..a575cd27c 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentConfirmationPanel.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentConfirmationPanel.java @@ -1,58 +1,67 @@ -package org.obiba.onyx.marble.core.wicket.consent; - -import java.util.Arrays; - -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.RadioChoice; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.marble.core.service.ActiveConsentService; - -public class ConsentConfirmationPanel extends Panel { - - private static final long serialVersionUID = 1L; - - @SpringBean - private ActiveConsentService activeConsentService; - - public ConsentConfirmationPanel(String id) { - super(id); - setOutputMarkupId(true); - - add(createConsentConfirmationRadio()); - } - - @SuppressWarnings("serial") - private RadioChoice createConsentConfirmationRadio() { - - IChoiceRenderer choiceRenderer = new IChoiceRenderer() { - - public Object getDisplayValue(Object object) { - return (new StringResourceModel("ConsentConfirmation." + object.toString(), ConsentConfirmationPanel.this, null).getString()); - } - - public String getIdValue(Object object, int index) { - return object.toString(); - } - }; - - RadioChoice consentConfirmation = new RadioChoice("consentConfirmation", new PropertyModel(activeConsentService.getConsent(), "accepted"), Arrays.asList(new Boolean[] { true, false }), choiceRenderer) { - - @Override - protected boolean localizeDisplayValues() { - return true; - } - }; - - consentConfirmation.setNullValid(true); - consentConfirmation.setRequired(true); - - return consentConfirmation; - } - - public void save() { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.consent; + +import java.util.Arrays; + +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.RadioChoice; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.marble.core.service.ActiveConsentService; + +public class ConsentConfirmationPanel extends Panel { + + private static final long serialVersionUID = 1L; + + @SpringBean + private ActiveConsentService activeConsentService; + + public ConsentConfirmationPanel(String id) { + super(id); + setOutputMarkupId(true); + + add(createConsentConfirmationRadio()); + } + + @SuppressWarnings("serial") + private RadioChoice createConsentConfirmationRadio() { + + IChoiceRenderer choiceRenderer = new IChoiceRenderer() { + + public Object getDisplayValue(Object object) { + return (new StringResourceModel("ConsentConfirmation." + object.toString(), ConsentConfirmationPanel.this, null).getString()); + } + + public String getIdValue(Object object, int index) { + return object.toString(); + } + }; + + RadioChoice consentConfirmation = new RadioChoice("consentConfirmation", new PropertyModel(activeConsentService.getConsent(), "accepted"), Arrays.asList(new Boolean[] { true, false }), choiceRenderer) { + + @Override + protected boolean localizeDisplayValues() { + return true; + } + }; + + consentConfirmation.setNullValid(true); + consentConfirmation.setRequired(true); + + return consentConfirmation; + } + + public void save() { + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentModeSelectionPanel.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentModeSelectionPanel.java index cf3838a30..e5d5db6ac 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentModeSelectionPanel.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ConsentModeSelectionPanel.java @@ -1,86 +1,95 @@ -package org.obiba.onyx.marble.core.wicket.consent; - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import org.apache.wicket.markup.html.form.ChoiceRenderer; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.RadioChoice; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.marble.domain.consent.ConsentMode; - -public class ConsentModeSelectionPanel extends Panel { - - private static final long serialVersionUID = 1L; - - private static final List consentLanguages = Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH }); - - @SpringBean - private ActiveConsentService activeConsentService; - - public ConsentModeSelectionPanel(String id) { - super(id); - setOutputMarkupId(true); - - add(createConsentModeRadio()); - add(createConsentLanguageDropDown()); - - } - - @SuppressWarnings("serial") - private RadioChoice createConsentModeRadio() { - RadioChoice consentModeRadio = new RadioChoice("consentMode", new PropertyModel(activeConsentService.getConsent(), "mode"), Arrays.asList(ConsentMode.values()), new ChoiceRenderer()) { - - @Override - protected boolean localizeDisplayValues() { - return true; - } - }; - - consentModeRadio.setRequired(true); - - return consentModeRadio; - } - - @SuppressWarnings("serial") - private DropDownChoice createConsentLanguageDropDown() { - - IChoiceRenderer choiceRenderer = new IChoiceRenderer() { - - public Object getDisplayValue(Object object) { - Locale lang = (Locale) object; - return lang.getDisplayLanguage(getLocale()); - } - - public String getIdValue(Object object, int index) { - return object.toString(); - } - - }; - - DropDownChoice consentLanguageDropDown = new DropDownChoice("consentLanguage", new PropertyModel(activeConsentService.getConsent(), "language"), consentLanguages, choiceRenderer) { - - @Override - protected boolean localizeDisplayValues() { - return true; - } - - }; - - consentLanguageDropDown.setRequired(true); - consentLanguageDropDown.setNullValid(true); - - return consentLanguageDropDown; - } - - public void save() { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.consent; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import org.apache.wicket.markup.html.form.ChoiceRenderer; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.RadioChoice; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.marble.domain.consent.ConsentMode; + +public class ConsentModeSelectionPanel extends Panel { + + private static final long serialVersionUID = 1L; + + private static final List consentLanguages = Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH }); + + @SpringBean + private ActiveConsentService activeConsentService; + + public ConsentModeSelectionPanel(String id) { + super(id); + setOutputMarkupId(true); + + add(createConsentModeRadio()); + add(createConsentLanguageDropDown()); + + } + + @SuppressWarnings("serial") + private RadioChoice createConsentModeRadio() { + RadioChoice consentModeRadio = new RadioChoice("consentMode", new PropertyModel(activeConsentService.getConsent(), "mode"), Arrays.asList(ConsentMode.values()), new ChoiceRenderer()) { + + @Override + protected boolean localizeDisplayValues() { + return true; + } + }; + + consentModeRadio.setRequired(true); + + return consentModeRadio; + } + + @SuppressWarnings("serial") + private DropDownChoice createConsentLanguageDropDown() { + + IChoiceRenderer choiceRenderer = new IChoiceRenderer() { + + public Object getDisplayValue(Object object) { + Locale lang = (Locale) object; + return lang.getDisplayLanguage(getLocale()); + } + + public String getIdValue(Object object, int index) { + return object.toString(); + } + + }; + + DropDownChoice consentLanguageDropDown = new DropDownChoice("consentLanguage", new PropertyModel(activeConsentService.getConsent(), "language"), consentLanguages, choiceRenderer) { + + @Override + protected boolean localizeDisplayValues() { + return true; + } + + }; + + consentLanguageDropDown.setRequired(true); + consentLanguageDropDown.setNullValid(true); + + return consentLanguageDropDown; + } + + public void save() { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ElectronicConsentPanel.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ElectronicConsentPanel.java index 0fed3fc38..0053226c7 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ElectronicConsentPanel.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/consent/ElectronicConsentPanel.java @@ -1,19 +1,28 @@ -package org.obiba.onyx.marble.core.wicket.consent; - -import org.apache.wicket.markup.html.panel.Panel; - -public class ElectronicConsentPanel extends Panel { - - private static final long serialVersionUID = 1L; - - public ElectronicConsentPanel(String id) { - super(id); - setOutputMarkupId(true); - } - - public void save() { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.consent; + +import org.apache.wicket.markup.html.panel.Panel; + +public class ElectronicConsentPanel extends Panel { + + private static final long serialVersionUID = 1L; + + public ElectronicConsentPanel(String id) { + super(id); + setOutputMarkupId(true); + } + + public void save() { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentConfirmationStep.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentConfirmationStep.java index 98813f688..55fd25ba1 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentConfirmationStep.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentConfirmationStep.java @@ -1,39 +1,48 @@ -package org.obiba.onyx.marble.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.marble.core.wicket.consent.ConsentConfirmationPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class ConsentConfirmationStep extends WizardStepPanel { - - private static final long serialVersionUID = 1L; - - private ConsentConfirmationPanel consentConfirmationPanel; - - public ConsentConfirmationStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label("title", new StringResourceModel("ConsentConfirmationTitle", this, null))); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(true); - form.getNextLink().setEnabled(false); - form.getFinishLink().setEnabled(true); - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, consentConfirmationPanel = new ConsentConfirmationPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - consentConfirmationPanel.save(); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.marble.core.wicket.consent.ConsentConfirmationPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class ConsentConfirmationStep extends WizardStepPanel { + + private static final long serialVersionUID = 1L; + + private ConsentConfirmationPanel consentConfirmationPanel; + + public ConsentConfirmationStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label("title", new StringResourceModel("ConsentConfirmationTitle", this, null))); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(true); + form.getNextLink().setEnabled(false); + form.getFinishLink().setEnabled(true); + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, consentConfirmationPanel = new ConsentConfirmationPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + consentConfirmationPanel.save(); + } +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentModeSelectionStep.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentModeSelectionStep.java index 2b5764817..0d5514a3a 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentModeSelectionStep.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentModeSelectionStep.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.marble.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.marble.core.wicket.consent.ConsentModeSelectionPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.obiba.onyx.marble.domain.consent.ConsentMode; - -public class ConsentModeSelectionStep extends WizardStepPanel { - - private static final long serialVersionUID = 1L; - - private ConsentModeSelectionPanel consentModeSelectionPanel; - - @SpringBean - private ActiveConsentService activeConsentService; - - WizardStepPanel electronicConsentStep; - WizardStepPanel consentConfirmationStep; - - public ConsentModeSelectionStep(String id, WizardStepPanel electronicConsentStep, WizardStepPanel consentConfirmationStep) { - super(id); - setOutputMarkupId(true); - this.electronicConsentStep = electronicConsentStep; - this.consentConfirmationStep = consentConfirmationStep; - - add(new Label("title", new StringResourceModel("ConsentModeSelectionTitle", this, null))); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getPreviousLink().setEnabled(false); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, consentModeSelectionPanel = new ConsentModeSelectionPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - if( activeConsentService.getMode().equals(ConsentMode.MANUAL) ) { - consentConfirmationStep.setPreviousStep(this); - setNextStep(consentConfirmationStep); - } else { - consentConfirmationStep.setPreviousStep(electronicConsentStep); - setNextStep(electronicConsentStep); - } - consentModeSelectionPanel.save(); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.marble.core.wicket.consent.ConsentModeSelectionPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.obiba.onyx.marble.domain.consent.ConsentMode; + +public class ConsentModeSelectionStep extends WizardStepPanel { + + private static final long serialVersionUID = 1L; + + private ConsentModeSelectionPanel consentModeSelectionPanel; + + @SpringBean + private ActiveConsentService activeConsentService; + + WizardStepPanel electronicConsentStep; + WizardStepPanel consentConfirmationStep; + + public ConsentModeSelectionStep(String id, WizardStepPanel electronicConsentStep, WizardStepPanel consentConfirmationStep) { + super(id); + setOutputMarkupId(true); + this.electronicConsentStep = electronicConsentStep; + this.consentConfirmationStep = consentConfirmationStep; + + add(new Label("title", new StringResourceModel("ConsentModeSelectionTitle", this, null))); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getPreviousLink().setEnabled(false); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, consentModeSelectionPanel = new ConsentModeSelectionPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + if( activeConsentService.getMode().equals(ConsentMode.MANUAL) ) { + consentConfirmationStep.setPreviousStep(this); + setNextStep(consentConfirmationStep); + } else { + consentConfirmationStep.setPreviousStep(electronicConsentStep); + setNextStep(electronicConsentStep); + } + consentModeSelectionPanel.save(); + } +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentWizardForm.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentWizardForm.java index f18400b6c..4b7eec9a8 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentWizardForm.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ConsentWizardForm.java @@ -1,86 +1,95 @@ -package org.obiba.onyx.marble.core.wicket.wizard; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.marble.domain.consent.Consent; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class ConsentWizardForm extends WizardForm { - - private static final Logger log = LoggerFactory.getLogger(ConsentWizardForm.class); - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveConsentService activeConsentService; - - private WizardStepPanel consentModeSelectionStep; - - private WizardStepPanel electronicConsentStep; - - private WizardStepPanel consentConfirmationStep; - - public ConsentWizardForm(String id, IModel interviewConsentModel) { - super(id); - - activeConsentService.setConsent((Consent) interviewConsentModel.getObject()); - - electronicConsentStep = new ElectronicConsentStep(getStepId()); - consentConfirmationStep = new ConsentConfirmationStep(getStepId()); - consentModeSelectionStep = new ConsentModeSelectionStep(getStepId(), electronicConsentStep, consentConfirmationStep); - - WizardStepPanel startStep = setupStaticWizardFlow(); - - startStep.onStepInNext(this, null); - startStep.handleWizardState(this, null); - add(startStep); - - } - - private WizardStepPanel setupStaticWizardFlow() { - WizardStepPanel startStep = consentModeSelectionStep; - startStep.setPreviousStep(startStep); - electronicConsentStep.setPreviousStep(startStep); - electronicConsentStep.setNextStep(consentConfirmationStep); - return startStep; - } - - public ActiveInterviewService getActiveInterviewService() { - return activeInterviewService; - } - - public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { - this.activeInterviewService = activeInterviewService; - } - - public WizardStepPanel getConsentModeSelectionStep() { - return consentModeSelectionStep; - } - - public void setConsentModeSelectionStep(WizardStepPanel consentModeSelectionStep) { - this.consentModeSelectionStep = consentModeSelectionStep; - } - - public WizardStepPanel getElectronicConsentStep() { - return electronicConsentStep; - } - - public void setElectronicConsentStep(WizardStepPanel electronicConsentStep) { - this.electronicConsentStep = electronicConsentStep; - } - - public WizardStepPanel getConsentConfirmationStep() { - return consentConfirmationStep; - } - - public void setConsentConfirmationStep(WizardStepPanel consentConfirmationStep) { - this.consentConfirmationStep = consentConfirmationStep; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.wizard; + +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.marble.domain.consent.Consent; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class ConsentWizardForm extends WizardForm { + + private static final Logger log = LoggerFactory.getLogger(ConsentWizardForm.class); + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveConsentService activeConsentService; + + private WizardStepPanel consentModeSelectionStep; + + private WizardStepPanel electronicConsentStep; + + private WizardStepPanel consentConfirmationStep; + + public ConsentWizardForm(String id, IModel interviewConsentModel) { + super(id); + + activeConsentService.setConsent((Consent) interviewConsentModel.getObject()); + + electronicConsentStep = new ElectronicConsentStep(getStepId()); + consentConfirmationStep = new ConsentConfirmationStep(getStepId()); + consentModeSelectionStep = new ConsentModeSelectionStep(getStepId(), electronicConsentStep, consentConfirmationStep); + + WizardStepPanel startStep = setupStaticWizardFlow(); + + startStep.onStepInNext(this, null); + startStep.handleWizardState(this, null); + add(startStep); + + } + + private WizardStepPanel setupStaticWizardFlow() { + WizardStepPanel startStep = consentModeSelectionStep; + startStep.setPreviousStep(startStep); + electronicConsentStep.setPreviousStep(startStep); + electronicConsentStep.setNextStep(consentConfirmationStep); + return startStep; + } + + public ActiveInterviewService getActiveInterviewService() { + return activeInterviewService; + } + + public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { + this.activeInterviewService = activeInterviewService; + } + + public WizardStepPanel getConsentModeSelectionStep() { + return consentModeSelectionStep; + } + + public void setConsentModeSelectionStep(WizardStepPanel consentModeSelectionStep) { + this.consentModeSelectionStep = consentModeSelectionStep; + } + + public WizardStepPanel getElectronicConsentStep() { + return electronicConsentStep; + } + + public void setElectronicConsentStep(WizardStepPanel electronicConsentStep) { + this.electronicConsentStep = electronicConsentStep; + } + + public WizardStepPanel getConsentConfirmationStep() { + return consentConfirmationStep; + } + + public void setConsentConfirmationStep(WizardStepPanel consentConfirmationStep) { + this.consentConfirmationStep = consentConfirmationStep; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ElectronicConsentStep.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ElectronicConsentStep.java index 65363dff3..8d1b77b82 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ElectronicConsentStep.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/core/wicket/wizard/ElectronicConsentStep.java @@ -1,48 +1,57 @@ -package org.obiba.onyx.marble.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.marble.core.wicket.consent.ElectronicConsentPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class ElectronicConsentStep extends WizardStepPanel { - - private static final long serialVersionUID = 1L; - - private ElectronicConsentPanel electronicConsentPanel; - - @SpringBean - private ActiveConsentService activeConsentService; - - public ElectronicConsentStep(String id) { - super(id); - setOutputMarkupId(true); - add(new Label("title", new StringResourceModel("ElectronicConsentTitle", this, null))); - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - // No previous step - form.getPreviousLink().setEnabled(true); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } - - @Override - public void onStepInNext(WizardForm form, AjaxRequestTarget target) { - setContent(target, electronicConsentPanel = new ElectronicConsentPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - electronicConsentPanel.save(); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.marble.core.wicket.consent.ElectronicConsentPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class ElectronicConsentStep extends WizardStepPanel { + + private static final long serialVersionUID = 1L; + + private ElectronicConsentPanel electronicConsentPanel; + + @SpringBean + private ActiveConsentService activeConsentService; + + public ElectronicConsentStep(String id) { + super(id); + setOutputMarkupId(true); + add(new Label("title", new StringResourceModel("ElectronicConsentTitle", this, null))); + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + // No previous step + form.getPreviousLink().setEnabled(true); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } + + @Override + public void onStepInNext(WizardForm form, AjaxRequestTarget target) { + setContent(target, electronicConsentPanel = new ElectronicConsentPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + electronicConsentPanel.save(); + } +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/Consent.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/Consent.java index 8388791a8..5533b4d69 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/Consent.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/Consent.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.marble.domain.consent; - -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.core.domain.participant.Interview; - -@Entity -public class Consent extends AbstractEntity { - - private static final long serialVersionUID = 1L; - - @OneToOne - @JoinColumn(name = "interview_id") - private Interview interview; - - private ConsentMode mode; - - private String language; - - private Boolean accepted; - - public ConsentMode getMode() { - return mode; - } - - public void setMode(ConsentMode mode) { - this.mode = mode; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public Boolean isAccepted() { - return accepted; - } - - public void setAccepted(Boolean accepted) { - this.accepted = accepted; - } - - public Interview getInterview() { - return interview; - } - - public void setInterview(Interview interview) { - this.interview = interview; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.domain.consent; + +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.core.domain.participant.Interview; + +@Entity +public class Consent extends AbstractEntity { + + private static final long serialVersionUID = 1L; + + @OneToOne + @JoinColumn(name = "interview_id") + private Interview interview; + + private ConsentMode mode; + + private String language; + + private Boolean accepted; + + public ConsentMode getMode() { + return mode; + } + + public void setMode(ConsentMode mode) { + this.mode = mode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Boolean isAccepted() { + return accepted; + } + + public void setAccepted(Boolean accepted) { + this.accepted = accepted; + } + + public Interview getInterview() { + return interview; + } + + public void setInterview(Interview interview) { + this.interview = interview; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/ConsentMode.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/ConsentMode.java index bff4f1c38..6cf412639 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/ConsentMode.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/domain/consent/ConsentMode.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.marble.domain.consent; - -public enum ConsentMode { - ELECTRONIC, MANUAL -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.domain.consent; + +public enum ConsentMode { + ELECTRONIC, MANUAL +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/MarbleModule.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/MarbleModule.java index 325e77e45..9e5dc30d2 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/MarbleModule.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/MarbleModule.java @@ -1,63 +1,72 @@ -package org.obiba.onyx.marble.engine; - -import java.util.List; - -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class MarbleModule implements Module, ApplicationContextAware { - - private ApplicationContext applicationContext; - - private List stages; - - public IStageExecution createStageExecution(Interview interview, Stage stage) { - StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); - exec.setStage(stage); - exec.setInterview(interview); - - AbstractStageState ready = (AbstractStageState) applicationContext.getBean("marbleReadyState"); - AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("marbleInProgressState"); - AbstractStageState completed = (AbstractStageState) applicationContext.getBean("marbleCompletedState"); - - exec.addEdge(ready, TransitionEvent.START, inProgress); - exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); - exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); - exec.addEdge(completed, TransitionEvent.CANCEL, ready); - - exec.setInitialState(ready); - - return exec; - } - - public String getName() { - return "marble"; - } - - public void initialize() { - } - - public void shutdown() { - } - - public List getStages() { - return stages; - } - - public void setStages(List stages) { - this.stages = stages; - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.engine; + +import java.util.List; + +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +public class MarbleModule implements Module, ApplicationContextAware { + + private ApplicationContext applicationContext; + + private List stages; + + public IStageExecution createStageExecution(Interview interview, Stage stage) { + StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); + exec.setStage(stage); + exec.setInterview(interview); + + AbstractStageState ready = (AbstractStageState) applicationContext.getBean("marbleReadyState"); + AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("marbleInProgressState"); + AbstractStageState completed = (AbstractStageState) applicationContext.getBean("marbleCompletedState"); + + exec.addEdge(ready, TransitionEvent.START, inProgress); + exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); + exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); + exec.addEdge(completed, TransitionEvent.CANCEL, ready); + + exec.setInitialState(ready); + + return exec; + } + + public String getName() { + return "marble"; + } + + public void initialize() { + } + + public void shutdown() { + } + + public List getStages() { + return stages; + } + + public void setStages(List stages) { + this.stages = stages; + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/AbstractMarbleStageState.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/AbstractMarbleStageState.java index a24a93835..845eb7a5e 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/AbstractMarbleStageState.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/AbstractMarbleStageState.java @@ -1,32 +1,41 @@ -package org.obiba.onyx.marble.engine.state; - -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.marble.core.service.ActiveConsentService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractMarbleStageState extends AbstractStageState { - - private static final Logger log = LoggerFactory.getLogger(AbstractMarbleStageState.class); - - private ActiveConsentService activeConsentService; - - public void setActiveConsentService(ActiveConsentService activeConsentService) { - this.activeConsentService = activeConsentService; - } - - protected ActiveConsentService getActiveConsentService() { - return activeConsentService; - } - - @Override - public Data getData(String key) { - if(key.equals("Consent")) { - return DataBuilder.buildBoolean(activeConsentService.getConsent().isAccepted()); - } - return null; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.marble.engine.state; + +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.marble.core.service.ActiveConsentService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractMarbleStageState extends AbstractStageState { + + private static final Logger log = LoggerFactory.getLogger(AbstractMarbleStageState.class); + + private ActiveConsentService activeConsentService; + + public void setActiveConsentService(ActiveConsentService activeConsentService) { + this.activeConsentService = activeConsentService; + } + + protected ActiveConsentService getActiveConsentService() { + return activeConsentService; + } + + @Override + public Data getData(String key) { + if(key.equals("Consent")) { + return DataBuilder.buildBoolean(activeConsentService.getConsent().isAccepted()); + } + return null; + } + +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleCompletedState.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleCompletedState.java index 00b6e78e4..ec57d5b6d 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleCompletedState.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleCompletedState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -34,4 +43,4 @@ public String getName() { return "Marble.Completed"; } -} \ No newline at end of file +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleInProgressState.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleInProgressState.java index 933e3e92a..a093bba84 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleInProgressState.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleInProgressState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -46,4 +55,4 @@ public String getName() { return "Marble.InProgress"; } -} \ No newline at end of file +} diff --git a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleReadyState.java b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleReadyState.java index 724750651..1d70e972b 100644 --- a/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleReadyState.java +++ b/onyx-modules/marble/marble-core/src/main/java/org/obiba/onyx/marble/engine/state/MarbleReadyState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ /** * */ @@ -44,4 +53,4 @@ public String getName() { return "Marble.Ready"; } -} \ No newline at end of file +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/ActiveConclusionService.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/ActiveConclusionService.java index daaf208ce..5afe50f8f 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/ActiveConclusionService.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/ActiveConclusionService.java @@ -1,11 +1,20 @@ -package org.obiba.onyx.mica.core.service; - -public interface ActiveConclusionService { - - public Boolean getConclusion(); - - public void setConclusion(Boolean conclusion); - - public void validate(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.core.service; + +public interface ActiveConclusionService { + + public Boolean getConclusion(); + + public void setConclusion(Boolean conclusion); + + public void validate(); + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/impl/DefaultActiveConclusionServiceImpl.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/impl/DefaultActiveConclusionServiceImpl.java index c59bb783a..8e2e3acbc 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/impl/DefaultActiveConclusionServiceImpl.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/service/impl/DefaultActiveConclusionServiceImpl.java @@ -1,27 +1,36 @@ -package org.obiba.onyx.mica.core.service.impl; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.mica.core.service.ActiveConclusionService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultActiveConclusionServiceImpl extends PersistenceManagerAwareService implements ActiveConclusionService { - - private static final Logger log = LoggerFactory.getLogger(DefaultActiveConclusionServiceImpl.class); - - private Boolean conclusion = true; - - public Boolean getConclusion() { - return conclusion; - } - - public void setConclusion(Boolean conclusion) { - this.conclusion = conclusion; - } - - public void validate() { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.core.service.impl; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.mica.core.service.ActiveConclusionService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DefaultActiveConclusionServiceImpl extends PersistenceManagerAwareService implements ActiveConclusionService { + + private static final Logger log = LoggerFactory.getLogger(DefaultActiveConclusionServiceImpl.class); + + private Boolean conclusion = true; + + public Boolean getConclusion() { + return conclusion; + } + + public void setConclusion(Boolean conclusion) { + this.conclusion = conclusion; + } + + public void validate() { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/wicket/MicaPanel.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/wicket/MicaPanel.java index f05a12c65..4c635383d 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/wicket/MicaPanel.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/core/wicket/MicaPanel.java @@ -1,100 +1,109 @@ -package org.obiba.onyx.mica.core.wicket; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxButton; -import org.apache.wicket.markup.html.form.CheckBox; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.mica.core.service.ActiveConclusionService; -import org.obiba.onyx.wicket.IEngineComponentAware; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MicaPanel extends Panel implements IEngineComponentAware { - - private static final long serialVersionUID = -6692482689347742363L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(MicaPanel.class); - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveConclusionService activeConclusionService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private ActionWindow actionWindow; - - private FeedbackPanel feedbackPanel; - - @SuppressWarnings("serial") - public MicaPanel(String id, Stage stage) { - super(id); - - final String stageName = stage.getName(); - - Form form = new Form("form"); - add(form); - - form.add(new CheckBox("cb", new PropertyModel(activeConclusionService, "conclusion"))); - - form.add(new AjaxButton("submit", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - log.info("conclusion=" + activeConclusionService.getConclusion()); - IStageExecution exec = activeInterviewService.getStageExecution(stageName); - ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); - if(actionDef != null) { - actionWindow.show(target, new StageModel(moduleRegistry, stageName), actionDef); - } - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedbackPanel); - } - - }); - - form.add(new AjaxLink("cancel") { - - public void onClick(AjaxRequestTarget target) { - IStageExecution exec = activeInterviewService.getStageExecution(stageName); - ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); - if(actionDef != null) { - actionWindow.show(target, new StageModel(moduleRegistry, stageName), actionDef); - } - } - - }); - } - - public void setActionWindwon(ActionWindow window) { - this.actionWindow = window; - } - - public void setFeedbackPanel(FeedbackPanel feedbackPanel) { - this.feedbackPanel = feedbackPanel; - } - - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.core.wicket; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.markup.html.form.CheckBox; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.mica.core.service.ActiveConclusionService; +import org.obiba.onyx.wicket.IEngineComponentAware; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MicaPanel extends Panel implements IEngineComponentAware { + + private static final long serialVersionUID = -6692482689347742363L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(MicaPanel.class); + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveConclusionService activeConclusionService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private ActionWindow actionWindow; + + private FeedbackPanel feedbackPanel; + + @SuppressWarnings("serial") + public MicaPanel(String id, Stage stage) { + super(id); + + final String stageName = stage.getName(); + + Form form = new Form("form"); + add(form); + + form.add(new CheckBox("cb", new PropertyModel(activeConclusionService, "conclusion"))); + + form.add(new AjaxButton("submit", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + log.info("conclusion=" + activeConclusionService.getConclusion()); + IStageExecution exec = activeInterviewService.getStageExecution(stageName); + ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); + if(actionDef != null) { + actionWindow.show(target, new StageModel(moduleRegistry, stageName), actionDef); + } + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedbackPanel); + } + + }); + + form.add(new AjaxLink("cancel") { + + public void onClick(AjaxRequestTarget target) { + IStageExecution exec = activeInterviewService.getStageExecution(stageName); + ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); + if(actionDef != null) { + actionWindow.show(target, new StageModel(moduleRegistry, stageName), actionDef); + } + } + + }); + } + + public void setActionWindwon(ActionWindow window) { + this.actionWindow = window; + } + + public void setFeedbackPanel(FeedbackPanel feedbackPanel) { + this.feedbackPanel = feedbackPanel; + } + + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/MicaModule.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/MicaModule.java index 7f983ad9c..d73563f98 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/MicaModule.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/MicaModule.java @@ -1,88 +1,97 @@ -package org.obiba.onyx.mica.engine; - -import java.util.List; - -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class MicaModule implements Module, ApplicationContextAware { - - private static final Logger log = LoggerFactory.getLogger(MicaModule.class); - - private ApplicationContext applicationContext; - - private ActiveInterviewService activeInterviewService; - - private List stages; - - public String getName() { - return "mica"; - } - - public void initialize() { - log.info("initialize"); - } - - public void shutdown() { - log.info("shutdown"); - } - - public IStageExecution createStageExecution(Interview interview, Stage stage) { - StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); - exec.setStage(stage); - exec.setInterview(interview); - - AbstractStageState waiting = (AbstractStageState) applicationContext.getBean("micaWaitingState"); - AbstractStageState ready = (AbstractStageState) applicationContext.getBean("micaReadyState"); - AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("micaInProgressState"); - AbstractStageState completed = (AbstractStageState) applicationContext.getBean("micaCompletedState"); - - exec.addEdge(ready, TransitionEvent.START, inProgress); - exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); - exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); - exec.addEdge(completed, TransitionEvent.CANCEL, ready); - - // if (dependsOn != null && dependsOn.length>0) { - exec.addEdge(waiting, TransitionEvent.VALID, ready); - exec.addEdge(ready, TransitionEvent.INVALID, waiting); - exec.addEdge(completed, TransitionEvent.INVALID, waiting); - - if(stage.getStageDependencyCondition() == null) { - exec.setInitialState(ready); - } else { - if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == null) { - exec.setInitialState(waiting); - } else if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == true) { - exec.setInitialState(ready); - } - } - return exec; - } - - public List getStages() { - return stages; - } - - public void setStages(List stages) { - this.stages = stages; - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { - this.activeInterviewService = activeInterviewService; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.engine; + +import java.util.List; + +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +public class MicaModule implements Module, ApplicationContextAware { + + private static final Logger log = LoggerFactory.getLogger(MicaModule.class); + + private ApplicationContext applicationContext; + + private ActiveInterviewService activeInterviewService; + + private List stages; + + public String getName() { + return "mica"; + } + + public void initialize() { + log.info("initialize"); + } + + public void shutdown() { + log.info("shutdown"); + } + + public IStageExecution createStageExecution(Interview interview, Stage stage) { + StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); + exec.setStage(stage); + exec.setInterview(interview); + + AbstractStageState waiting = (AbstractStageState) applicationContext.getBean("micaWaitingState"); + AbstractStageState ready = (AbstractStageState) applicationContext.getBean("micaReadyState"); + AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("micaInProgressState"); + AbstractStageState completed = (AbstractStageState) applicationContext.getBean("micaCompletedState"); + + exec.addEdge(ready, TransitionEvent.START, inProgress); + exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); + exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); + exec.addEdge(completed, TransitionEvent.CANCEL, ready); + + // if (dependsOn != null && dependsOn.length>0) { + exec.addEdge(waiting, TransitionEvent.VALID, ready); + exec.addEdge(ready, TransitionEvent.INVALID, waiting); + exec.addEdge(completed, TransitionEvent.INVALID, waiting); + + if(stage.getStageDependencyCondition() == null) { + exec.setInitialState(ready); + } else { + if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == null) { + exec.setInitialState(waiting); + } else if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == true) { + exec.setInitialState(ready); + } + } + return exec; + } + + public List getStages() { + return stages; + } + + public void setStages(List stages) { + this.stages = stages; + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { + this.activeInterviewService = activeInterviewService; + } +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/AbstractMicaStageState.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/AbstractMicaStageState.java index 9c1abe0cc..9d9038504 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/AbstractMicaStageState.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/AbstractMicaStageState.java @@ -1,38 +1,47 @@ -package org.obiba.onyx.mica.engine.state; - -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.mica.core.service.ActiveConclusionService; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractMicaStageState extends AbstractStageState { - - private static final Logger log = LoggerFactory.getLogger(AbstractMicaStageState.class); - - private ActiveConclusionService activeConclusionService; - - public void setActiveConclusionService(ActiveConclusionService activeConclusionService) { - this.activeConclusionService = activeConclusionService; - } - - protected ActiveConclusionService getActiveConclusionService() { - return activeConclusionService; - } - - @Override - public Data getData(String key) { - if(key.equals("Consent")) { - log.info("getData(" + key +")=" + activeConclusionService.getConclusion()); - return DataBuilder.buildBoolean(activeConclusionService.getConclusion()); - } - return null; - } - - @Override - protected Boolean areDependenciesCompleted() { - return super.areDependenciesCompleted(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.engine.state; + +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.mica.core.service.ActiveConclusionService; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractMicaStageState extends AbstractStageState { + + private static final Logger log = LoggerFactory.getLogger(AbstractMicaStageState.class); + + private ActiveConclusionService activeConclusionService; + + public void setActiveConclusionService(ActiveConclusionService activeConclusionService) { + this.activeConclusionService = activeConclusionService; + } + + protected ActiveConclusionService getActiveConclusionService() { + return activeConclusionService; + } + + @Override + public Data getData(String key) { + if(key.equals("Consent")) { + log.info("getData(" + key +")=" + activeConclusionService.getConclusion()); + return DataBuilder.buildBoolean(activeConclusionService.getConclusion()); + } + return null; + } + + @Override + protected Boolean areDependenciesCompleted() { + return super.areDependenciesCompleted(); + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaCompletedState.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaCompletedState.java index af8642a0c..b28efb3e0 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaCompletedState.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaCompletedState.java @@ -1,37 +1,46 @@ -/** - * - */ -package org.obiba.onyx.mica.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class MicaCompletedState extends AbstractMicaStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(MicaCompletedState.class); - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.CANCEL_ACTION); - } - - @Override - public void stop(Action action) { - super.execute(action); - log.info("Mica Stage {} is cancelling", super.getStage().getName()); - castEvent(TransitionEvent.CANCEL); - } - - @Override - public boolean isCompleted() { - return true; - } - - public String getName() { - return "Mica.Completed"; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * + */ +package org.obiba.onyx.mica.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class MicaCompletedState extends AbstractMicaStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(MicaCompletedState.class); + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.CANCEL_ACTION); + } + + @Override + public void stop(Action action) { + super.execute(action); + log.info("Mica Stage {} is cancelling", super.getStage().getName()); + castEvent(TransitionEvent.CANCEL); + } + + @Override + public boolean isCompleted() { + return true; + } + + public String getName() { + return "Mica.Completed"; + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaInProgressState.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaInProgressState.java index 0485fd640..ff73013c1 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaInProgressState.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaInProgressState.java @@ -1,51 +1,60 @@ -/** - * - */ -package org.obiba.onyx.mica.engine.state; - -import org.apache.wicket.Component; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.mica.core.wicket.MicaPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class MicaInProgressState extends AbstractMicaStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(MicaInProgressState.class); - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.CANCEL_ACTION); - addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); - } - - public Component getWidget(String id) { - return new MicaPanel(id, getStage()); - } - - @Override - public void complete(Action action) { - log.info("Mica Stage {} is completing", super.getStage().getName()); - // Finish current conclusion - getActiveConclusionService().validate(); - castEvent(TransitionEvent.COMPLETE); - } - - @Override - public void stop(Action action) { - log.info("Mica Stage {} is canceling", super.getStage().getName()); - castEvent(TransitionEvent.CANCEL); - } - - @Override - public boolean isInteractive() { - return true; - } - - public String getName() { - return "Mica.InProgress"; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * + */ +package org.obiba.onyx.mica.engine.state; + +import org.apache.wicket.Component; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.mica.core.wicket.MicaPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class MicaInProgressState extends AbstractMicaStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(MicaInProgressState.class); + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.CANCEL_ACTION); + addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); + } + + public Component getWidget(String id) { + return new MicaPanel(id, getStage()); + } + + @Override + public void complete(Action action) { + log.info("Mica Stage {} is completing", super.getStage().getName()); + // Finish current conclusion + getActiveConclusionService().validate(); + castEvent(TransitionEvent.COMPLETE); + } + + @Override + public void stop(Action action) { + log.info("Mica Stage {} is canceling", super.getStage().getName()); + castEvent(TransitionEvent.CANCEL); + } + + @Override + public boolean isInteractive() { + return true; + } + + public String getName() { + return "Mica.InProgress"; + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaReadyState.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaReadyState.java index c164ca135..c7988036d 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaReadyState.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaReadyState.java @@ -1,46 +1,55 @@ -/** - * - */ -package org.obiba.onyx.mica.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.mica.core.service.ActiveConclusionService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -/** - * Mica Ready State, goes there each time a state is cancelled. - * - * @author Meryam Belhiah - * - */ -public class MicaReadyState extends AbstractMicaStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(MicaReadyState.class); - - private ActiveConclusionService activeConclusionService; - - public void setActiveConsentService(ActiveConclusionService activeConsentService) { - this.activeConclusionService = activeConsentService; - } - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.START_ACTION); - } - - @Override - public void execute(Action action) { - super.execute(action); - log.info("Mica Stage {} is starting", super.getStage().getName()); - activeConclusionService.setConclusion(false); - castEvent(TransitionEvent.START); - } - - public String getName() { - return "Mica.Ready"; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * + */ +package org.obiba.onyx.mica.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.mica.core.service.ActiveConclusionService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +/** + * Mica Ready State, goes there each time a state is cancelled. + * + * @author Meryam Belhiah + * + */ +public class MicaReadyState extends AbstractMicaStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(MicaReadyState.class); + + private ActiveConclusionService activeConclusionService; + + public void setActiveConsentService(ActiveConclusionService activeConsentService) { + this.activeConclusionService = activeConsentService; + } + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.START_ACTION); + } + + @Override + public void execute(Action action) { + super.execute(action); + log.info("Mica Stage {} is starting", super.getStage().getName()); + activeConclusionService.setConclusion(false); + castEvent(TransitionEvent.START); + } + + public String getName() { + return "Mica.Ready"; + } + +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaWaitingState.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaWaitingState.java index 8217a5ce1..6d107690e 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaWaitingState.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/MicaWaitingState.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.mica.engine.state; import org.obiba.onyx.engine.state.ITransitionListener; @@ -25,4 +34,4 @@ protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { return true; } -} \ No newline at end of file +} diff --git a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/ModuleStageDependencyCondition.java b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/ModuleStageDependencyCondition.java index 3d2f6d34f..b8bb057b0 100644 --- a/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/ModuleStageDependencyCondition.java +++ b/onyx-modules/mica/mica-core/src/main/java/org/obiba/onyx/mica/engine/state/ModuleStageDependencyCondition.java @@ -1,89 +1,98 @@ -package org.obiba.onyx.mica.engine.state; - -import java.util.List; - -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.onyx.engine.state.IStageExecution; - -/** - * Mica specific dependency condition depending on the presence of runValues for the stage - * @author acarey - */ -public class ModuleStageDependencyCondition extends StageDependencyCondition { - - private static final long serialVersionUID = 1L; - - private ModuleRegistry moduleRegistry; - - private String moduleName; - - public ModuleStageDependencyCondition() { - } - - /** - * Returns a Boolean depending on the fact that the step is completed and also on its result - * Null if not completed - * True if completed - */ - @SuppressWarnings("static-access") - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - - IStageExecution stageExecution; - - Module module = moduleRegistry.getModule(moduleName); - - System.out.println("*******mica******" + module + "*************"); - List moduleStage = module.getStages(); - - Boolean isDepSatisfied = true; - - for(Stage oneStage : moduleStage) { - stageExecution = activeInterviewService.getStageExecution(oneStage.getName()); - - System.out.println("******mica***dependency***before***" +isDepSatisfied+"*********************"); - - System.out.println("******mica*******" + oneStage.getName() + "*************"); - System.out.println("******mica*******" + stageExecution.isCompleted() + "*************"); - - - if(!stageExecution.isCompleted()) { - isDepSatisfied = null; - } - else { - if(isDepSatisfied.equals(true)) { - isDepSatisfied = true; - } - } - System.out.println("******mica***dependency***after***" +isDepSatisfied+"*********************"); - } - return isDepSatisfied; - } - - @Override - public boolean isDependentOn(String stageName) { - - - return this.moduleName.equals(moduleName); - } - - public ModuleRegistry getModuleRegistry() { - return moduleRegistry; - } - - public void setModuleRegistry(ModuleRegistry moduleRegistry) { - this.moduleRegistry = moduleRegistry; - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.mica.engine.state; + +import java.util.List; + +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.onyx.engine.state.IStageExecution; + +/** + * Mica specific dependency condition depending on the presence of runValues for the stage + * @author acarey + */ +public class ModuleStageDependencyCondition extends StageDependencyCondition { + + private static final long serialVersionUID = 1L; + + private ModuleRegistry moduleRegistry; + + private String moduleName; + + public ModuleStageDependencyCondition() { + } + + /** + * Returns a Boolean depending on the fact that the step is completed and also on its result + * Null if not completed + * True if completed + */ + @SuppressWarnings("static-access") + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + + IStageExecution stageExecution; + + Module module = moduleRegistry.getModule(moduleName); + + System.out.println("*******mica******" + module + "*************"); + List moduleStage = module.getStages(); + + Boolean isDepSatisfied = true; + + for(Stage oneStage : moduleStage) { + stageExecution = activeInterviewService.getStageExecution(oneStage.getName()); + + System.out.println("******mica***dependency***before***" +isDepSatisfied+"*********************"); + + System.out.println("******mica*******" + oneStage.getName() + "*************"); + System.out.println("******mica*******" + stageExecution.isCompleted() + "*************"); + + + if(!stageExecution.isCompleted()) { + isDepSatisfied = null; + } + else { + if(isDepSatisfied.equals(true)) { + isDepSatisfied = true; + } + } + System.out.println("******mica***dependency***after***" +isDepSatisfied+"*********************"); + } + return isDepSatisfied; + } + + @Override + public boolean isDependentOn(String stageName) { + + + return this.moduleName.equals(moduleName); + } + + public ModuleRegistry getModuleRegistry() { + return moduleRegistry; + } + + public void setModuleRegistry(ModuleRegistry moduleRegistry) { + this.moduleRegistry = moduleRegistry; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/CategoryAnswer.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/CategoryAnswer.java index 7be83823f..2596e1c52 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/CategoryAnswer.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/CategoryAnswer.java @@ -1,128 +1,137 @@ -package org.obiba.onyx.quartz.core.domain.answer; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -import org.obiba.core.domain.AbstractEntity; -import org.obiba.onyx.util.data.DataType; - -@Entity -public class CategoryAnswer extends AbstractEntity { - - private static final long serialVersionUID = 8308345423791582240L; - - private String categoryName; - - private Integer occurence; - - private Boolean active; - - private DataType dataType; - - private String textValue; - - private Long integerValue; - - private Double decimalValue; - - private Date dateValue; - - @ManyToOne - @JoinColumn(name = "question_answer_id") - private QuestionAnswer questionAnswer; - - @ManyToOne - @JoinColumn(name = "parent_category_answer_id") - private CategoryAnswer parentCategoryAnswer; - - public QuestionAnswer getQuestionAnswer() { - return questionAnswer; - } - - public void setQuestionAnswer(QuestionAnswer questionAnswer) { - this.questionAnswer = questionAnswer; - } - - public String getCategoryName() { - return categoryName; - } - - public void setCategoryName(String categoryName) { - this.categoryName = categoryName; - } - - public Integer getOccurence() { - return occurence; - } - - public void setOccurence(Integer occurence) { - this.occurence = occurence; - } - - public Boolean getActive() { - return active; - } - - public void setActive(Boolean active) { - this.active = active; - } - - public DataType getDataType() { - return dataType; - } - - public void setDataType(DataType dataType) { - this.dataType = dataType; - } - - public String getTextValue() { - return textValue; - } - - public void setTextValue(String textValue) { - this.textValue = textValue; - } - - public Long getIntegerValue() { - return integerValue; - } - - public void setIntegerValue(Long integerValue) { - this.integerValue = integerValue; - } - - public Double getDecimalValue() { - return decimalValue; - } - - public void setDecimalValue(Double decimalValue) { - this.decimalValue = decimalValue; - } - - public Date getDateValue() { - return dateValue; - } - - public void setDateValue(Date dateValue) { - this.dateValue = dateValue; - } - - public CategoryAnswer getParentCategoryAnswer() { - return parentCategoryAnswer; - } - - public void setParentCategoryAnswer(CategoryAnswer parentCategoryAnswer) { - this.parentCategoryAnswer = parentCategoryAnswer; - } - - public QuestionAnswer getParentQuestionAnswer() { - if (getParentCategoryAnswer() == null) - return null; - - return getParentCategoryAnswer().getQuestionAnswer(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.domain.answer; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +import org.obiba.core.domain.AbstractEntity; +import org.obiba.onyx.util.data.DataType; + +@Entity +public class CategoryAnswer extends AbstractEntity { + + private static final long serialVersionUID = 8308345423791582240L; + + private String categoryName; + + private Integer occurence; + + private Boolean active; + + private DataType dataType; + + private String textValue; + + private Long integerValue; + + private Double decimalValue; + + private Date dateValue; + + @ManyToOne + @JoinColumn(name = "question_answer_id") + private QuestionAnswer questionAnswer; + + @ManyToOne + @JoinColumn(name = "parent_category_answer_id") + private CategoryAnswer parentCategoryAnswer; + + public QuestionAnswer getQuestionAnswer() { + return questionAnswer; + } + + public void setQuestionAnswer(QuestionAnswer questionAnswer) { + this.questionAnswer = questionAnswer; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + public Integer getOccurence() { + return occurence; + } + + public void setOccurence(Integer occurence) { + this.occurence = occurence; + } + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public DataType getDataType() { + return dataType; + } + + public void setDataType(DataType dataType) { + this.dataType = dataType; + } + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public Long getIntegerValue() { + return integerValue; + } + + public void setIntegerValue(Long integerValue) { + this.integerValue = integerValue; + } + + public Double getDecimalValue() { + return decimalValue; + } + + public void setDecimalValue(Double decimalValue) { + this.decimalValue = decimalValue; + } + + public Date getDateValue() { + return dateValue; + } + + public void setDateValue(Date dateValue) { + this.dateValue = dateValue; + } + + public CategoryAnswer getParentCategoryAnswer() { + return parentCategoryAnswer; + } + + public void setParentCategoryAnswer(CategoryAnswer parentCategoryAnswer) { + this.parentCategoryAnswer = parentCategoryAnswer; + } + + public QuestionAnswer getParentQuestionAnswer() { + if (getParentCategoryAnswer() == null) + return null; + + return getParentCategoryAnswer().getQuestionAnswer(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionAnswer.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionAnswer.java index cd3af29f4..342720186 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionAnswer.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionAnswer.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.domain.answer; import java.util.ArrayList; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionnaireParticipant.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionnaireParticipant.java index aa653a528..5807888b7 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionnaireParticipant.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/domain/answer/QuestionnaireParticipant.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.domain.answer; import java.util.ArrayList; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IAnswerListener.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IAnswerListener.java index 80653918c..305c3a195 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IAnswerListener.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IAnswerListener.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire; import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/ILocalizable.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/ILocalizable.java index 7c4f1e265..b95668ef2 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/ILocalizable.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/ILocalizable.java @@ -1,16 +1,25 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire; - - -/** - * A localizable element is visitable for providing the localization key for each of its properties. - * @author Yannick Marcon - * - */ -public interface ILocalizable extends IVisitable { - - /** - * Unique identifier for the localizable element. - * @return - */ - public String getName(); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire; + + +/** + * A localizable element is visitable for providing the localization key for each of its properties. + * @author Yannick Marcon + * + */ +public interface ILocalizable extends IVisitable { + + /** + * Unique identifier for the localizable element. + * @return + */ + public String getName(); +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitable.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitable.java index 57bf5aa12..a06b2f006 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitable.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitable.java @@ -1,18 +1,27 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; - -/** - * Visitable {@link Questionnaire} element. - * @author Yannick Marcon - * - */ -public interface IVisitable { - - /** - * Accept the visit. - * @param visitor - */ - public void accept(IVisitor visitor); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; + +/** + * Visitable {@link Questionnaire} element. + * @author Yannick Marcon + * + */ +public interface IVisitable { + + /** + * Accept the visit. + * @param visitor + */ + public void accept(IVisitor visitor); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitor.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitor.java index 494c4fdeb..5250da74b 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitor.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/IVisitor.java @@ -1,32 +1,41 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Questionnaire element visitor. - * @author Yannick Marcon - * - */ -public interface IVisitor { - - public void visit(Questionnaire questionnaire); - - public void visit(Section section); - - public void visit(Page page); - - public void visit(Question question); - - public void visit(QuestionCategory questionCategory); - - public void visit(Category category); - - public void visit(OpenAnswerDefinition openAnswerDefinition); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Questionnaire element visitor. + * @author Yannick Marcon + * + */ +public interface IVisitor { + + public void visit(Questionnaire questionnaire); + + public void visit(Section section); + + public void visit(Page page); + + public void visit(Question question); + + public void visit(QuestionCategory questionCategory); + + public void visit(Category category); + + public void visit(OpenAnswerDefinition openAnswerDefinition); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/AnswerSource.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/AnswerSource.java index bddface07..6109d6279 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/AnswerSource.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/AnswerSource.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.answer; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/FixedSource.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/FixedSource.java index 94c83d8ef..717a5b906 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/FixedSource.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/FixedSource.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.answer; import org.obiba.onyx.util.data.Data; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/ParticipantPropertySource.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/ParticipantPropertySource.java index 1afc2d697..5210c1cea 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/ParticipantPropertySource.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/ParticipantPropertySource.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.answer; import org.obiba.onyx.util.data.Data; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampSource.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampSource.java index 65b456307..2070d66c6 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampSource.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampSource.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.answer; import java.util.Date; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampType.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampType.java index 01fa82450..c30083d00 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampType.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/answer/TimestampType.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.answer; public enum TimestampType { diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundle.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundle.java index ac1b01bb8..4c7600f59 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundle.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundle.java @@ -1,88 +1,97 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle; - -import java.util.Locale; -import java.util.Properties; -import java.util.Set; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.springframework.context.MessageSource; - -public interface QuestionnaireBundle { - /** - * Returns the name of the bundle. - * - * This is identical with the name of the questionnaire. - * - * @return bundle name - */ - public String getName(); - - /** - * Returns the bundle's questionnaire. - * - * Exactly one questionnaire exists per bundle. - * - * @return questionnaire - */ - public Questionnaire getQuestionnaire(); - - /** - * Specifies the language in which the questionnaire will be administered in the given locale. - * - * Note: If a language was previously specified for the locale, the new language overwrites the previous one. - * - * @param locale locale - * @param language language, as a set of key-value entries - */ - public void setLanguage(Locale locale, Properties language); - - /** - * Returns the language in which the questionnaire will be administered in the specified locale. - * - * Note: If no language was previously specified for the locale, the language returned will just the keys required - * (values will be empty). - * - * @param locale locale - * @return language, as a set of key-value entries - */ - public Properties getLanguage(Locale locale); - - /** - * Returns all of the languages in which the bundle's questionnaire may be administered, as a set of locales. - * - * The languages returned are determined by the presence of corresponding resource bundles in the questionnaire - * bundle. For example, if the following resource bundles exist - * - *
    - *
  • questionnaire_en.properties
  • - *
  • questionnaire_fr.properties
  • - *
- * - * a set containing two locales shall be returned -- Locale("en") and Locale("fr"). - * - * @return all languages in which the bundle's questionnaire may be administered - */ - public Set getAvailableLanguages(); - - /** - * Returns the Spring MessageSource associated with the bundle. - * - * The MessageSource can be used to localize questionnaire text to any of the languages returned by - * getAvailableLanguages(). - * - * @return bundle message source - */ - public MessageSource getMessageSource(); - - /** - * Given a localizable (a questionnaire, or a questionnaire element) and a property, - * returns the property's key. - * - * @param localizable a questionnaire, or any element of a questionnaire that implements - * the ILocalizable interface - * @param property property name - * @return property key - */ - public String getPropertyKey(ILocalizable localizable, String property); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle; + +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.springframework.context.MessageSource; + +public interface QuestionnaireBundle { + /** + * Returns the name of the bundle. + * + * This is identical with the name of the questionnaire. + * + * @return bundle name + */ + public String getName(); + + /** + * Returns the bundle's questionnaire. + * + * Exactly one questionnaire exists per bundle. + * + * @return questionnaire + */ + public Questionnaire getQuestionnaire(); + + /** + * Specifies the language in which the questionnaire will be administered in the given locale. + * + * Note: If a language was previously specified for the locale, the new language overwrites the previous one. + * + * @param locale locale + * @param language language, as a set of key-value entries + */ + public void setLanguage(Locale locale, Properties language); + + /** + * Returns the language in which the questionnaire will be administered in the specified locale. + * + * Note: If no language was previously specified for the locale, the language returned will just the keys required + * (values will be empty). + * + * @param locale locale + * @return language, as a set of key-value entries + */ + public Properties getLanguage(Locale locale); + + /** + * Returns all of the languages in which the bundle's questionnaire may be administered, as a set of locales. + * + * The languages returned are determined by the presence of corresponding resource bundles in the questionnaire + * bundle. For example, if the following resource bundles exist + * + *
    + *
  • questionnaire_en.properties
  • + *
  • questionnaire_fr.properties
  • + *
+ * + * a set containing two locales shall be returned -- Locale("en") and Locale("fr"). + * + * @return all languages in which the bundle's questionnaire may be administered + */ + public Set getAvailableLanguages(); + + /** + * Returns the Spring MessageSource associated with the bundle. + * + * The MessageSource can be used to localize questionnaire text to any of the languages returned by + * getAvailableLanguages(). + * + * @return bundle message source + */ + public MessageSource getMessageSource(); + + /** + * Given a localizable (a questionnaire, or a questionnaire element) and a property, + * returns the property's key. + * + * @param localizable a questionnaire, or any element of a questionnaire that implements + * the ILocalizable interface + * @param property property name + * @return property key + */ + public String getPropertyKey(ILocalizable localizable, String property); +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundleManager.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundleManager.java index 133d72a99..7f4d403d5 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundleManager.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/QuestionnaireBundleManager.java @@ -1,32 +1,41 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle; - -import java.io.IOException; -import java.util.Set; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; - -public interface QuestionnaireBundleManager { - /** - * Creates a bundle for the given questionnaire. - * - * @param questionnaire questionnaire - * @return questionnaire bundle created - * @throws IOException on any I/O-related error - */ - public QuestionnaireBundle createBundle(Questionnaire questionnaire) throws IOException; - - /** - * Returns the latest version of the specified questionnaire bundle. - * - * @param name questionnaire bundle name - * @return questionnaire bundle (or null if no bundle with the specified name was found) - */ - public QuestionnaireBundle getBundle(String name); - - /** - * Returns the latest versions of all questionnaire bundles. - * - * @return managed questionnaire bundles - */ - public Set bundles(); -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle; + +import java.io.IOException; +import java.util.Set; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; + +public interface QuestionnaireBundleManager { + /** + * Creates a bundle for the given questionnaire. + * + * @param questionnaire questionnaire + * @return questionnaire bundle created + * @throws IOException on any I/O-related error + */ + public QuestionnaireBundle createBundle(Questionnaire questionnaire) throws IOException; + + /** + * Returns the latest version of the specified questionnaire bundle. + * + * @param name questionnaire bundle name + * @return questionnaire bundle (or null if no bundle with the specified name was found) + */ + public QuestionnaireBundle getBundle(String name); + + /** + * Returns the latest versions of all questionnaire bundles. + * + * @return managed questionnaire bundles + */ + public Set bundles(); +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImpl.java index 21412fa8b..f7b41aa4f 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImpl.java @@ -1,232 +1,241 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.HashSet; -import java.util.Locale; -import java.util.Properties; -import java.util.Set; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireStreamer; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.support.ReloadableResourceBundleMessageSource; - -public class QuestionnaireBundleImpl implements QuestionnaireBundle { - - // - // Constants - // - - public static final String LANGUAGE_FILE_BASENAME = "questionnaire"; - - public static final String LANGUAGE_FILE_EXTENSION = ".properties"; - - private static final Logger log = LoggerFactory.getLogger(QuestionnaireBundleImpl.class); - - // - // Instance Variables - // - - private File bundleVersionDir; - - private Questionnaire questionnaire; - - private MessageSource messageSource; - - private IPropertyKeyProvider propertyKeyProvider; - - // - // Constructors - // - - public QuestionnaireBundleImpl(File bundleVersionDir, Questionnaire questionnaire, IPropertyKeyProvider propertyKeyProvider) { - if(bundleVersionDir == null) { - throw new IllegalArgumentException("Null bundle version directory"); - } - - if(questionnaire == null) { - throw new IllegalArgumentException("Null questionnaire"); - } - - if (propertyKeyProvider == null) { - throw new IllegalArgumentException("Null property key provider"); - } - - this.bundleVersionDir = bundleVersionDir; - this.questionnaire = questionnaire; - this.propertyKeyProvider = propertyKeyProvider; - - for (Locale locale : getAvailableLanguages()){ - this.questionnaire.addLocale(locale); - } - - // Initialize the message source. - messageSource = new ReloadableResourceBundleMessageSource() { - @Override - protected MessageFormat createMessageFormat(String msg, Locale locale) { - return new StringReferenceCompatibleMessageFormat((msg != null ? msg : ""), locale); - } - }; - ((ReloadableResourceBundleMessageSource) messageSource).setBasename(getMessageSourceBasename(bundleVersionDir)); - } - - // - // QuestionnaireBundle Methods - // - - public String getName() { - return questionnaire.getName(); - } - - public Questionnaire getQuestionnaire() { - return questionnaire; - } - - public void setLanguage(Locale locale, Properties language) { - FileOutputStream fos = null; - - try { - QuestionnaireStreamer.storeLanguage(getQuestionnaire(), locale, language, propertyKeyProvider, fos = new FileOutputStream(new File(bundleVersionDir, "questionnaire_" + locale + LANGUAGE_FILE_EXTENSION))); - } catch(IOException ex) { - log.error("Failed to store language file", ex); - } finally { - if(fos != null) { - try { - fos.close(); - } catch(IOException ex) { - log.error("Failed to close language file output stream", ex); - } - } - } - } - - public Properties getLanguage(Locale locale) { - Properties language = null; - - File languageFile = new File(bundleVersionDir, "questionnaire_" + locale + LANGUAGE_FILE_EXTENSION); - - if(languageFile.exists()) { - language = new Properties(); - - FileInputStream fis = null; - - try { - language.load(fis = new FileInputStream(languageFile)); - } catch(IOException ex) { - language = null; - log.error("Failed to load language file", ex); - } finally { - if(fis != null) { - try { - fis.close(); - } catch(IOException ex) { - log.error("Failed to close language file input stream", ex); - } - } - } - } - - if(language == null) { - QuestionnaireBuilder builder = QuestionnaireBuilder.getInstance(getQuestionnaire()); - language = builder.getProperties(propertyKeyProvider); - } - - return language; - } - - public Set getAvailableLanguages() { - final Set languages = new HashSet(); - - // Iterate over all language files. - bundleVersionDir.listFiles(new FileFilter() { - public boolean accept(File file) { - String fileName = file.getName(); - - if(file.isFile() && fileName.startsWith(LANGUAGE_FILE_BASENAME + '_') && fileName.endsWith(LANGUAGE_FILE_EXTENSION)) { - languages.add(new Locale(extractLocaleString(fileName))); - return true; - } - - return false; - } - }); - - return languages; - } - - public MessageSource getMessageSource() { - return messageSource; - } - - public String getPropertyKey(ILocalizable localizable, String property) { - return propertyKeyProvider.getPropertyKey(localizable, property); - } - - // - // Methods - // - - @Override - public int hashCode() { - return getName().hashCode(); - } - - @Override - public boolean equals(Object o) { - if(o instanceof QuestionnaireBundle) { - return ((QuestionnaireBundle) o).getName().equals(getName()); - } - - return false; - } - - /** - * Given a bundle version directory, returns the base name used to configure the Spring message source. - * - * @param bundleVersionDir bundle version directory - * @return message source base name - */ - private String getMessageSourceBasename(File bundleVersionDir) { - StringBuffer baseName = new StringBuffer(); - - // Append the bundle root directory. - baseName.append(bundleVersionDir.getParentFile().getParentFile().getName()); - - // Append the bundle directory. - baseName.append('/'); - baseName.append(bundleVersionDir.getParentFile().getName()); - - // Append the bundle version directory. - baseName.append('/'); - baseName.append(bundleVersionDir.getName()); - - // Append the resource bundle base name. - baseName.append('/'); - baseName.append(LANGUAGE_FILE_BASENAME); - - return baseName.toString(); - } - - private String extractLocaleString(String fileName) { - String localeString = null; - - int startIndex = fileName.indexOf('_'); - int endIndex = fileName.lastIndexOf(LANGUAGE_FILE_EXTENSION); - - localeString = fileName.substring(startIndex + 1, endIndex); - - return localeString; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.HashSet; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireStreamer; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.MessageSource; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; + +public class QuestionnaireBundleImpl implements QuestionnaireBundle { + + // + // Constants + // + + public static final String LANGUAGE_FILE_BASENAME = "questionnaire"; + + public static final String LANGUAGE_FILE_EXTENSION = ".properties"; + + private static final Logger log = LoggerFactory.getLogger(QuestionnaireBundleImpl.class); + + // + // Instance Variables + // + + private File bundleVersionDir; + + private Questionnaire questionnaire; + + private MessageSource messageSource; + + private IPropertyKeyProvider propertyKeyProvider; + + // + // Constructors + // + + public QuestionnaireBundleImpl(File bundleVersionDir, Questionnaire questionnaire, IPropertyKeyProvider propertyKeyProvider) { + if(bundleVersionDir == null) { + throw new IllegalArgumentException("Null bundle version directory"); + } + + if(questionnaire == null) { + throw new IllegalArgumentException("Null questionnaire"); + } + + if (propertyKeyProvider == null) { + throw new IllegalArgumentException("Null property key provider"); + } + + this.bundleVersionDir = bundleVersionDir; + this.questionnaire = questionnaire; + this.propertyKeyProvider = propertyKeyProvider; + + for (Locale locale : getAvailableLanguages()){ + this.questionnaire.addLocale(locale); + } + + // Initialize the message source. + messageSource = new ReloadableResourceBundleMessageSource() { + @Override + protected MessageFormat createMessageFormat(String msg, Locale locale) { + return new StringReferenceCompatibleMessageFormat((msg != null ? msg : ""), locale); + } + }; + ((ReloadableResourceBundleMessageSource) messageSource).setBasename(getMessageSourceBasename(bundleVersionDir)); + } + + // + // QuestionnaireBundle Methods + // + + public String getName() { + return questionnaire.getName(); + } + + public Questionnaire getQuestionnaire() { + return questionnaire; + } + + public void setLanguage(Locale locale, Properties language) { + FileOutputStream fos = null; + + try { + QuestionnaireStreamer.storeLanguage(getQuestionnaire(), locale, language, propertyKeyProvider, fos = new FileOutputStream(new File(bundleVersionDir, "questionnaire_" + locale + LANGUAGE_FILE_EXTENSION))); + } catch(IOException ex) { + log.error("Failed to store language file", ex); + } finally { + if(fos != null) { + try { + fos.close(); + } catch(IOException ex) { + log.error("Failed to close language file output stream", ex); + } + } + } + } + + public Properties getLanguage(Locale locale) { + Properties language = null; + + File languageFile = new File(bundleVersionDir, "questionnaire_" + locale + LANGUAGE_FILE_EXTENSION); + + if(languageFile.exists()) { + language = new Properties(); + + FileInputStream fis = null; + + try { + language.load(fis = new FileInputStream(languageFile)); + } catch(IOException ex) { + language = null; + log.error("Failed to load language file", ex); + } finally { + if(fis != null) { + try { + fis.close(); + } catch(IOException ex) { + log.error("Failed to close language file input stream", ex); + } + } + } + } + + if(language == null) { + QuestionnaireBuilder builder = QuestionnaireBuilder.getInstance(getQuestionnaire()); + language = builder.getProperties(propertyKeyProvider); + } + + return language; + } + + public Set getAvailableLanguages() { + final Set languages = new HashSet(); + + // Iterate over all language files. + bundleVersionDir.listFiles(new FileFilter() { + public boolean accept(File file) { + String fileName = file.getName(); + + if(file.isFile() && fileName.startsWith(LANGUAGE_FILE_BASENAME + '_') && fileName.endsWith(LANGUAGE_FILE_EXTENSION)) { + languages.add(new Locale(extractLocaleString(fileName))); + return true; + } + + return false; + } + }); + + return languages; + } + + public MessageSource getMessageSource() { + return messageSource; + } + + public String getPropertyKey(ILocalizable localizable, String property) { + return propertyKeyProvider.getPropertyKey(localizable, property); + } + + // + // Methods + // + + @Override + public int hashCode() { + return getName().hashCode(); + } + + @Override + public boolean equals(Object o) { + if(o instanceof QuestionnaireBundle) { + return ((QuestionnaireBundle) o).getName().equals(getName()); + } + + return false; + } + + /** + * Given a bundle version directory, returns the base name used to configure the Spring message source. + * + * @param bundleVersionDir bundle version directory + * @return message source base name + */ + private String getMessageSourceBasename(File bundleVersionDir) { + StringBuffer baseName = new StringBuffer(); + + // Append the bundle root directory. + baseName.append(bundleVersionDir.getParentFile().getParentFile().getName()); + + // Append the bundle directory. + baseName.append('/'); + baseName.append(bundleVersionDir.getParentFile().getName()); + + // Append the bundle version directory. + baseName.append('/'); + baseName.append(bundleVersionDir.getName()); + + // Append the resource bundle base name. + baseName.append('/'); + baseName.append(LANGUAGE_FILE_BASENAME); + + return baseName.toString(); + } + + private String extractLocaleString(String fileName) { + String localeString = null; + + int startIndex = fileName.indexOf('_'); + int endIndex = fileName.lastIndexOf(LANGUAGE_FILE_EXTENSION); + + localeString = fileName.substring(startIndex + 1, endIndex); + + return localeString; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImpl.java index d5b5cd83c..5d0c2362f 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImpl.java @@ -1,317 +1,326 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireStreamer; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.runtime.Version; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ResourceLoaderAware; -import org.springframework.core.io.ResourceLoader; - -/** - * A file system based implementation of QuestionnaireBundleManager. - * - * @author cag-dspathis - * - */ -public class QuestionnaireBundleManagerImpl implements QuestionnaireBundleManager, ResourceLoaderAware, InitializingBean { - // - // Constants - // - - public static final String QUESTIONNAIRE_BASE_NAME = "questionnaire"; - - private static final Logger log = LoggerFactory.getLogger(QuestionnaireBundleManagerImpl.class); - - // - // Instance Variables - // - - private File rootDir; - - private Set bundleCache; - - private ResourceLoader resourceLoader; - - private IPropertyKeyProvider propertyKeyProvider; - - // - // Constructors - // - - /** - * Creates a QuestionnaireBundleManagerImpl - * - * @param rootDir root directory - */ - public QuestionnaireBundleManagerImpl(File rootDir) { - // Initialize the root directory here for tests. When running within Spring, - // the root directory will be re-initialized, with the appropriate resource loader, - // after properties are set (see afterPropertiesSet() method). - this.rootDir = rootDir; - - bundleCache = new HashSet(); - } - - // - // ResourceLoaderAware Methods - // - - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } - - // - // InitializingBean Methods - // - - public void afterPropertiesSet() throws Exception { - String resourcePath = rootDir.isAbsolute() ? "file:" + rootDir.getPath() : rootDir.getPath(); - - rootDir = resourceLoader.getResource(resourcePath).getFile(); - - if(!rootDir.exists()) { - rootDir.mkdirs(); - } - - if(!isValidRootDirectory(rootDir)) { - throw new IllegalArgumentException("Invalid root directory: " + rootDir); - } - } - - public void setPropertyKeyProvider(IPropertyKeyProvider propertyKeyProvider) { - this.propertyKeyProvider = propertyKeyProvider; - } - - // - // QuestionnaireBundleManager Methods - // - - public QuestionnaireBundle createBundle(Questionnaire questionnaire) throws IOException { - File bundleVersionDir = new File(new File(rootDir, questionnaire.getName()), questionnaire.getVersion()); - - // Create the bundle object. - QuestionnaireBundle bundle = new QuestionnaireBundleImpl(bundleVersionDir, questionnaire, propertyKeyProvider); - - // Serialize it. - serializeBundle(bundle); - - return bundle; - } - - public QuestionnaireBundle getBundle(String name) { - QuestionnaireBundle bundle = null; - - // Look for the bundle in the cache. - for(QuestionnaireBundle aBundle : bundleCache) { - if(aBundle.getName().equals(name)) { - bundle = aBundle; - break; - } - } - - // If not found, load the latest version of the bundle from the file system. - if(bundle == null) { - try { - bundle = loadBundle(name); - } catch(IOException ex) { - log.error("Failed to load questionnaire bundle " + name); - } - } - - return bundle; - } - - public Set bundles() { - final Set bundles = new HashSet(); - - // Iterate over all bundle directories. - rootDir.listFiles(new FileFilter() { - public boolean accept(File file) { - if(file.isDirectory()) { - bundles.add(getBundle(file.getName())); - return true; - } - - return false; - } - }); - - return bundles; - } - - // - // Methods - // - - /** - * Indicates whether the specified root directory is valid. - * - * @param directory root directory - * @return true if the directory is not null, is indeed a directory (i.e., not a file), - * and is readable - */ - private boolean isValidRootDirectory(File directory) { - return (directory != null && directory.isDirectory() && directory.canRead()); - } - - /** - * Loads the latest version of the specified questionnaire bundle from the file system. - * - * @param name bundle name - * @return bundle (or null if not found - * @throws IOException on any I/O error - */ - private QuestionnaireBundle loadBundle(String name) throws IOException { - QuestionnaireBundle bundle = null; - - // Determine the latest version of the bundle. - File bundleDir = new File(rootDir, name); - String latestBundleVersion = getLatestBundleVersion(bundleDir); - - if(latestBundleVersion != null) { - try { - // Load the bundle. - bundle = deserializeBundle(new File(bundleDir, latestBundleVersion)); - - // Put it in the cache. - cacheBundle(bundle); - } catch(Exception ex) { - log.error("Failed to deserialize bundle " + bundleDir.getName() + " version " + latestBundleVersion, ex); - } - } else { - // Log as an error the fact that a bundle exists with no versions. - log.error("No version exists of questionnaire bundle " + bundleDir.getName() + "!"); - } - - return bundle; - } - - /** - * Serializes a bundle. - * - * This method creates the necessary directory structure for the bundle, then serializes the bundle's questionnaire in - * the appropriate directory, as follows: - * - * {rootDir}/{bundleDir}/{bundleVersionDir}/questionnaire.xml - * - * @param bundle questionnaire bundle - * @throws IOException on any I/O error - */ - private void serializeBundle(QuestionnaireBundle bundle) throws IOException { - // Create the bundle version directory, which will contain the questionnaire. - File bundleVersionDir = new File(new File(rootDir, bundle.getQuestionnaire().getName()), bundle.getQuestionnaire().getVersion()); - bundleVersionDir.mkdirs(); - - // Create the questionnaire file. - File questionnaireFile = new File(bundleVersionDir, QUESTIONNAIRE_BASE_NAME + ".xml"); - if(!questionnaireFile.exists()) { - questionnaireFile.createNewFile(); - } - - // Serialize the questionnaire to the file. - FileOutputStream fos = null; - - try { - fos = new FileOutputStream(questionnaireFile); - QuestionnaireStreamer.toXML(bundle.getQuestionnaire(), new FileOutputStream(questionnaireFile)); - } finally { - if(fos != null) { - try { - fos.close(); - } catch(IOException ex) { - log.error("Failed to close questionnaire file output stream", ex); - } - } - } - } - - /** - * Deserializes a bundle. - * - * This method first loads the bundle's questionnaire from the file system then instantiates and returns a - * QuestionnaireBundle containing that questionnaire. - * - * @param bundleVersionDir bundle version directory - * @return questionnaire bundle - * @throws IOException on any I/O error - */ - private QuestionnaireBundle deserializeBundle(File bundleVersionDir) throws IOException { - // Deserialize the questionnaire. - Questionnaire questionnaire = null; - FileInputStream fis = null; - - try { - fis = new FileInputStream(new File(bundleVersionDir, QUESTIONNAIRE_BASE_NAME + ".xml")); - questionnaire = QuestionnaireStreamer.fromBundle(fis); - } finally { - if(fis != null) { - try { - fis.close(); - } catch(IOException ex) { - log.error("Failed to close questionnaire file input stream", ex); - } - } - } - - // Create the bundle. - QuestionnaireBundle bundle = new QuestionnaireBundleImpl(bundleVersionDir, questionnaire, propertyKeyProvider); - - return bundle; - } - - private void cacheBundle(QuestionnaireBundle bundle) { - bundleCache.add(bundle); - log.debug("Added bundle " + bundle.getName() + " to the cache"); - } - - private String getLatestBundleVersion(File bundleDir) { - VersionFileFilter versionFileFilter = new VersionFileFilter(); - - bundleDir.listFiles(versionFileFilter); - String latestVersion = versionFileFilter.getLatestVersion(); - - return latestVersion; - } - - // - // Inner Classes - // - - class VersionFileFilter implements FileFilter { - private Version latestVersion; - - private String latestVersionFilename; - - public boolean accept(File file) { - if(file.isDirectory()) { - Version version = new Version(file.getName()); - - if(latestVersion == null || (version.compareTo(latestVersion) > 0)) { - latestVersion = version; - latestVersionFilename = file.getName(); - } - - return true; - } - - return false; - } - - public String getLatestVersion() { - return latestVersionFilename; - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireStreamer; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.runtime.Version; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.ResourceLoader; + +/** + * A file system based implementation of QuestionnaireBundleManager. + * + * @author cag-dspathis + * + */ +public class QuestionnaireBundleManagerImpl implements QuestionnaireBundleManager, ResourceLoaderAware, InitializingBean { + // + // Constants + // + + public static final String QUESTIONNAIRE_BASE_NAME = "questionnaire"; + + private static final Logger log = LoggerFactory.getLogger(QuestionnaireBundleManagerImpl.class); + + // + // Instance Variables + // + + private File rootDir; + + private Set bundleCache; + + private ResourceLoader resourceLoader; + + private IPropertyKeyProvider propertyKeyProvider; + + // + // Constructors + // + + /** + * Creates a QuestionnaireBundleManagerImpl + * + * @param rootDir root directory + */ + public QuestionnaireBundleManagerImpl(File rootDir) { + // Initialize the root directory here for tests. When running within Spring, + // the root directory will be re-initialized, with the appropriate resource loader, + // after properties are set (see afterPropertiesSet() method). + this.rootDir = rootDir; + + bundleCache = new HashSet(); + } + + // + // ResourceLoaderAware Methods + // + + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + // + // InitializingBean Methods + // + + public void afterPropertiesSet() throws Exception { + String resourcePath = rootDir.isAbsolute() ? "file:" + rootDir.getPath() : rootDir.getPath(); + + rootDir = resourceLoader.getResource(resourcePath).getFile(); + + if(!rootDir.exists()) { + rootDir.mkdirs(); + } + + if(!isValidRootDirectory(rootDir)) { + throw new IllegalArgumentException("Invalid root directory: " + rootDir); + } + } + + public void setPropertyKeyProvider(IPropertyKeyProvider propertyKeyProvider) { + this.propertyKeyProvider = propertyKeyProvider; + } + + // + // QuestionnaireBundleManager Methods + // + + public QuestionnaireBundle createBundle(Questionnaire questionnaire) throws IOException { + File bundleVersionDir = new File(new File(rootDir, questionnaire.getName()), questionnaire.getVersion()); + + // Create the bundle object. + QuestionnaireBundle bundle = new QuestionnaireBundleImpl(bundleVersionDir, questionnaire, propertyKeyProvider); + + // Serialize it. + serializeBundle(bundle); + + return bundle; + } + + public QuestionnaireBundle getBundle(String name) { + QuestionnaireBundle bundle = null; + + // Look for the bundle in the cache. + for(QuestionnaireBundle aBundle : bundleCache) { + if(aBundle.getName().equals(name)) { + bundle = aBundle; + break; + } + } + + // If not found, load the latest version of the bundle from the file system. + if(bundle == null) { + try { + bundle = loadBundle(name); + } catch(IOException ex) { + log.error("Failed to load questionnaire bundle " + name); + } + } + + return bundle; + } + + public Set bundles() { + final Set bundles = new HashSet(); + + // Iterate over all bundle directories. + rootDir.listFiles(new FileFilter() { + public boolean accept(File file) { + if(file.isDirectory()) { + bundles.add(getBundle(file.getName())); + return true; + } + + return false; + } + }); + + return bundles; + } + + // + // Methods + // + + /** + * Indicates whether the specified root directory is valid. + * + * @param directory root directory + * @return true if the directory is not null, is indeed a directory (i.e., not a file), + * and is readable + */ + private boolean isValidRootDirectory(File directory) { + return (directory != null && directory.isDirectory() && directory.canRead()); + } + + /** + * Loads the latest version of the specified questionnaire bundle from the file system. + * + * @param name bundle name + * @return bundle (or null if not found + * @throws IOException on any I/O error + */ + private QuestionnaireBundle loadBundle(String name) throws IOException { + QuestionnaireBundle bundle = null; + + // Determine the latest version of the bundle. + File bundleDir = new File(rootDir, name); + String latestBundleVersion = getLatestBundleVersion(bundleDir); + + if(latestBundleVersion != null) { + try { + // Load the bundle. + bundle = deserializeBundle(new File(bundleDir, latestBundleVersion)); + + // Put it in the cache. + cacheBundle(bundle); + } catch(Exception ex) { + log.error("Failed to deserialize bundle " + bundleDir.getName() + " version " + latestBundleVersion, ex); + } + } else { + // Log as an error the fact that a bundle exists with no versions. + log.error("No version exists of questionnaire bundle " + bundleDir.getName() + "!"); + } + + return bundle; + } + + /** + * Serializes a bundle. + * + * This method creates the necessary directory structure for the bundle, then serializes the bundle's questionnaire in + * the appropriate directory, as follows: + * + * {rootDir}/{bundleDir}/{bundleVersionDir}/questionnaire.xml + * + * @param bundle questionnaire bundle + * @throws IOException on any I/O error + */ + private void serializeBundle(QuestionnaireBundle bundle) throws IOException { + // Create the bundle version directory, which will contain the questionnaire. + File bundleVersionDir = new File(new File(rootDir, bundle.getQuestionnaire().getName()), bundle.getQuestionnaire().getVersion()); + bundleVersionDir.mkdirs(); + + // Create the questionnaire file. + File questionnaireFile = new File(bundleVersionDir, QUESTIONNAIRE_BASE_NAME + ".xml"); + if(!questionnaireFile.exists()) { + questionnaireFile.createNewFile(); + } + + // Serialize the questionnaire to the file. + FileOutputStream fos = null; + + try { + fos = new FileOutputStream(questionnaireFile); + QuestionnaireStreamer.toXML(bundle.getQuestionnaire(), new FileOutputStream(questionnaireFile)); + } finally { + if(fos != null) { + try { + fos.close(); + } catch(IOException ex) { + log.error("Failed to close questionnaire file output stream", ex); + } + } + } + } + + /** + * Deserializes a bundle. + * + * This method first loads the bundle's questionnaire from the file system then instantiates and returns a + * QuestionnaireBundle containing that questionnaire. + * + * @param bundleVersionDir bundle version directory + * @return questionnaire bundle + * @throws IOException on any I/O error + */ + private QuestionnaireBundle deserializeBundle(File bundleVersionDir) throws IOException { + // Deserialize the questionnaire. + Questionnaire questionnaire = null; + FileInputStream fis = null; + + try { + fis = new FileInputStream(new File(bundleVersionDir, QUESTIONNAIRE_BASE_NAME + ".xml")); + questionnaire = QuestionnaireStreamer.fromBundle(fis); + } finally { + if(fis != null) { + try { + fis.close(); + } catch(IOException ex) { + log.error("Failed to close questionnaire file input stream", ex); + } + } + } + + // Create the bundle. + QuestionnaireBundle bundle = new QuestionnaireBundleImpl(bundleVersionDir, questionnaire, propertyKeyProvider); + + return bundle; + } + + private void cacheBundle(QuestionnaireBundle bundle) { + bundleCache.add(bundle); + log.debug("Added bundle " + bundle.getName() + " to the cache"); + } + + private String getLatestBundleVersion(File bundleDir) { + VersionFileFilter versionFileFilter = new VersionFileFilter(); + + bundleDir.listFiles(versionFileFilter); + String latestVersion = versionFileFilter.getLatestVersion(); + + return latestVersion; + } + + // + // Inner Classes + // + + class VersionFileFilter implements FileFilter { + private Version latestVersion; + + private String latestVersionFilename; + + public boolean accept(File file) { + if(file.isDirectory()) { + Version version = new Version(file.getName()); + + if(latestVersion == null || (version.compareTo(latestVersion) > 0)) { + latestVersion = version; + latestVersionFilename = file.getName(); + } + + return true; + } + + return false; + } + + public String getLatestVersion() { + return latestVersionFilename; + } + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/AnswerCondition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/AnswerCondition.java index 28c8f70e1..95770c894 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/AnswerCondition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/AnswerCondition.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.condition; import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ComparisionOperator.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ComparisionOperator.java index 0e8f8e0cd..95688d068 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ComparisionOperator.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ComparisionOperator.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.condition; public enum ComparisionOperator { diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/Condition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/Condition.java index cbf6b2eb1..08f9a82f6 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/Condition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/Condition.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.condition; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ConditionOperator.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ConditionOperator.java index b3600f856..33765bfce 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ConditionOperator.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/ConditionOperator.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.condition; public enum ConditionOperator { diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/DataComparator.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/DataComparator.java index ac5e99b2f..f5321b9f4 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/DataComparator.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/DataComparator.java @@ -1,31 +1,40 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.condition; - -import java.io.Serializable; - -import org.obiba.onyx.util.data.Data; - -public class DataComparator implements Serializable { - - private static final long serialVersionUID = 6128481252934955909L; - - private ComparisionOperator comparisionOperator; - - private Data data; - - public Data getData() { - return data; - } - - public void setData(Data data) { - this.data = data; - } - - public ComparisionOperator getComparisionOperator() { - return comparisionOperator; - } - - public void setComparisionOperator(ComparisionOperator comparisionOperator) { - this.comparisionOperator = comparisionOperator; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.condition; + +import java.io.Serializable; + +import org.obiba.onyx.util.data.Data; + +public class DataComparator implements Serializable { + + private static final long serialVersionUID = 6128481252934955909L; + + private ComparisionOperator comparisionOperator; + + private Data data; + + public Data getData() { + return data; + } + + public void setData(Data data) { + this.data = data; + } + + public ComparisionOperator getComparisionOperator() { + return comparisionOperator; + } + + public void setComparisionOperator(ComparisionOperator comparisionOperator) { + this.comparisionOperator = comparisionOperator; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/MultipleCondition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/MultipleCondition.java index 92a5e01b6..7ba7bf8dc 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/MultipleCondition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/MultipleCondition.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.condition; public class MultipleCondition extends Condition { diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/NoAnswerCondition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/NoAnswerCondition.java index 1aa46d88f..ec85d81ee 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/NoAnswerCondition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/condition/NoAnswerCondition.java @@ -1,21 +1,30 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.condition; - -public class NoAnswerCondition extends Condition { - - private static final long serialVersionUID = -7934445960755750180L; - - private Condition condition; - - public Condition getCondition() { - return condition; - } - - public void setCondition(Condition condition) { - this.condition = condition; - } - - public boolean isToBeAnswered() { - return !condition.isToBeAnswered(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.condition; + +public class NoAnswerCondition extends Condition { + + private static final long serialVersionUID = -7934445960755750180L; + + private Condition condition; + + public Condition getCondition() { + return condition; + } + + public void setCondition(Condition condition) { + this.condition = condition; + } + + public boolean isToBeAnswered() { + return !condition.isToBeAnswered(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Category.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Category.java index 99b0b1ef8..c872c1714 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Category.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Category.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/OpenAnswerDefinition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/OpenAnswerDefinition.java index fc05b4c75..1821d40db 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/OpenAnswerDefinition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/OpenAnswerDefinition.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Page.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Page.java index 97c5ac3d6..456ea90a5 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Page.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Page.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Question.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Question.java index 1bab5ce4a..a37320edb 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Question.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Question.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/QuestionCategory.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/QuestionCategory.java index 0c7c11059..d0a101c61 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/QuestionCategory.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/QuestionCategory.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Questionnaire.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Questionnaire.java index ccd6e7acc..35339228c 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Questionnaire.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Questionnaire.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Section.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Section.java index 69a05e9c1..af947f709 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Section.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/question/Section.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.question; import java.io.Serializable; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/IWalkerVisitor.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/IWalkerVisitor.java index 4cc818710..ff6b46162 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/IWalkerVisitor.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/IWalkerVisitor.java @@ -1,19 +1,28 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util; - -import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; - -/** - * Handle the walk through each questionnaire element. - * @author Yannick Marcon - * @see QuestionnaireWalker - * - */ -public interface IWalkerVisitor extends IVisitor { - - /** - * Stop walking through the questionnaire hierarchy if false. - * @return - */ - public boolean visiteMore(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util; + +import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; + +/** + * Handle the walk through each questionnaire element. + * @author Yannick Marcon + * @see QuestionnaireWalker + * + */ +public interface IWalkerVisitor extends IVisitor { + + /** + * Stop walking through the questionnaire hierarchy if false. + * @return + */ + public boolean visiteMore(); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilder.java index 295721cd6..4fdb0aa27 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilder.java @@ -1,143 +1,152 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util; - -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.AbstractQuestionnaireElementBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.PageBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.PropertyKeyWriterVisitor; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.QuestionBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.SectionBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl.PropertiesPropertyKeyWriterImpl; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.runtime.Version; - -/** - * The {@link Questionnaire} main builder. - * @author Yannick Marcon - * - */ -public class QuestionnaireBuilder extends AbstractQuestionnaireElementBuilder { - - /** - * Constructor. - * @param name - * @param version - * @throws IllegalArgumentException if name does not respect naming pattern and if version does not respect - * versionning pattern. - * @see Version - */ - private QuestionnaireBuilder(String name, String version) { - super(null); - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - this.element = new Questionnaire(name, version); - this.questionnaire = this.element; - } - - private QuestionnaireBuilder(Questionnaire questionnaire) { - super(questionnaire); - this.element = questionnaire; - } - - /** - * Create a new {@link Questionnaire}. - * @param name - * @param version - * @return - * @throws IllegalArgumentException if name does not respect naming pattern and if version does not respect - * versionning pattern. - * @see Version - */ - public static QuestionnaireBuilder createQuestionnaire(String name, String version) { - return new QuestionnaireBuilder(name, version); - } - - /** - * Get an instance on the builder given a questionnaire. - * @param questionnaire - * @return - */ - public static QuestionnaireBuilder getInstance(Questionnaire questionnaire) { - return new QuestionnaireBuilder(questionnaire); - } - - /** - * Add a top level {@link Section} to current {@link Questionnaire}, and make it the current {@link Section} - * @param name - * @return - */ - public SectionBuilder withSection(String name) { - return SectionBuilder.createSection(this, name); - } - - /** - * Position the builder to the {@link Section} with the given name. - * @param name - * @return - * @throws IllegalStateException if no section can be found with this name - */ - public SectionBuilder inSection(String name) { - Section section = QuestionnaireFinder.getInstance(questionnaire).findSection(name); - if(section == null) { - throw invalidElementNameException(Section.class, name); - } - return SectionBuilder.inSection(getQuestionnaire(), section); - } - - /** - * Position the builder to the {@link Page} with the given name. - * @param name - * @return - * @throws IllegalStateException if no page can be found with this name - */ - public PageBuilder inPage(String name) { - Page page = QuestionnaireFinder.getInstance(questionnaire).findPage(name); - if(page == null) { - throw invalidElementNameException(Page.class, name); - } - return PageBuilder.inPage(getQuestionnaire(), page); - } - - /** - * Position the builder to the {@link Question} with the given name. - * @param name - * @return - * @throws IllegalStateException if no question can be found with this name - */ - public QuestionBuilder inQuestion(String name) { - Question question = QuestionnaireFinder.getInstance(questionnaire).findQuestion(name); - if(question == null) { - throw invalidElementNameException(Question.class, name); - } - return QuestionBuilder.inQuestion(getQuestionnaire(), question); - } - - /** - * Write the questionnaire properties. - * @param writer - */ - public void writeProperties(IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { - QuestionnaireWalker walker = new QuestionnaireWalker(new PropertyKeyWriterVisitor(propertyKeyProvider, writer)); - walker.walk(questionnaire); - writer.end(); - } - - /** - * Create the localization properties for the current {@link Questionnaire}. - * @return - */ - public Properties getProperties(IPropertyKeyProvider propertyKeyProvider) { - PropertiesPropertyKeyWriterImpl pWriter = new PropertiesPropertyKeyWriterImpl(); - - writeProperties(propertyKeyProvider, pWriter); - - return pWriter.getProperties(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util; + +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.AbstractQuestionnaireElementBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.PageBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.PropertyKeyWriterVisitor; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.QuestionBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.SectionBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl.PropertiesPropertyKeyWriterImpl; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.runtime.Version; + +/** + * The {@link Questionnaire} main builder. + * @author Yannick Marcon + * + */ +public class QuestionnaireBuilder extends AbstractQuestionnaireElementBuilder { + + /** + * Constructor. + * @param name + * @param version + * @throws IllegalArgumentException if name does not respect naming pattern and if version does not respect + * versionning pattern. + * @see Version + */ + private QuestionnaireBuilder(String name, String version) { + super(null); + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + this.element = new Questionnaire(name, version); + this.questionnaire = this.element; + } + + private QuestionnaireBuilder(Questionnaire questionnaire) { + super(questionnaire); + this.element = questionnaire; + } + + /** + * Create a new {@link Questionnaire}. + * @param name + * @param version + * @return + * @throws IllegalArgumentException if name does not respect naming pattern and if version does not respect + * versionning pattern. + * @see Version + */ + public static QuestionnaireBuilder createQuestionnaire(String name, String version) { + return new QuestionnaireBuilder(name, version); + } + + /** + * Get an instance on the builder given a questionnaire. + * @param questionnaire + * @return + */ + public static QuestionnaireBuilder getInstance(Questionnaire questionnaire) { + return new QuestionnaireBuilder(questionnaire); + } + + /** + * Add a top level {@link Section} to current {@link Questionnaire}, and make it the current {@link Section} + * @param name + * @return + */ + public SectionBuilder withSection(String name) { + return SectionBuilder.createSection(this, name); + } + + /** + * Position the builder to the {@link Section} with the given name. + * @param name + * @return + * @throws IllegalStateException if no section can be found with this name + */ + public SectionBuilder inSection(String name) { + Section section = QuestionnaireFinder.getInstance(questionnaire).findSection(name); + if(section == null) { + throw invalidElementNameException(Section.class, name); + } + return SectionBuilder.inSection(getQuestionnaire(), section); + } + + /** + * Position the builder to the {@link Page} with the given name. + * @param name + * @return + * @throws IllegalStateException if no page can be found with this name + */ + public PageBuilder inPage(String name) { + Page page = QuestionnaireFinder.getInstance(questionnaire).findPage(name); + if(page == null) { + throw invalidElementNameException(Page.class, name); + } + return PageBuilder.inPage(getQuestionnaire(), page); + } + + /** + * Position the builder to the {@link Question} with the given name. + * @param name + * @return + * @throws IllegalStateException if no question can be found with this name + */ + public QuestionBuilder inQuestion(String name) { + Question question = QuestionnaireFinder.getInstance(questionnaire).findQuestion(name); + if(question == null) { + throw invalidElementNameException(Question.class, name); + } + return QuestionBuilder.inQuestion(getQuestionnaire(), question); + } + + /** + * Write the questionnaire properties. + * @param writer + */ + public void writeProperties(IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { + QuestionnaireWalker walker = new QuestionnaireWalker(new PropertyKeyWriterVisitor(propertyKeyProvider, writer)); + walker.walk(questionnaire); + writer.end(); + } + + /** + * Create the localization properties for the current {@link Questionnaire}. + * @return + */ + public Properties getProperties(IPropertyKeyProvider propertyKeyProvider) { + PropertiesPropertyKeyWriterImpl pWriter = new PropertiesPropertyKeyWriterImpl(); + + writeProperties(propertyKeyProvider, pWriter); + + return pWriter.getProperties(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireFinder.java index 9a930537c..de2d02eea 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireFinder.java @@ -1,143 +1,152 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.CategoryFinder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.OpenAnswerDefinitionFinder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.PageFinder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.QuestionFinder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.SectionFinder; - -/** - * Find elements in a {@link Questionnaire}. - * @author Yannick Marcon - * - */ -public class QuestionnaireFinder { - - private Questionnaire questionnaire; - - public QuestionnaireFinder(Questionnaire questionnaire) { - this.questionnaire = questionnaire; - } - - public static QuestionnaireFinder getInstance(Questionnaire questionnaire) { - return new QuestionnaireFinder(questionnaire); - } - - /** - * Find {@link Section} in the questionnaire. - * @param name - * @return null if not found - */ - public Section findSection(String name) { - SectionFinder finder = new SectionFinder(name); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getFirstElement(); - } - - /** - * Find {@link Page} in the questionnaire. - * @param name - * @return null if not found - */ - public Page findPage(String name) { - PageFinder finder = new PageFinder(name); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getFirstElement(); - } - - /** - * Find {@link Question} with the given name in the questionnaire. - * @param name - * @return null if not found - */ - public Question findQuestion(String name) { - QuestionFinder finder = new QuestionFinder(name); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getFirstElement(); - } - - /** - * Find the first {@link OpenAnswerDefinition} with the given name. - * @param name - * @return - */ - public OpenAnswerDefinition findOpenAnswerDefinition(String name) { - OpenAnswerDefinitionFinder finder = new OpenAnswerDefinitionFinder(name); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getFirstElement(); - } - - /** - * Find the first {@link Category} with the given name. - * @param name - * @return null if not found - */ - public Category findCategory(String name) { - CategoryFinder finder = new CategoryFinder(name); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getFirstElement(); - } - - /** - * Find all the {@link Category} and associated {@link Question}. - * @param name - * @return - */ - public Map> findCategories(String name) { - CategoryFinder finder = new CategoryFinder(name, false); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getQuestionCategories(); - } - - /** - * Look for shared {@link Category}: categories refered by more than one question. - * @return - */ - public List findSharedCategories() { - CategoryFinder finder = new CategoryFinder(); - QuestionnaireWalker walker = new QuestionnaireWalker(finder); - walker.walk(questionnaire); - - return finder.getQuestionSharedCategories(); - } - - /** - * Find among the shared {@link Categories} the set of the ones that are unique by their name. - * @return - */ - public List findGlobalCategories() { - Map map = new HashMap(); - for(Category category : findSharedCategories()) { - if(!map.containsKey(category)) { - map.put(category.getName(), category); - } else { - map.remove(category.getName()); - } - } - - return new LinkedList(map.values()); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.CategoryFinder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.OpenAnswerDefinitionFinder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.PageFinder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.QuestionFinder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.finder.SectionFinder; + +/** + * Find elements in a {@link Questionnaire}. + * @author Yannick Marcon + * + */ +public class QuestionnaireFinder { + + private Questionnaire questionnaire; + + public QuestionnaireFinder(Questionnaire questionnaire) { + this.questionnaire = questionnaire; + } + + public static QuestionnaireFinder getInstance(Questionnaire questionnaire) { + return new QuestionnaireFinder(questionnaire); + } + + /** + * Find {@link Section} in the questionnaire. + * @param name + * @return null if not found + */ + public Section findSection(String name) { + SectionFinder finder = new SectionFinder(name); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getFirstElement(); + } + + /** + * Find {@link Page} in the questionnaire. + * @param name + * @return null if not found + */ + public Page findPage(String name) { + PageFinder finder = new PageFinder(name); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getFirstElement(); + } + + /** + * Find {@link Question} with the given name in the questionnaire. + * @param name + * @return null if not found + */ + public Question findQuestion(String name) { + QuestionFinder finder = new QuestionFinder(name); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getFirstElement(); + } + + /** + * Find the first {@link OpenAnswerDefinition} with the given name. + * @param name + * @return + */ + public OpenAnswerDefinition findOpenAnswerDefinition(String name) { + OpenAnswerDefinitionFinder finder = new OpenAnswerDefinitionFinder(name); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getFirstElement(); + } + + /** + * Find the first {@link Category} with the given name. + * @param name + * @return null if not found + */ + public Category findCategory(String name) { + CategoryFinder finder = new CategoryFinder(name); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getFirstElement(); + } + + /** + * Find all the {@link Category} and associated {@link Question}. + * @param name + * @return + */ + public Map> findCategories(String name) { + CategoryFinder finder = new CategoryFinder(name, false); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getQuestionCategories(); + } + + /** + * Look for shared {@link Category}: categories refered by more than one question. + * @return + */ + public List findSharedCategories() { + CategoryFinder finder = new CategoryFinder(); + QuestionnaireWalker walker = new QuestionnaireWalker(finder); + walker.walk(questionnaire); + + return finder.getQuestionSharedCategories(); + } + + /** + * Find among the shared {@link Categories} the set of the ones that are unique by their name. + * @return + */ + public List findGlobalCategories() { + Map map = new HashMap(); + for(Category category : findSharedCategories()) { + if(!map.containsKey(category)) { + map.put(category.getName(), category); + } else { + map.remove(category.getName()); + } + } + + return new LinkedList(map.values()); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamer.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamer.java index 8c0b71bcf..caa17925c 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamer.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamer.java @@ -1,122 +1,131 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Locale; -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl.OutputStreamPropertyKeyWriterImpl; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.onyx.util.data.Data; - -import com.thoughtworks.xstream.XStream; - -public class QuestionnaireStreamer { - - /** - * The de-serializer. - */ - private XStream xstream; - - private QuestionnaireStreamer() { - initializeXStream(); - } - - private void initializeXStream() { - xstream = new XStream(); - xstream.setMode(XStream.ID_REFERENCES); - xstream.alias("questionnaire", Questionnaire.class); - xstream.useAttributeFor(Questionnaire.class, "name"); - xstream.useAttributeFor(Questionnaire.class, "version"); - xstream.alias("section", Section.class); - xstream.useAttributeFor(Section.class, "name"); - xstream.alias("page", Page.class); - xstream.useAttributeFor(Page.class, "name"); - xstream.useAttributeFor(Page.class, "uIFactoryName"); - xstream.alias("question", Question.class); - xstream.useAttributeFor(Question.class, "name"); - xstream.useAttributeFor(Question.class, "number"); - xstream.useAttributeFor(Question.class, "required"); - xstream.useAttributeFor(Question.class, "multiple"); - xstream.useAttributeFor(Question.class, "minCount"); - xstream.useAttributeFor(Question.class, "maxCount"); - xstream.useAttributeFor(Question.class, "uIFactoryName"); - xstream.alias("category", Category.class); - xstream.useAttributeFor(Category.class, "name"); - xstream.alias("questionCategory", QuestionCategory.class); - xstream.useAttributeFor(QuestionCategory.class, "repeatable"); - xstream.useAttributeFor(QuestionCategory.class, "selected"); - xstream.useAttributeFor(QuestionCategory.class, "exportName"); - xstream.alias("open", OpenAnswerDefinition.class); - xstream.useAttributeFor(OpenAnswerDefinition.class, "name"); - xstream.useAttributeFor(OpenAnswerDefinition.class, "dataType"); - xstream.useAttributeFor(OpenAnswerDefinition.class, "unit"); - xstream.useAttributeFor(OpenAnswerDefinition.class, "format"); - xstream.alias("data", Data.class); - xstream.useAttributeFor(Data.class, "type"); - } - - /** - * Load a {@link Questionnaire} from its bundle directory. - * @param inputStream questionnaire input stream - * @return questionnaire - */ - public static Questionnaire fromBundle(InputStream inputStream) { - QuestionnaireStreamer streamer = new QuestionnaireStreamer(); - return (Questionnaire) streamer.xstream.fromXML(inputStream); - } - - /** - * Dump a {@link Questionnaire} to a string. - * @param questionnaire - * @return - */ - public static String toXML(Questionnaire questionnaire) { - QuestionnaireStreamer streamer = new QuestionnaireStreamer(); - return streamer.xstream.toXML(questionnaire); - } - - /** - * Dump a {@link Questionnaire} to a stream. - * @param questionnaire - * @param outputStream - */ - public static void toXML(Questionnaire questionnaire, OutputStream outputStream) { - QuestionnaireStreamer streamer = new QuestionnaireStreamer(); - streamer.xstream.toXML(questionnaire, outputStream); - } - - /** - * Stores the a language for a questionnaire, for the given locale, to the specified - * IQuestionnairePropertiesWriter. - * - * @param questionnaire - * @param locale - * @param language - * @param writer - */ - public static void storeLanguage(Questionnaire questionnaire, Locale locale, Properties language, IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { - QuestionnaireBuilder.getInstance(questionnaire).writeProperties(propertyKeyProvider, writer); - } - - /** - * Stores the a language for a questionnaire, for the given locale, to the specified OutputStream. - * - * @param questionnaire questionnaire - * @param locale locale - * @param language language - * @param outputStream output stream - */ - public static void storeLanguage(Questionnaire questionnaire, Locale locale, Properties language, IPropertyKeyProvider propertyKeyProvider, OutputStream outputStream) { - storeLanguage(questionnaire, locale, language, propertyKeyProvider, new OutputStreamPropertyKeyWriterImpl(language, outputStream)); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Locale; +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl.OutputStreamPropertyKeyWriterImpl; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.onyx.util.data.Data; + +import com.thoughtworks.xstream.XStream; + +public class QuestionnaireStreamer { + + /** + * The de-serializer. + */ + private XStream xstream; + + private QuestionnaireStreamer() { + initializeXStream(); + } + + private void initializeXStream() { + xstream = new XStream(); + xstream.setMode(XStream.ID_REFERENCES); + xstream.alias("questionnaire", Questionnaire.class); + xstream.useAttributeFor(Questionnaire.class, "name"); + xstream.useAttributeFor(Questionnaire.class, "version"); + xstream.alias("section", Section.class); + xstream.useAttributeFor(Section.class, "name"); + xstream.alias("page", Page.class); + xstream.useAttributeFor(Page.class, "name"); + xstream.useAttributeFor(Page.class, "uIFactoryName"); + xstream.alias("question", Question.class); + xstream.useAttributeFor(Question.class, "name"); + xstream.useAttributeFor(Question.class, "number"); + xstream.useAttributeFor(Question.class, "required"); + xstream.useAttributeFor(Question.class, "multiple"); + xstream.useAttributeFor(Question.class, "minCount"); + xstream.useAttributeFor(Question.class, "maxCount"); + xstream.useAttributeFor(Question.class, "uIFactoryName"); + xstream.alias("category", Category.class); + xstream.useAttributeFor(Category.class, "name"); + xstream.alias("questionCategory", QuestionCategory.class); + xstream.useAttributeFor(QuestionCategory.class, "repeatable"); + xstream.useAttributeFor(QuestionCategory.class, "selected"); + xstream.useAttributeFor(QuestionCategory.class, "exportName"); + xstream.alias("open", OpenAnswerDefinition.class); + xstream.useAttributeFor(OpenAnswerDefinition.class, "name"); + xstream.useAttributeFor(OpenAnswerDefinition.class, "dataType"); + xstream.useAttributeFor(OpenAnswerDefinition.class, "unit"); + xstream.useAttributeFor(OpenAnswerDefinition.class, "format"); + xstream.alias("data", Data.class); + xstream.useAttributeFor(Data.class, "type"); + } + + /** + * Load a {@link Questionnaire} from its bundle directory. + * @param inputStream questionnaire input stream + * @return questionnaire + */ + public static Questionnaire fromBundle(InputStream inputStream) { + QuestionnaireStreamer streamer = new QuestionnaireStreamer(); + return (Questionnaire) streamer.xstream.fromXML(inputStream); + } + + /** + * Dump a {@link Questionnaire} to a string. + * @param questionnaire + * @return + */ + public static String toXML(Questionnaire questionnaire) { + QuestionnaireStreamer streamer = new QuestionnaireStreamer(); + return streamer.xstream.toXML(questionnaire); + } + + /** + * Dump a {@link Questionnaire} to a stream. + * @param questionnaire + * @param outputStream + */ + public static void toXML(Questionnaire questionnaire, OutputStream outputStream) { + QuestionnaireStreamer streamer = new QuestionnaireStreamer(); + streamer.xstream.toXML(questionnaire, outputStream); + } + + /** + * Stores the a language for a questionnaire, for the given locale, to the specified + * IQuestionnairePropertiesWriter. + * + * @param questionnaire + * @param locale + * @param language + * @param writer + */ + public static void storeLanguage(Questionnaire questionnaire, Locale locale, Properties language, IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { + QuestionnaireBuilder.getInstance(questionnaire).writeProperties(propertyKeyProvider, writer); + } + + /** + * Stores the a language for a questionnaire, for the given locale, to the specified OutputStream. + * + * @param questionnaire questionnaire + * @param locale locale + * @param language language + * @param outputStream output stream + */ + public static void storeLanguage(Questionnaire questionnaire, Locale locale, Properties language, IPropertyKeyProvider propertyKeyProvider, OutputStream outputStream) { + storeLanguage(questionnaire, locale, language, propertyKeyProvider, new OutputStreamPropertyKeyWriterImpl(language, outputStream)); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireWalker.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireWalker.java index f5c9d1090..a021fca87 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireWalker.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireWalker.java @@ -1,133 +1,142 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util; - -import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Walks through the tree of {@link Questionnaire} elements, and call for a {@link IWalkerVisitor} at each node. - * @author Yannick Marcon - * - */ -public class QuestionnaireWalker implements IVisitor { - - /** - * A walk in which each parent node is traversed before its children is called a pre-order walk. - */ - boolean preOrder; - - /** - * Final visitor that performs real job at each node visit. - */ - private IWalkerVisitor visitor; - - /** - * Constructor, given a questionnaire visitor that will perform real operation at each node visit. - * @param visitor - */ - public QuestionnaireWalker(IWalkerVisitor visitor) { - this.visitor = visitor; - } - - /** - * Go through the questionnaire. - * @param questionnaire - * @param preOrder a walk in which each parent node is traversed before its children is called a pre-order walk. - */ - public void walk(Questionnaire questionnaire, boolean preOrder) { - this.preOrder = preOrder; - questionnaire.accept(this); - } - - /** - * Go through the questionnaire, in a pre-order walk. - * @param questionnaire - */ - public void walk(Questionnaire questionnaire) { - walk(questionnaire, true); - } - - /** - * Shall we continue walking through the questionnaire ? - */ - private boolean visiteMore() { - return visitor.visiteMore(); - } - - public final void visit(Questionnaire questionnaire) { - if(preOrder) questionnaire.accept(visitor); - for(Section section : questionnaire.getSections()) { - section.accept(this); - if(!visiteMore()) break; - } - if(!preOrder) questionnaire.accept(visitor); - } - - public final void visit(Section section) { - if(preOrder) section.accept(visitor); - if(visiteMore()) { - for(Page page : section.getPages()) { - page.accept(this); - if(!visiteMore()) break; - } - } - if(visiteMore()) { - for(Section sectionChild : section.getSections()) { - sectionChild.accept(this); - } - } - if(!preOrder) section.accept(visitor); - } - - public final void visit(Page page) { - if(preOrder) page.accept(visitor); - if(visiteMore()) { - for(Question question : page.getQuestions()) { - question.accept(this); - if(!visiteMore()) break; - } - } - if(!preOrder) page.accept(visitor); - } - - public final void visit(Question question) { - if(preOrder) question.accept(visitor); - if(visiteMore()) { - for(QuestionCategory questionCategory : question.getQuestionCategories()) { - questionCategory.accept(this); - if(!visiteMore()) break; - } - } - if(visiteMore()) { - for(Question questionChild : question.getQuestions()) { - questionChild.accept(this); - if(!visiteMore()) break; - } - } - if(!preOrder) question.accept(visitor); - } - - public final void visit(QuestionCategory questionCategory) { - if(preOrder) questionCategory.accept(visitor); - questionCategory.getCategory().accept(this); - if(!preOrder) questionCategory.accept(visitor); - } - - public final void visit(Category category) { - if(preOrder) category.accept(visitor); - if(visiteMore() && category.getOpenAnswerDefinition() != null) { - category.getOpenAnswerDefinition().accept(this); - } - if(!preOrder) category.accept(visitor); - } - - public final void visit(OpenAnswerDefinition openAnswerDefinition) { - openAnswerDefinition.accept(visitor); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util; + +import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Walks through the tree of {@link Questionnaire} elements, and call for a {@link IWalkerVisitor} at each node. + * @author Yannick Marcon + * + */ +public class QuestionnaireWalker implements IVisitor { + + /** + * A walk in which each parent node is traversed before its children is called a pre-order walk. + */ + boolean preOrder; + + /** + * Final visitor that performs real job at each node visit. + */ + private IWalkerVisitor visitor; + + /** + * Constructor, given a questionnaire visitor that will perform real operation at each node visit. + * @param visitor + */ + public QuestionnaireWalker(IWalkerVisitor visitor) { + this.visitor = visitor; + } + + /** + * Go through the questionnaire. + * @param questionnaire + * @param preOrder a walk in which each parent node is traversed before its children is called a pre-order walk. + */ + public void walk(Questionnaire questionnaire, boolean preOrder) { + this.preOrder = preOrder; + questionnaire.accept(this); + } + + /** + * Go through the questionnaire, in a pre-order walk. + * @param questionnaire + */ + public void walk(Questionnaire questionnaire) { + walk(questionnaire, true); + } + + /** + * Shall we continue walking through the questionnaire ? + */ + private boolean visiteMore() { + return visitor.visiteMore(); + } + + public final void visit(Questionnaire questionnaire) { + if(preOrder) questionnaire.accept(visitor); + for(Section section : questionnaire.getSections()) { + section.accept(this); + if(!visiteMore()) break; + } + if(!preOrder) questionnaire.accept(visitor); + } + + public final void visit(Section section) { + if(preOrder) section.accept(visitor); + if(visiteMore()) { + for(Page page : section.getPages()) { + page.accept(this); + if(!visiteMore()) break; + } + } + if(visiteMore()) { + for(Section sectionChild : section.getSections()) { + sectionChild.accept(this); + } + } + if(!preOrder) section.accept(visitor); + } + + public final void visit(Page page) { + if(preOrder) page.accept(visitor); + if(visiteMore()) { + for(Question question : page.getQuestions()) { + question.accept(this); + if(!visiteMore()) break; + } + } + if(!preOrder) page.accept(visitor); + } + + public final void visit(Question question) { + if(preOrder) question.accept(visitor); + if(visiteMore()) { + for(QuestionCategory questionCategory : question.getQuestionCategories()) { + questionCategory.accept(this); + if(!visiteMore()) break; + } + } + if(visiteMore()) { + for(Question questionChild : question.getQuestions()) { + questionChild.accept(this); + if(!visiteMore()) break; + } + } + if(!preOrder) question.accept(visitor); + } + + public final void visit(QuestionCategory questionCategory) { + if(preOrder) questionCategory.accept(visitor); + questionCategory.getCategory().accept(this); + if(!preOrder) questionCategory.accept(visitor); + } + + public final void visit(Category category) { + if(preOrder) category.accept(visitor); + if(visiteMore() && category.getOpenAnswerDefinition() != null) { + category.getOpenAnswerDefinition().accept(this); + } + if(!preOrder) category.accept(visitor); + } + + public final void visit(OpenAnswerDefinition openAnswerDefinition) { + openAnswerDefinition.accept(visitor); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/AbstractQuestionnaireElementBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/AbstractQuestionnaireElementBuilder.java index 2258a07b9..f8c9f2726 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/AbstractQuestionnaireElementBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/AbstractQuestionnaireElementBuilder.java @@ -1,99 +1,108 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; - -/** - * Base class for defining {@link Questionnaire} element builders. - * @author Yannick Marcon - * - * @param - */ -public abstract class AbstractQuestionnaireElementBuilder { - - /** - * Naming pattern for questionnaire elements to be respected. - */ - private static final Pattern NAME_PATTERN = Pattern.compile("[a-z,A-Z,0-9,_]+"); - - /** - * The current questionnaire element. - */ - protected T element; - - /** - * The questionnaire we are dealing with. - */ - protected Questionnaire questionnaire; - - /** - * Constructor with a given questionnaire. - * @param questionnaire - */ - public AbstractQuestionnaireElementBuilder(Questionnaire questionnaire) { - super(); - this.questionnaire = questionnaire; - } - - /** - * Check that the given name respects the naming pattern. - * @param name - * @return - */ - protected static boolean checkNamePattern(String name) { - Matcher m = NAME_PATTERN.matcher(name); - return m.matches(); - } - - /** - * Build an exception about the name pattern. - * @param name - * @return - */ - protected static IllegalArgumentException invalidNamePatternException(String name) { - return new IllegalArgumentException("Not a valid questionnaire element name: " + name + ". Expected pattern is " + NAME_PATTERN); - } - - /** - * Build an exception about the name unicity. - * @param elementClass - * @param name - * @return - */ - @SuppressWarnings("unchecked") - protected static IllegalArgumentException invalidNameUnicityException(Class elementClass, String name) { - return new IllegalArgumentException(elementClass.getSimpleName() + " name must be unique: " + name + "."); - } - - /** - * Build an exception if an element cannot be found in the questionnaire from its name. - * @param elementClass - * @param name - * @return - */ - @SuppressWarnings("unchecked") - protected static IllegalStateException invalidElementNameException(Class elementClass, String name) { - return new IllegalStateException("Unable to find in questionnaire the " + elementClass.getSimpleName() + " with name: " + name + ". Create it first."); - } - - /** - * Get the current questionnaire element. - * @return - */ - public T getElement() { - return element; - } - - /** - * Get the questionnaire currently build. - * @return - */ - public Questionnaire getQuestionnaire() { - return questionnaire; - } - - - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; + +/** + * Base class for defining {@link Questionnaire} element builders. + * @author Yannick Marcon + * + * @param + */ +public abstract class AbstractQuestionnaireElementBuilder { + + /** + * Naming pattern for questionnaire elements to be respected. + */ + private static final Pattern NAME_PATTERN = Pattern.compile("[a-z,A-Z,0-9,_]+"); + + /** + * The current questionnaire element. + */ + protected T element; + + /** + * The questionnaire we are dealing with. + */ + protected Questionnaire questionnaire; + + /** + * Constructor with a given questionnaire. + * @param questionnaire + */ + public AbstractQuestionnaireElementBuilder(Questionnaire questionnaire) { + super(); + this.questionnaire = questionnaire; + } + + /** + * Check that the given name respects the naming pattern. + * @param name + * @return + */ + protected static boolean checkNamePattern(String name) { + Matcher m = NAME_PATTERN.matcher(name); + return m.matches(); + } + + /** + * Build an exception about the name pattern. + * @param name + * @return + */ + protected static IllegalArgumentException invalidNamePatternException(String name) { + return new IllegalArgumentException("Not a valid questionnaire element name: " + name + ". Expected pattern is " + NAME_PATTERN); + } + + /** + * Build an exception about the name unicity. + * @param elementClass + * @param name + * @return + */ + @SuppressWarnings("unchecked") + protected static IllegalArgumentException invalidNameUnicityException(Class elementClass, String name) { + return new IllegalArgumentException(elementClass.getSimpleName() + " name must be unique: " + name + "."); + } + + /** + * Build an exception if an element cannot be found in the questionnaire from its name. + * @param elementClass + * @param name + * @return + */ + @SuppressWarnings("unchecked") + protected static IllegalStateException invalidElementNameException(Class elementClass, String name) { + return new IllegalStateException("Unable to find in questionnaire the " + elementClass.getSimpleName() + " with name: " + name + ". Create it first."); + } + + /** + * Get the current questionnaire element. + * @return + */ + public T getElement() { + return element; + } + + /** + * Get the questionnaire currently build. + * @return + */ + public Questionnaire getQuestionnaire() { + return questionnaire; + } + + + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/CategoryBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/CategoryBuilder.java index b744edc02..21f1d4eb5 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/CategoryBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/CategoryBuilder.java @@ -1,185 +1,194 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import java.util.List; -import java.util.Map; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.util.data.DataType; - -/** - * {@link Category} builder, given a {@link Questionnaire} and a current {@link Question}. - * @author Yannick Marcon - * - */ -public class CategoryBuilder extends AbstractQuestionnaireElementBuilder { - - private QuestionCategory questionCategory; - - /** - * Constructor using {@link QuestionBuilder} to get the {@link Question} it is applied to. - * @param parent - * @param category - */ - private CategoryBuilder(QuestionBuilder parent, Category category) { - super(parent.getQuestionnaire()); - this.element = category; - this.questionCategory = createQuestionCategory(parent.getElement()); - } - - /** - * Add a {@link Category} to current {@link Question}, make it the current category. - * @param name - * @param selected if is selected by default - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static CategoryBuilder createQuestionCategory(QuestionBuilder parent, String name) { - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - return new CategoryBuilder(parent, new Category(name)); - } - - /** - * Add a {@link Category} to current {@link Question}, make it the current category. - * @param name - * @param selected if is selected by default - * @return - */ - public static CategoryBuilder createQuestionCategory(QuestionBuilder parent, Category category) { - return new CategoryBuilder(parent, category); - } - - /** - * Set the export name to the current question category ({@link QuestionCategory}). - * @param exportName - * @return - */ - public CategoryBuilder setExportName(String exportName) { - questionCategory.setExportName(exportName); - return this; - } - - /** - * Set if the current question category ({@link QuestionCategory}) should be selected or not. - * @param selected - * @return - */ - public CategoryBuilder setSelected(boolean selected) { - questionCategory.setSelected(selected); - return this; - } - - /** - * Set if the current question category ({@link QuestionCategory}) should be repeatable or not. - * @param selected - * @return - */ - public CategoryBuilder setRepeatable(boolean repeatable) { - questionCategory.setRepeatable(repeatable); - return this; - } - - /** - * Set the {@link OpenAnswerDefinition} to the current category. - * @param name - * @param dataType - * @return - */ - public OpenAnswerDefinitionBuilder withOpenAnswerDefinition(String name, DataType dataType) { - return OpenAnswerDefinitionBuilder.createOpenAnswerDefinition(this, name, dataType); - } - - /** - * Add a {@link Category} to the current {@link Question}. - * @param name - * @return - */ - public CategoryBuilder withCategory(String name) { - this.element = new Category(name); - questionCategory = createQuestionCategory(questionCategory.getQuestion()); - return this; - } - - /** - * Add a set of {@link Category} to the current {@link Question}. - * @param names - * @return - */ - public CategoryBuilder withCategories(String... names) { - for(String name : names) { - withCategory(name); - } - return this; - } - - /** - * Look for a {@link Category} with the same name and given export name in the {@link QuestionnaireBuilder. Create it if not found. - * @param name - * @return - */ - public CategoryBuilder withSharedCategory(String name, String exportName) { - withSharedCategory(name).setExportName(exportName); - return this; - } - - /** - * Look for a {@link Category} with the same name in the {@link QuestionnaireBuilder. Create it if not found. - * @param name - * @return - */ - public CategoryBuilder withSharedCategory(String name) { - Map> map = QuestionnaireFinder.getInstance(questionnaire).findCategories(name); - if (map.keySet().size() > 1) { - throw invalidSharedCategoryNameUnicityException(name); - } - else if (map.keySet().isEmpty()) { - return withCategory(name); - } - else { - this.element = map.keySet().iterator().next(); - questionCategory = createQuestionCategory(questionCategory.getQuestion()); - return this; - } - } - - /** - * Add a set of {@link Category} by looking them from the name in the {@link Questionnaire}. Create them if not found. - * @param names - * @return - */ - public CategoryBuilder withSharedCategories(String... names) { - for(String name : names) { - withSharedCategory(name); - } - return this; - } - - /** - * Create the {@link QuestionCategory} for the current {@link Question} and {@link Category}. - * @param question - * @return - */ - private QuestionCategory createQuestionCategory(Question question) { - // make sure for is not already a category with same name in this question - for (Category category : question.getCategories()) { - if (category.getName().equals(element.getName())) { - throw new IllegalArgumentException("You cannot have categories with the same name in a question: " + element.getName()); - } - } - QuestionCategory questionCategory = new QuestionCategory(); - questionCategory.setSelected(false); - questionCategory.setCategory(element); - question.addQuestionCategory(questionCategory); - return questionCategory; - } - - private IllegalArgumentException invalidSharedCategoryNameUnicityException(String name) { - return new IllegalArgumentException("There are several categories with name: " + name); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import java.util.List; +import java.util.Map; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.util.data.DataType; + +/** + * {@link Category} builder, given a {@link Questionnaire} and a current {@link Question}. + * @author Yannick Marcon + * + */ +public class CategoryBuilder extends AbstractQuestionnaireElementBuilder { + + private QuestionCategory questionCategory; + + /** + * Constructor using {@link QuestionBuilder} to get the {@link Question} it is applied to. + * @param parent + * @param category + */ + private CategoryBuilder(QuestionBuilder parent, Category category) { + super(parent.getQuestionnaire()); + this.element = category; + this.questionCategory = createQuestionCategory(parent.getElement()); + } + + /** + * Add a {@link Category} to current {@link Question}, make it the current category. + * @param name + * @param selected if is selected by default + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static CategoryBuilder createQuestionCategory(QuestionBuilder parent, String name) { + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + return new CategoryBuilder(parent, new Category(name)); + } + + /** + * Add a {@link Category} to current {@link Question}, make it the current category. + * @param name + * @param selected if is selected by default + * @return + */ + public static CategoryBuilder createQuestionCategory(QuestionBuilder parent, Category category) { + return new CategoryBuilder(parent, category); + } + + /** + * Set the export name to the current question category ({@link QuestionCategory}). + * @param exportName + * @return + */ + public CategoryBuilder setExportName(String exportName) { + questionCategory.setExportName(exportName); + return this; + } + + /** + * Set if the current question category ({@link QuestionCategory}) should be selected or not. + * @param selected + * @return + */ + public CategoryBuilder setSelected(boolean selected) { + questionCategory.setSelected(selected); + return this; + } + + /** + * Set if the current question category ({@link QuestionCategory}) should be repeatable or not. + * @param selected + * @return + */ + public CategoryBuilder setRepeatable(boolean repeatable) { + questionCategory.setRepeatable(repeatable); + return this; + } + + /** + * Set the {@link OpenAnswerDefinition} to the current category. + * @param name + * @param dataType + * @return + */ + public OpenAnswerDefinitionBuilder withOpenAnswerDefinition(String name, DataType dataType) { + return OpenAnswerDefinitionBuilder.createOpenAnswerDefinition(this, name, dataType); + } + + /** + * Add a {@link Category} to the current {@link Question}. + * @param name + * @return + */ + public CategoryBuilder withCategory(String name) { + this.element = new Category(name); + questionCategory = createQuestionCategory(questionCategory.getQuestion()); + return this; + } + + /** + * Add a set of {@link Category} to the current {@link Question}. + * @param names + * @return + */ + public CategoryBuilder withCategories(String... names) { + for(String name : names) { + withCategory(name); + } + return this; + } + + /** + * Look for a {@link Category} with the same name and given export name in the {@link QuestionnaireBuilder. Create it if not found. + * @param name + * @return + */ + public CategoryBuilder withSharedCategory(String name, String exportName) { + withSharedCategory(name).setExportName(exportName); + return this; + } + + /** + * Look for a {@link Category} with the same name in the {@link QuestionnaireBuilder. Create it if not found. + * @param name + * @return + */ + public CategoryBuilder withSharedCategory(String name) { + Map> map = QuestionnaireFinder.getInstance(questionnaire).findCategories(name); + if (map.keySet().size() > 1) { + throw invalidSharedCategoryNameUnicityException(name); + } + else if (map.keySet().isEmpty()) { + return withCategory(name); + } + else { + this.element = map.keySet().iterator().next(); + questionCategory = createQuestionCategory(questionCategory.getQuestion()); + return this; + } + } + + /** + * Add a set of {@link Category} by looking them from the name in the {@link Questionnaire}. Create them if not found. + * @param names + * @return + */ + public CategoryBuilder withSharedCategories(String... names) { + for(String name : names) { + withSharedCategory(name); + } + return this; + } + + /** + * Create the {@link QuestionCategory} for the current {@link Question} and {@link Category}. + * @param question + * @return + */ + private QuestionCategory createQuestionCategory(Question question) { + // make sure for is not already a category with same name in this question + for (Category category : question.getCategories()) { + if (category.getName().equals(element.getName())) { + throw new IllegalArgumentException("You cannot have categories with the same name in a question: " + element.getName()); + } + } + QuestionCategory questionCategory = new QuestionCategory(); + questionCategory.setSelected(false); + questionCategory.setCategory(element); + question.addQuestionCategory(questionCategory); + return questionCategory; + } + + private IllegalArgumentException invalidSharedCategoryNameUnicityException(String name) { + return new IllegalArgumentException("There are several categories with name: " + name); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/IPropertyKeyWriter.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/IPropertyKeyWriter.java index d48a0ca65..852cd1587 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/IPropertyKeyWriter.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/IPropertyKeyWriter.java @@ -1,44 +1,53 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; - -/** - * Interface for writing the {@link Questionnaire} localization properties to different kind of medias. - * @author Yannick Marcon - * @see ILocalizable - * - */ -public interface IPropertyKeyWriter { - - /** - * Properties from which values can be fetched. - * @return - */ - public Properties getReference(); - - /** - * Call for key value pair writing. - * @param key - * @param value - */ - public void write(String key, String value); - - /** - * Write property comments. - * @param comments - */ - public void writeComment(String... comments); - - /** - * Questionnaire properties can be divided in several blocs, for fancy user reading. - */ - public void endBloc(); - - /** - * Call when writing is finished. - */ - public void end(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; + +/** + * Interface for writing the {@link Questionnaire} localization properties to different kind of medias. + * @author Yannick Marcon + * @see ILocalizable + * + */ +public interface IPropertyKeyWriter { + + /** + * Properties from which values can be fetched. + * @return + */ + public Properties getReference(); + + /** + * Call for key value pair writing. + * @param key + * @param value + */ + public void write(String key, String value); + + /** + * Write property comments. + * @param comments + */ + public void writeComment(String... comments); + + /** + * Questionnaire properties can be divided in several blocs, for fancy user reading. + */ + public void endBloc(); + + /** + * Call when writing is finished. + */ + public void end(); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/OpenAnswerDefinitionBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/OpenAnswerDefinitionBuilder.java index a5c559ace..2d60411c1 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/OpenAnswerDefinitionBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/OpenAnswerDefinitionBuilder.java @@ -1,172 +1,181 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; - -/** - * {@link OpenAnswerDefinition} builder, given a {@link Questionnaire} and a current {@link Category}. - * @author Yannick Marcon - * - */ -public class OpenAnswerDefinitionBuilder extends AbstractQuestionnaireElementBuilder { - - /** - * Constructor using {@link CategoryBuilder} to get the {@link Category} it is applied to. - * @param parent - * @param name - * @param dataType - */ - private OpenAnswerDefinitionBuilder(CategoryBuilder parent, String name, DataType dataType) { - super(parent.getQuestionnaire()); - if(!checkUniqueOpenAnswerDefinitionName(name)) { - throw invalidNameUnicityException(OpenAnswerDefinition.class, name); - } - element = new OpenAnswerDefinition(name, dataType); - parent.getElement().setOpenAnswerDefinition(element); - } - - /** - * Set the {@link OpenAnswerDefinition} to the current category. - * @param name - * @param dataType - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static OpenAnswerDefinitionBuilder createOpenAnswerDefinition(CategoryBuilder parent, String name, DataType dataType) { - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - return new OpenAnswerDefinitionBuilder(parent, name, dataType); - } - - /** - * Set the absolute range to the current {@link OpenAnswerDefinition}. - * @param minValue no limit if null - * @param maxValue no limit if null - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionAbsoluteValues(Data minValue, Data maxValue) { - element.setAbsoluteMinValue(minValue); - element.setAbsoluteMaxValue(maxValue); - - return this; - } - - /** - * Set the absolute range to the current {@link OpenAnswerDefinition}. - * @param minValue no limit if null or no length - * @param maxValue no limit if null or no length - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionAbsoluteValues(String minValue, String maxValue) { - if(minValue != null && minValue.length() > 0) { - element.setAbsoluteMinValue(DataBuilder.build(element.getDataType(), minValue)); - } else { - element.setAbsoluteMinValue(null); - } - if(maxValue != null && maxValue.length() > 0) { - element.setAbsoluteMaxValue(DataBuilder.build(element.getDataType(), maxValue)); - } else { - element.setAbsoluteMaxValue(null); - } - - return this; - } - - /** - * Set the usual range to the current {@link OpenAnswerDefinition}. - * @param minValue no limit if null - * @param maxValue no limit if null - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUsualValues(Data minValue, Data maxValue) { - element.setUsualMinValue(minValue); - element.setUsualMaxValue(maxValue); - - return this; - } - - /** - * Set the usual range to the current {@link OpenAnswerDefinition}. - * @param minValue no limit if null or no length - * @param maxValue no limit if null or no length - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUsualValues(String minValue, String maxValue) { - if(minValue != null && minValue.length() > 0) { - element.setUsualMinValue(DataBuilder.build(element.getDataType(), minValue)); - } else { - element.setUsualMinValue(null); - } - if(maxValue != null && maxValue.length() > 0) { - element.setUsualMaxValue(DataBuilder.build(element.getDataType(), maxValue)); - } else { - element.setUsualMaxValue(null); - } - - return this; - } - - /** - * Set the unit to the current {@link OpenAnswerDefinition}. - * @param unit - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUnit(String unit) { - element.setUnit(unit); - - return this; - } - - /** - * Set the data format to the current {@link OpenAnswerDefinition}. - * @param format - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionFormat(String format) { - element.setFormat(format); - - return this; - } - - /** - * Set the default data to the current {@link OpenAnswerDefinition}. - * @param data - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionDefaultData(Data... defaultValues) { - for(Data value : defaultValues) { - element.addDefaultValue(value); - } - - return this; - } - - /** - * Set the default data to the current {@link OpenAnswerDefinition}. - * @param data - * @return - */ - public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionDefaultData(String... defaultValues) { - for(String value : defaultValues) { - element.addDefaultValue(value); - } - - return this; - } - - /** - * Check open answer definition name unicity. - * @param name - * @return - */ - private boolean checkUniqueOpenAnswerDefinitionName(String name) { - return (QuestionnaireFinder.getInstance(questionnaire).findOpenAnswerDefinition(name) == null); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; + +/** + * {@link OpenAnswerDefinition} builder, given a {@link Questionnaire} and a current {@link Category}. + * @author Yannick Marcon + * + */ +public class OpenAnswerDefinitionBuilder extends AbstractQuestionnaireElementBuilder { + + /** + * Constructor using {@link CategoryBuilder} to get the {@link Category} it is applied to. + * @param parent + * @param name + * @param dataType + */ + private OpenAnswerDefinitionBuilder(CategoryBuilder parent, String name, DataType dataType) { + super(parent.getQuestionnaire()); + if(!checkUniqueOpenAnswerDefinitionName(name)) { + throw invalidNameUnicityException(OpenAnswerDefinition.class, name); + } + element = new OpenAnswerDefinition(name, dataType); + parent.getElement().setOpenAnswerDefinition(element); + } + + /** + * Set the {@link OpenAnswerDefinition} to the current category. + * @param name + * @param dataType + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static OpenAnswerDefinitionBuilder createOpenAnswerDefinition(CategoryBuilder parent, String name, DataType dataType) { + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + return new OpenAnswerDefinitionBuilder(parent, name, dataType); + } + + /** + * Set the absolute range to the current {@link OpenAnswerDefinition}. + * @param minValue no limit if null + * @param maxValue no limit if null + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionAbsoluteValues(Data minValue, Data maxValue) { + element.setAbsoluteMinValue(minValue); + element.setAbsoluteMaxValue(maxValue); + + return this; + } + + /** + * Set the absolute range to the current {@link OpenAnswerDefinition}. + * @param minValue no limit if null or no length + * @param maxValue no limit if null or no length + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionAbsoluteValues(String minValue, String maxValue) { + if(minValue != null && minValue.length() > 0) { + element.setAbsoluteMinValue(DataBuilder.build(element.getDataType(), minValue)); + } else { + element.setAbsoluteMinValue(null); + } + if(maxValue != null && maxValue.length() > 0) { + element.setAbsoluteMaxValue(DataBuilder.build(element.getDataType(), maxValue)); + } else { + element.setAbsoluteMaxValue(null); + } + + return this; + } + + /** + * Set the usual range to the current {@link OpenAnswerDefinition}. + * @param minValue no limit if null + * @param maxValue no limit if null + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUsualValues(Data minValue, Data maxValue) { + element.setUsualMinValue(minValue); + element.setUsualMaxValue(maxValue); + + return this; + } + + /** + * Set the usual range to the current {@link OpenAnswerDefinition}. + * @param minValue no limit if null or no length + * @param maxValue no limit if null or no length + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUsualValues(String minValue, String maxValue) { + if(minValue != null && minValue.length() > 0) { + element.setUsualMinValue(DataBuilder.build(element.getDataType(), minValue)); + } else { + element.setUsualMinValue(null); + } + if(maxValue != null && maxValue.length() > 0) { + element.setUsualMaxValue(DataBuilder.build(element.getDataType(), maxValue)); + } else { + element.setUsualMaxValue(null); + } + + return this; + } + + /** + * Set the unit to the current {@link OpenAnswerDefinition}. + * @param unit + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionUnit(String unit) { + element.setUnit(unit); + + return this; + } + + /** + * Set the data format to the current {@link OpenAnswerDefinition}. + * @param format + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionFormat(String format) { + element.setFormat(format); + + return this; + } + + /** + * Set the default data to the current {@link OpenAnswerDefinition}. + * @param data + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionDefaultData(Data... defaultValues) { + for(Data value : defaultValues) { + element.addDefaultValue(value); + } + + return this; + } + + /** + * Set the default data to the current {@link OpenAnswerDefinition}. + * @param data + * @return + */ + public OpenAnswerDefinitionBuilder setOpenAnswerDefinitionDefaultData(String... defaultValues) { + for(String value : defaultValues) { + element.addDefaultValue(value); + } + + return this; + } + + /** + * Check open answer definition name unicity. + * @param name + * @return + */ + private boolean checkUniqueOpenAnswerDefinitionName(String name) { + return (QuestionnaireFinder.getInstance(questionnaire).findOpenAnswerDefinition(name) == null); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PageBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PageBuilder.java index cba126f0a..5ee3e3c81 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PageBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PageBuilder.java @@ -1,139 +1,148 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; -import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; -import org.obiba.onyx.quartz.core.wicket.layout.impl.DefaultPageLayoutFactory; - -/** - * {@link Page} builder, given a {@link Questionnaire} and a current {@link Section}. - * @author Yannick Marcon - * - */ -public class PageBuilder extends AbstractQuestionnaireElementBuilder { - - /** - * Constructor using {@link SectionBuilder} to get the {@link Section} it is applied to. - * @param sectionBuilder - * @param name - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - private PageBuilder(SectionBuilder sectionBuilder, String name, Class uiFactoryClass) { - super(sectionBuilder.getQuestionnaire()); - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - if(!checkUniquePageName(name)) { - throw invalidNameUnicityException(Page.class, name); - } - this.element = new Page(name); - try { - this.element.setUIFactoryName(uiFactoryClass.newInstance().getName()); - } catch(Exception e) { - throw invalidPageLayoutFactoryException(uiFactoryClass, e); - } - this.questionnaire.addPage(element); - sectionBuilder.getElement().addPage(element); - } - - /** - * Constructor. - * @param questionnaire - * @param page - */ - private PageBuilder(Questionnaire questionnaire, Page page) { - super(questionnaire); - this.element = page; - } - - /** - * Create a page in a {@link Section} given its name. - * @param parent - * @param name - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static PageBuilder createPage(SectionBuilder parent, String name) { - return new PageBuilder(parent, name, DefaultPageLayoutFactory.class); - } - - /** - * Create a page in a {@link Section} given its name. - * @param parent - * @param name - * @param uiFactoryClass - * @return - */ - public static PageBuilder createPage(SectionBuilder parent, String name, Class uiFactoryClass) { - return new PageBuilder(parent, name, uiFactoryClass); - } - - /** - * Set the given {@link Page} as the current one. - * @param questionnaire - * @param page - * @return - */ - public static PageBuilder inPage(Questionnaire questionnaire, Page page) { - return new PageBuilder(questionnaire, page); - } - - /** - * Add a required, non multiple, {@link Question} to current {@link Page} and make it current {@link Question}. - * @param name - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name) { - return QuestionBuilder.createQuestion(this, name, false); - } - - /** - * Add a required, non multiple, {@link Question} to current {@link Page} and make it current {@link Question}. - * @param name - * @param uiFactoryClass - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name, Class uiFactoryClass) { - return QuestionBuilder.createQuestion(this, name, false, uiFactoryClass); - } - - /** - * Add a required, {@link Question} to current {@link Page} and make it current {@link Question}. - * @param name - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name, boolean multiple) { - return QuestionBuilder.createQuestion(this, name, multiple); - } - - /** - * Add a required, {@link Question} to current {@link Page} and make it current {@link Question}. - * @param name - * @param uiFactoryName - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name, boolean multiple, Class uiFactoryClass) { - return QuestionBuilder.createQuestion(this, name, multiple, uiFactoryClass); - } - - /** - * Check page name unicity. - * @param name - * @return - */ - private boolean checkUniquePageName(String name) { - return (QuestionnaireFinder.getInstance(questionnaire).findPage(name) == null); - } - - private IllegalArgumentException invalidPageLayoutFactoryException(Class uiFactoryClass, Exception e) { - return new IllegalArgumentException("Unable to get page layout factory name from " + uiFactoryClass.getName(), e); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; +import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; +import org.obiba.onyx.quartz.core.wicket.layout.impl.DefaultPageLayoutFactory; + +/** + * {@link Page} builder, given a {@link Questionnaire} and a current {@link Section}. + * @author Yannick Marcon + * + */ +public class PageBuilder extends AbstractQuestionnaireElementBuilder { + + /** + * Constructor using {@link SectionBuilder} to get the {@link Section} it is applied to. + * @param sectionBuilder + * @param name + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + private PageBuilder(SectionBuilder sectionBuilder, String name, Class uiFactoryClass) { + super(sectionBuilder.getQuestionnaire()); + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + if(!checkUniquePageName(name)) { + throw invalidNameUnicityException(Page.class, name); + } + this.element = new Page(name); + try { + this.element.setUIFactoryName(uiFactoryClass.newInstance().getName()); + } catch(Exception e) { + throw invalidPageLayoutFactoryException(uiFactoryClass, e); + } + this.questionnaire.addPage(element); + sectionBuilder.getElement().addPage(element); + } + + /** + * Constructor. + * @param questionnaire + * @param page + */ + private PageBuilder(Questionnaire questionnaire, Page page) { + super(questionnaire); + this.element = page; + } + + /** + * Create a page in a {@link Section} given its name. + * @param parent + * @param name + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static PageBuilder createPage(SectionBuilder parent, String name) { + return new PageBuilder(parent, name, DefaultPageLayoutFactory.class); + } + + /** + * Create a page in a {@link Section} given its name. + * @param parent + * @param name + * @param uiFactoryClass + * @return + */ + public static PageBuilder createPage(SectionBuilder parent, String name, Class uiFactoryClass) { + return new PageBuilder(parent, name, uiFactoryClass); + } + + /** + * Set the given {@link Page} as the current one. + * @param questionnaire + * @param page + * @return + */ + public static PageBuilder inPage(Questionnaire questionnaire, Page page) { + return new PageBuilder(questionnaire, page); + } + + /** + * Add a required, non multiple, {@link Question} to current {@link Page} and make it current {@link Question}. + * @param name + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name) { + return QuestionBuilder.createQuestion(this, name, false); + } + + /** + * Add a required, non multiple, {@link Question} to current {@link Page} and make it current {@link Question}. + * @param name + * @param uiFactoryClass + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name, Class uiFactoryClass) { + return QuestionBuilder.createQuestion(this, name, false, uiFactoryClass); + } + + /** + * Add a required, {@link Question} to current {@link Page} and make it current {@link Question}. + * @param name + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name, boolean multiple) { + return QuestionBuilder.createQuestion(this, name, multiple); + } + + /** + * Add a required, {@link Question} to current {@link Page} and make it current {@link Question}. + * @param name + * @param uiFactoryName + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name, boolean multiple, Class uiFactoryClass) { + return QuestionBuilder.createQuestion(this, name, multiple, uiFactoryClass); + } + + /** + * Check page name unicity. + * @param name + * @return + */ + private boolean checkUniquePageName(String name) { + return (QuestionnaireFinder.getInstance(questionnaire).findPage(name) == null); + } + + private IllegalArgumentException invalidPageLayoutFactoryException(Class uiFactoryClass, Exception e) { + return new IllegalArgumentException("Unable to get page layout factory name from " + uiFactoryClass.getName(), e); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PropertyKeyWriterVisitor.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PropertyKeyWriterVisitor.java index 8a1c7e2b3..b81800ede 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PropertyKeyWriterVisitor.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/PropertyKeyWriterVisitor.java @@ -1,131 +1,140 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.IWalkerVisitor; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Questionnaire visitor for building localization properties at each questionnaire element visit. - * @author Yannick Marcon - * - */ -public class PropertyKeyWriterVisitor implements IWalkerVisitor { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(PropertyKeyWriterVisitor.class); - - private IPropertyKeyProvider propertyKeyProvider; - - private IPropertyKeyWriter writer; - - private List propertyKeys = new ArrayList(); - - /** - * Constructor, given property key provider and writer. - * @param propertyKeyProvider - * @param writer - */ - public PropertyKeyWriterVisitor(IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { - this.propertyKeyProvider = propertyKeyProvider; - this.writer = writer; - } - - public void visit(Questionnaire questionnaire) { - writer.writeComment("", "Questionnaire: " + questionnaire.getName() + ", version " + questionnaire.getVersion(), ""); - writePropertyKey(questionnaire); - writer.writeComment("", "Shared categories", ""); - for(Category category : QuestionnaireFinder.getInstance(questionnaire).findSharedCategories()) { - writePropertyKey(category); - } - } - - public void visit(Section section) { - writePropertyKey(section); - } - - public void visit(Page page) { - writePropertyKey(page); - } - - public void visit(Question question) { - writer.writeComment("", "Question " + question.getName(), ""); - writePropertyKey(question); - } - - public void visit(QuestionCategory questionCategory) { - writePropertyKey(questionCategory, questionCategory.getCategory()); - } - - public void visit(Category category) { - // write category property keys only if it is a shared one - // this is done when visiting questionnaire - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - writePropertyKey(openAnswerDefinition); - } - - /** - * Shortcut method call. - * @param localizable - * @param properties - */ - private void writePropertyKey(ILocalizable localizable) { - writePropertyKey(localizable, null); - } - - /** - * For each of the localization keys declared by the {@link ILocalizable} add it to the properties object. Set the - * value to null by default or to the localization interpolation key. - * @param localizable - * @param interpolationLocalizable - * @param writer - */ - private void writePropertyKey(ILocalizable localizable, ILocalizable interpolationLocalizable) { - boolean written = false; - for(String property : propertyKeyProvider.getProperties(localizable)) { - String key = propertyKeyProvider.getPropertyKey(localizable, property); - if(!propertyKeys.contains(key)) { - Properties ref = writer.getReference(); - if(ref != null && ref.containsKey(key) && !ref.get(key).equals("")) { - // property key value already defined - writer.write(key, ref.getProperty(key)); - } else if(interpolationLocalizable != null) { - String interpolationKey = propertyKeyProvider.getPropertyKey(interpolationLocalizable, property); - if(propertyKeys.contains(interpolationKey)) { - // interpolation already written, just refer to it - writer.write(key, "${" + interpolationKey + "}"); - } else { - // interpolation not already written, then ignored - writer.write(key, ""); - } - } else { - writer.write(key, ""); - } - propertyKeys.add(key); - written = true; - } - } - if(written) writer.endBloc(); - } - - public boolean visiteMore() { - // no stop - return true; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.IWalkerVisitor; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Questionnaire visitor for building localization properties at each questionnaire element visit. + * @author Yannick Marcon + * + */ +public class PropertyKeyWriterVisitor implements IWalkerVisitor { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(PropertyKeyWriterVisitor.class); + + private IPropertyKeyProvider propertyKeyProvider; + + private IPropertyKeyWriter writer; + + private List propertyKeys = new ArrayList(); + + /** + * Constructor, given property key provider and writer. + * @param propertyKeyProvider + * @param writer + */ + public PropertyKeyWriterVisitor(IPropertyKeyProvider propertyKeyProvider, IPropertyKeyWriter writer) { + this.propertyKeyProvider = propertyKeyProvider; + this.writer = writer; + } + + public void visit(Questionnaire questionnaire) { + writer.writeComment("", "Questionnaire: " + questionnaire.getName() + ", version " + questionnaire.getVersion(), ""); + writePropertyKey(questionnaire); + writer.writeComment("", "Shared categories", ""); + for(Category category : QuestionnaireFinder.getInstance(questionnaire).findSharedCategories()) { + writePropertyKey(category); + } + } + + public void visit(Section section) { + writePropertyKey(section); + } + + public void visit(Page page) { + writePropertyKey(page); + } + + public void visit(Question question) { + writer.writeComment("", "Question " + question.getName(), ""); + writePropertyKey(question); + } + + public void visit(QuestionCategory questionCategory) { + writePropertyKey(questionCategory, questionCategory.getCategory()); + } + + public void visit(Category category) { + // write category property keys only if it is a shared one + // this is done when visiting questionnaire + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + writePropertyKey(openAnswerDefinition); + } + + /** + * Shortcut method call. + * @param localizable + * @param properties + */ + private void writePropertyKey(ILocalizable localizable) { + writePropertyKey(localizable, null); + } + + /** + * For each of the localization keys declared by the {@link ILocalizable} add it to the properties object. Set the + * value to null by default or to the localization interpolation key. + * @param localizable + * @param interpolationLocalizable + * @param writer + */ + private void writePropertyKey(ILocalizable localizable, ILocalizable interpolationLocalizable) { + boolean written = false; + for(String property : propertyKeyProvider.getProperties(localizable)) { + String key = propertyKeyProvider.getPropertyKey(localizable, property); + if(!propertyKeys.contains(key)) { + Properties ref = writer.getReference(); + if(ref != null && ref.containsKey(key) && !ref.get(key).equals("")) { + // property key value already defined + writer.write(key, ref.getProperty(key)); + } else if(interpolationLocalizable != null) { + String interpolationKey = propertyKeyProvider.getPropertyKey(interpolationLocalizable, property); + if(propertyKeys.contains(interpolationKey)) { + // interpolation already written, just refer to it + writer.write(key, "${" + interpolationKey + "}"); + } else { + // interpolation not already written, then ignored + writer.write(key, ""); + } + } else { + writer.write(key, ""); + } + propertyKeys.add(key); + written = true; + } + } + if(written) writer.endBloc(); + } + + public boolean visiteMore() { + // no stop + return true; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/QuestionBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/QuestionBuilder.java index 9c3c68d02..4274693ab 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/QuestionBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/QuestionBuilder.java @@ -1,263 +1,272 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import java.util.List; -import java.util.Map; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; -import org.obiba.onyx.quartz.core.wicket.layout.impl.DefaultQuestionPanelFactory; - -/** - * {@link Question} builder, given a {@link Questionnaire} and a current {@link Page}. - * @author Yannick Marcon - * - */ -public class QuestionBuilder extends AbstractQuestionnaireElementBuilder { - - /** - * Constructor using {@link PageBuilder} to get the {@link Page} it is applied to. - * @param parent - * @param name - * @param multiple - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - private QuestionBuilder(PageBuilder parent, String name, boolean multiple, Class uiFactoryClass) { - super(parent.getQuestionnaire()); - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - if(!checkUniqueQuestionName(name)) { - throw invalidNameUnicityException(Question.class, name); - } - element = new Question(name); - element.setRequired(true); - element.setMultiple(false); - try { - element.setUIFactoryName(uiFactoryClass.newInstance().getName()); - } catch(Exception e) { - throw invalidQuestionPanelFactoryException(uiFactoryClass, e); - } - parent.getElement().addQuestion(element); - } - - /** - * Constructor. - * @param questionnaire - * @param question - */ - private QuestionBuilder(Questionnaire questionnaire, Question question) { - super(questionnaire); - this.element = question; - } - - /** - * Create a {@link Question} in the given {@link Page}. - * @param parent - * @param name - * @param multiple - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static QuestionBuilder createQuestion(PageBuilder parent, String name, boolean multiple) { - return createQuestion(parent, name, multiple, DefaultQuestionPanelFactory.class); - } - - /** - * Create a {@link Question} in the given {@link Page}. - * @param parent - * @param name - * @param multiple - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static QuestionBuilder createQuestion(PageBuilder parent, String name, boolean multiple, Class uiFactoryClass) { - return new QuestionBuilder(parent, name, multiple, uiFactoryClass); - } - - /** - * Set the given {@link Question} as the current one. - * @param questionnaire - * @param question - * @return - */ - public static QuestionBuilder inQuestion(Questionnaire questionnaire, Question question) { - return new QuestionBuilder(questionnaire, question); - } - - /** - * Add a required, non multiple, {@link Question} to current {@link Question} and make it current {@link Question}. - * @param name - * @return - */ - public QuestionBuilder withQuestion(String name) { - return withQuestion(name, false); - } - - /** - * Add a required, non multiple, {@link Question} to current {@link Question} and make it current {@link Question}. - * @param name - * @param uiFactoryClass - * @return - */ - public QuestionBuilder withQuestion(String name, Class uiFactoryClass) { - return withQuestion(name, false, uiFactoryClass); - } - - /** - * Add a required {@link Question} to current {@link Question} and make it current {@link Question}. - * @param name - * @param multiple - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name, boolean multiple) { - return withQuestion(name, multiple, DefaultQuestionPanelFactory.class); - } - - /** - * Add a required {@link Question} to current {@link Question} and make it current {@link Question}. - * @param name - * @param multiple - * @param uiFactoryClass - * @return - * @see #getQuestion() - */ - public QuestionBuilder withQuestion(String name, boolean multiple, Class uiFactoryClass) { - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - if(!checkUniqueQuestionName(name)) { - throw invalidNameUnicityException(Question.class, name); - } - String uiFactoryName; - try { - uiFactoryName = uiFactoryClass.newInstance().getName(); - } catch(Exception e) { - throw invalidQuestionPanelFactoryException(uiFactoryClass, e); - } - Question question = new Question(name); - question.setRequired(true); - question.setMultiple(false); - question.setUIFactoryName(uiFactoryName); - element.addQuestion(question); - element = question; - - return this; - } - - /** - * Set if current {@link Question} is required. - * @param required - * @return - */ - public QuestionBuilder setRequired(boolean required) { - element.setRequired(required); - - return this; - } - - /** - * Set the range of answer count for current {@link Question}. - * @param minCount no limit if null - * @param maxCount no limit if null - * @return - */ - public QuestionBuilder setAnswerCount(Integer minCount, Integer maxCount) { - element.setMinCount(minCount); - element.setMaxCount(maxCount); - - return this; - } - - /** - * Add a {@link Category} to current {@link Question}, make it the current category. - * @param name - * @return - */ - public CategoryBuilder withCategory(String name) { - return CategoryBuilder.createQuestionCategory(this, name); - } - - /** - * Add a set of {@link Category} to current {@link Question}. - * @param names - * @return - */ - public CategoryBuilder withCategories(String... names) { - CategoryBuilder child = null; - - for(String name : names) { - child = withCategory(name); - } - - return child; - } - - /** - * Look for the {@link Category} with the given name in the current {@link Questionnaire}, add it (create it if - * necessary) to the current {@link Question}, make it the current category. - * @param name - * @return - */ - public CategoryBuilder withSharedCategory(String name) { - Map> map = QuestionnaireFinder.getInstance(questionnaire).findCategories(name); - if (map.keySet().size() > 1) { - throw invalidSharedCategoryNameUnicityException(name); - } - else if (map.keySet().isEmpty()) { - return withCategory(name); - } - else { - return CategoryBuilder.createQuestionCategory(this, map.keySet().iterator().next()); - } - } - - /** - * Look for the {@link Category} with the given name in the current {@link Questionnaire}, add it (create it if - * necessary) to the current {@link Question}, make it the current category. - * @param name - * @param exportName - * @return - */ - public CategoryBuilder withSharedCategory(String name, String exportName) { - CategoryBuilder builder = withSharedCategory(name); - builder.setExportName(exportName); - return builder; - } - - /** - * Add a set of shared {@link Category} to current {@link Question}. - * @param names - * @return - */ - public CategoryBuilder withSharedCategories(String... names) { - CategoryBuilder child = null; - - for(String name : names) { - child = withSharedCategory(name); - } - - return child; - } - - /** - * Check question name unicity. - * @param name - * @return - */ - private boolean checkUniqueQuestionName(String name) { - return (QuestionnaireFinder.getInstance(questionnaire).findQuestion(name) == null); - } - - private IllegalArgumentException invalidSharedCategoryNameUnicityException(String name) { - return new IllegalArgumentException("There are several categories with name: " + name); - } - - private IllegalArgumentException invalidQuestionPanelFactoryException(Class uiFactoryClass, Exception e) { - return new IllegalArgumentException("Unable to get question panel factory name from " + uiFactoryClass.getName(), e); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import java.util.List; +import java.util.Map; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; +import org.obiba.onyx.quartz.core.wicket.layout.impl.DefaultQuestionPanelFactory; + +/** + * {@link Question} builder, given a {@link Questionnaire} and a current {@link Page}. + * @author Yannick Marcon + * + */ +public class QuestionBuilder extends AbstractQuestionnaireElementBuilder { + + /** + * Constructor using {@link PageBuilder} to get the {@link Page} it is applied to. + * @param parent + * @param name + * @param multiple + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + private QuestionBuilder(PageBuilder parent, String name, boolean multiple, Class uiFactoryClass) { + super(parent.getQuestionnaire()); + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + if(!checkUniqueQuestionName(name)) { + throw invalidNameUnicityException(Question.class, name); + } + element = new Question(name); + element.setRequired(true); + element.setMultiple(false); + try { + element.setUIFactoryName(uiFactoryClass.newInstance().getName()); + } catch(Exception e) { + throw invalidQuestionPanelFactoryException(uiFactoryClass, e); + } + parent.getElement().addQuestion(element); + } + + /** + * Constructor. + * @param questionnaire + * @param question + */ + private QuestionBuilder(Questionnaire questionnaire, Question question) { + super(questionnaire); + this.element = question; + } + + /** + * Create a {@link Question} in the given {@link Page}. + * @param parent + * @param name + * @param multiple + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static QuestionBuilder createQuestion(PageBuilder parent, String name, boolean multiple) { + return createQuestion(parent, name, multiple, DefaultQuestionPanelFactory.class); + } + + /** + * Create a {@link Question} in the given {@link Page}. + * @param parent + * @param name + * @param multiple + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static QuestionBuilder createQuestion(PageBuilder parent, String name, boolean multiple, Class uiFactoryClass) { + return new QuestionBuilder(parent, name, multiple, uiFactoryClass); + } + + /** + * Set the given {@link Question} as the current one. + * @param questionnaire + * @param question + * @return + */ + public static QuestionBuilder inQuestion(Questionnaire questionnaire, Question question) { + return new QuestionBuilder(questionnaire, question); + } + + /** + * Add a required, non multiple, {@link Question} to current {@link Question} and make it current {@link Question}. + * @param name + * @return + */ + public QuestionBuilder withQuestion(String name) { + return withQuestion(name, false); + } + + /** + * Add a required, non multiple, {@link Question} to current {@link Question} and make it current {@link Question}. + * @param name + * @param uiFactoryClass + * @return + */ + public QuestionBuilder withQuestion(String name, Class uiFactoryClass) { + return withQuestion(name, false, uiFactoryClass); + } + + /** + * Add a required {@link Question} to current {@link Question} and make it current {@link Question}. + * @param name + * @param multiple + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name, boolean multiple) { + return withQuestion(name, multiple, DefaultQuestionPanelFactory.class); + } + + /** + * Add a required {@link Question} to current {@link Question} and make it current {@link Question}. + * @param name + * @param multiple + * @param uiFactoryClass + * @return + * @see #getQuestion() + */ + public QuestionBuilder withQuestion(String name, boolean multiple, Class uiFactoryClass) { + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + if(!checkUniqueQuestionName(name)) { + throw invalidNameUnicityException(Question.class, name); + } + String uiFactoryName; + try { + uiFactoryName = uiFactoryClass.newInstance().getName(); + } catch(Exception e) { + throw invalidQuestionPanelFactoryException(uiFactoryClass, e); + } + Question question = new Question(name); + question.setRequired(true); + question.setMultiple(false); + question.setUIFactoryName(uiFactoryName); + element.addQuestion(question); + element = question; + + return this; + } + + /** + * Set if current {@link Question} is required. + * @param required + * @return + */ + public QuestionBuilder setRequired(boolean required) { + element.setRequired(required); + + return this; + } + + /** + * Set the range of answer count for current {@link Question}. + * @param minCount no limit if null + * @param maxCount no limit if null + * @return + */ + public QuestionBuilder setAnswerCount(Integer minCount, Integer maxCount) { + element.setMinCount(minCount); + element.setMaxCount(maxCount); + + return this; + } + + /** + * Add a {@link Category} to current {@link Question}, make it the current category. + * @param name + * @return + */ + public CategoryBuilder withCategory(String name) { + return CategoryBuilder.createQuestionCategory(this, name); + } + + /** + * Add a set of {@link Category} to current {@link Question}. + * @param names + * @return + */ + public CategoryBuilder withCategories(String... names) { + CategoryBuilder child = null; + + for(String name : names) { + child = withCategory(name); + } + + return child; + } + + /** + * Look for the {@link Category} with the given name in the current {@link Questionnaire}, add it (create it if + * necessary) to the current {@link Question}, make it the current category. + * @param name + * @return + */ + public CategoryBuilder withSharedCategory(String name) { + Map> map = QuestionnaireFinder.getInstance(questionnaire).findCategories(name); + if (map.keySet().size() > 1) { + throw invalidSharedCategoryNameUnicityException(name); + } + else if (map.keySet().isEmpty()) { + return withCategory(name); + } + else { + return CategoryBuilder.createQuestionCategory(this, map.keySet().iterator().next()); + } + } + + /** + * Look for the {@link Category} with the given name in the current {@link Questionnaire}, add it (create it if + * necessary) to the current {@link Question}, make it the current category. + * @param name + * @param exportName + * @return + */ + public CategoryBuilder withSharedCategory(String name, String exportName) { + CategoryBuilder builder = withSharedCategory(name); + builder.setExportName(exportName); + return builder; + } + + /** + * Add a set of shared {@link Category} to current {@link Question}. + * @param names + * @return + */ + public CategoryBuilder withSharedCategories(String... names) { + CategoryBuilder child = null; + + for(String name : names) { + child = withSharedCategory(name); + } + + return child; + } + + /** + * Check question name unicity. + * @param name + * @return + */ + private boolean checkUniqueQuestionName(String name) { + return (QuestionnaireFinder.getInstance(questionnaire).findQuestion(name) == null); + } + + private IllegalArgumentException invalidSharedCategoryNameUnicityException(String name) { + return new IllegalArgumentException("There are several categories with name: " + name); + } + + private IllegalArgumentException invalidQuestionPanelFactoryException(Class uiFactoryClass, Exception e) { + return new IllegalArgumentException("Unable to get question panel factory name from " + uiFactoryClass.getName(), e); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/SectionBuilder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/SectionBuilder.java index cfdc52674..0503a99cb 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/SectionBuilder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/SectionBuilder.java @@ -1,108 +1,117 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; -import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; - -/** - * {@link Section} builder, given a {@link Questionnaire}. - * @author cag-ymarcon - * - */ -public class SectionBuilder extends AbstractQuestionnaireElementBuilder
{ - - /** - * Constructor using the {@link QuestionnaireBuilder} to get the {@link Questionnaire} it is applied to. - * @param parent - * @param name - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - private SectionBuilder(QuestionnaireBuilder parent, String name) { - super(parent.getQuestionnaire()); - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - if(!checkUniqueSectionName(name)) { - throw invalidNameUnicityException(Section.class, name); - } - this.element = new Section(name); - this.questionnaire.addSection(element); - } - - /** - * Constructor. - * @param questionnaire - * @param section - */ - private SectionBuilder(Questionnaire questionnaire, Section section) { - super(questionnaire); - this.element = section; - } - - /** - * Create a section in the {@link Questionnaire}. - * @param parent - * @param name - * @return - * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. - */ - public static SectionBuilder createSection(QuestionnaireBuilder parent, String name) { - return new SectionBuilder(parent, name); - } - - public static SectionBuilder inSection(Questionnaire questionnaire, Section section) { - return new SectionBuilder(questionnaire, section); - } - - /** - * Add a {@link Section} to current {@link Section}, and make it the current {@link Section}. - * @param name - * @return - */ - public SectionBuilder withSection(String name) { - if(!checkNamePattern(name)) { - throw invalidNamePatternException(name); - } - if(!checkUniqueSectionName(name)) { - throw invalidNameUnicityException(Section.class, name); - } - Section section = new Section(name); - element.addSection(section); - element = section; - - return this; - } - - /** - * Add a {@link Page} to current {@link Section} and make it the current {@link Page}. - * @param name - * @return - * @see #getPage() - */ - public PageBuilder withPage(String name) { - return PageBuilder.createPage(this, name); - } - - /** - * Add a {@link Page} to current {@link Section} and make it the current {@link Page}. - * @param name - * @return - * @see #getPage() - */ - public PageBuilder withPage(String name, Class uiFactoryClass) { - return PageBuilder.createPage(this, name, uiFactoryClass); - } - - /** - * Check section name is unique. - * @param name - * @return - */ - private boolean checkUniqueSectionName(String name) { - return (QuestionnaireFinder.getInstance(questionnaire).findSection(name) == null); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireFinder; +import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; + +/** + * {@link Section} builder, given a {@link Questionnaire}. + * @author cag-ymarcon + * + */ +public class SectionBuilder extends AbstractQuestionnaireElementBuilder
{ + + /** + * Constructor using the {@link QuestionnaireBuilder} to get the {@link Questionnaire} it is applied to. + * @param parent + * @param name + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + private SectionBuilder(QuestionnaireBuilder parent, String name) { + super(parent.getQuestionnaire()); + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + if(!checkUniqueSectionName(name)) { + throw invalidNameUnicityException(Section.class, name); + } + this.element = new Section(name); + this.questionnaire.addSection(element); + } + + /** + * Constructor. + * @param questionnaire + * @param section + */ + private SectionBuilder(Questionnaire questionnaire, Section section) { + super(questionnaire); + this.element = section; + } + + /** + * Create a section in the {@link Questionnaire}. + * @param parent + * @param name + * @return + * @throws IllegalArgumentException if name does not respect questionnaire element naming pattern. + */ + public static SectionBuilder createSection(QuestionnaireBuilder parent, String name) { + return new SectionBuilder(parent, name); + } + + public static SectionBuilder inSection(Questionnaire questionnaire, Section section) { + return new SectionBuilder(questionnaire, section); + } + + /** + * Add a {@link Section} to current {@link Section}, and make it the current {@link Section}. + * @param name + * @return + */ + public SectionBuilder withSection(String name) { + if(!checkNamePattern(name)) { + throw invalidNamePatternException(name); + } + if(!checkUniqueSectionName(name)) { + throw invalidNameUnicityException(Section.class, name); + } + Section section = new Section(name); + element.addSection(section); + element = section; + + return this; + } + + /** + * Add a {@link Page} to current {@link Section} and make it the current {@link Page}. + * @param name + * @return + * @see #getPage() + */ + public PageBuilder withPage(String name) { + return PageBuilder.createPage(this, name); + } + + /** + * Add a {@link Page} to current {@link Section} and make it the current {@link Page}. + * @param name + * @return + * @see #getPage() + */ + public PageBuilder withPage(String name, Class uiFactoryClass) { + return PageBuilder.createPage(this, name, uiFactoryClass); + } + + /** + * Check section name is unique. + * @param name + * @return + */ + private boolean checkUniqueSectionName(String name) { + return (QuestionnaireFinder.getInstance(questionnaire).findSection(name) == null); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/OutputStreamPropertyKeyWriterImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/OutputStreamPropertyKeyWriterImpl.java index acadfee47..ed364399b 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/OutputStreamPropertyKeyWriterImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/OutputStreamPropertyKeyWriterImpl.java @@ -1,48 +1,57 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl; - -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; - -/** - * Write the questionnaire properties into a output stream. - * @author Yannick Marcon - * - */ -public class OutputStreamPropertyKeyWriterImpl implements IPropertyKeyWriter { - - private Properties language; - - private PrintWriter printWriter; - - public OutputStreamPropertyKeyWriterImpl(Properties language, OutputStream outputStream) { - this.language = language; - this.printWriter = new PrintWriter(outputStream); - } - - public void endBloc() { - printWriter.println(); - } - - public void write(String key, String value) { - printWriter.println(key + "=" + value); - } - - public void end() { - printWriter.flush(); - printWriter.close(); - } - - public Properties getReference() { - return language; - } - - public void writeComment(String... comments) { - for (String comment : comments) { - printWriter.println("## " + comment); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl; + +import java.io.OutputStream; +import java.io.PrintWriter; +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; + +/** + * Write the questionnaire properties into a output stream. + * @author Yannick Marcon + * + */ +public class OutputStreamPropertyKeyWriterImpl implements IPropertyKeyWriter { + + private Properties language; + + private PrintWriter printWriter; + + public OutputStreamPropertyKeyWriterImpl(Properties language, OutputStream outputStream) { + this.language = language; + this.printWriter = new PrintWriter(outputStream); + } + + public void endBloc() { + printWriter.println(); + } + + public void write(String key, String value) { + printWriter.println(key + "=" + value); + } + + public void end() { + printWriter.flush(); + printWriter.close(); + } + + public Properties getReference() { + return language; + } + + public void writeComment(String... comments) { + for (String comment : comments) { + printWriter.println("## " + comment); + } + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/PropertiesPropertyKeyWriterImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/PropertiesPropertyKeyWriterImpl.java index d14af49fd..1b5e38fd1 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/PropertiesPropertyKeyWriterImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/builder/impl/PropertiesPropertyKeyWriterImpl.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl; - -import java.util.Properties; - -import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; - -/** - * Write the questionnaire properties into a properties object. - * @author Yannick Marcon - * - */ -public class PropertiesPropertyKeyWriterImpl implements IPropertyKeyWriter { - - private Properties language; - - private Properties properties = new Properties(); - - /** - * Constructor without properties reference. - */ - public PropertiesPropertyKeyWriterImpl() { - } - - /** - * Constructor with a property reference. - * @param language - */ - public PropertiesPropertyKeyWriterImpl(Properties language) { - this.language = language; - } - - /** - * Get the questionnaire properties object. - * @return - */ - public Properties getProperties() { - return properties; - } - - public void endBloc() { - } - - public void write(String key, String value) { - properties.put(key, value); - } - - public void end() { - } - - public Properties getReference() { - return language; - } - - public void writeComment(String... comments) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.impl; + +import java.util.Properties; + +import org.obiba.onyx.quartz.core.engine.questionnaire.util.builder.IPropertyKeyWriter; + +/** + * Write the questionnaire properties into a properties object. + * @author Yannick Marcon + * + */ +public class PropertiesPropertyKeyWriterImpl implements IPropertyKeyWriter { + + private Properties language; + + private Properties properties = new Properties(); + + /** + * Constructor without properties reference. + */ + public PropertiesPropertyKeyWriterImpl() { + } + + /** + * Constructor with a property reference. + * @param language + */ + public PropertiesPropertyKeyWriterImpl(Properties language) { + this.language = language; + } + + /** + * Get the questionnaire properties object. + * @return + */ + public Properties getProperties() { + return properties; + } + + public void endBloc() { + } + + public void write(String key, String value) { + properties.put(key, value); + } + + public void end() { + } + + public Properties getReference() { + return language; + } + + public void writeComment(String... comments) { + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/AbstractFinderVisitor.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/AbstractFinderVisitor.java index 72f24c282..19ef9cc3a 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/AbstractFinderVisitor.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/AbstractFinderVisitor.java @@ -1,101 +1,110 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import java.util.ArrayList; -import java.util.List; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.IWalkerVisitor; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireWalker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Base class for defining a questionnaire element finder visitor. - * @author Yannick Marcon - * @see QuestionnaireFinder - * @see QuestionnaireWalker - * @param questionnaire elements are search by their name - */ -public abstract class AbstractFinderVisitor implements IWalkerVisitor { - - @SuppressWarnings("unused") - private final Logger log = LoggerFactory.getLogger(getClass()); - - /** - * Localization name. - */ - private String name; - - /** - * Do we stop when first element is found ? - */ - private boolean stopAtFirst; - - /** - * The list of found elements. - */ - private List elements; - - /** - * Constructor, stopping at first element by default. - * @param name - */ - protected AbstractFinderVisitor(String name) { - this(name, true); - } - - /** - * Constructor. - * @param name - * @param stopAtFirst - */ - protected AbstractFinderVisitor(String name, boolean stopAtFirst) { - this.name = name; - this.stopAtFirst = stopAtFirst; - this.elements = new ArrayList(); - } - - /** - * The name of the questionnaire element that was looked for. - * @return - */ - public String getName() { - return name; - } - - /** - * The first element of the found list. - * @return null if none - */ - public T getFirstElement() { - if(elements.size() > 0) return elements.get(0); - else - return null; - } - - /** - * The list of found elements. - * @return - */ - public List getElements() { - return elements; - } - - /** - * Visit the element, deciding if it answer the search criteria. - * @param element - * @return true if search criteria is satisfied - */ - protected boolean visitElement(T element) { - if(element.getName().equals(name)) { - elements.add(element); - return true; - } - return false; - } - - public boolean visiteMore() { - return !(stopAtFirst && elements.size() > 0); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import java.util.ArrayList; +import java.util.List; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.IWalkerVisitor; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireWalker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for defining a questionnaire element finder visitor. + * @author Yannick Marcon + * @see QuestionnaireFinder + * @see QuestionnaireWalker + * @param questionnaire elements are search by their name + */ +public abstract class AbstractFinderVisitor implements IWalkerVisitor { + + @SuppressWarnings("unused") + private final Logger log = LoggerFactory.getLogger(getClass()); + + /** + * Localization name. + */ + private String name; + + /** + * Do we stop when first element is found ? + */ + private boolean stopAtFirst; + + /** + * The list of found elements. + */ + private List elements; + + /** + * Constructor, stopping at first element by default. + * @param name + */ + protected AbstractFinderVisitor(String name) { + this(name, true); + } + + /** + * Constructor. + * @param name + * @param stopAtFirst + */ + protected AbstractFinderVisitor(String name, boolean stopAtFirst) { + this.name = name; + this.stopAtFirst = stopAtFirst; + this.elements = new ArrayList(); + } + + /** + * The name of the questionnaire element that was looked for. + * @return + */ + public String getName() { + return name; + } + + /** + * The first element of the found list. + * @return null if none + */ + public T getFirstElement() { + if(elements.size() > 0) return elements.get(0); + else + return null; + } + + /** + * The list of found elements. + * @return + */ + public List getElements() { + return elements; + } + + /** + * Visit the element, deciding if it answer the search criteria. + * @param element + * @return true if search criteria is satisfied + */ + protected boolean visitElement(T element) { + if(element.getName().equals(name)) { + elements.add(element); + return true; + } + return false; + } + + public boolean visiteMore() { + return !(stopAtFirst && elements.size() > 0); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/CategoryFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/CategoryFinder.java index 42d21b07b..f350fc29b 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/CategoryFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/CategoryFinder.java @@ -1,107 +1,116 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Class for finding {@link Category}. - * @author Yannick Marcon - * - */ -public class CategoryFinder extends AbstractFinderVisitor { - - /** - * A map for storing the {@link Category} / {@link Question} association. - */ - Map> questionCategories = new HashMap>(); - - /** - * Constructor, for searching all categories with their question association. - * @see #getQuestionCategories() - * @see #getQuestionSharedCategories() - */ - public CategoryFinder() { - super(null, false); - } - - /** - * Constructor, for searching first {@link Category} with given name. - * @param name - */ - public CategoryFinder(String name) { - super(name); - } - - /** - * Constructor, for searching {@link Category} with given name. - * @param name - * @param stopAtFirst - */ - public CategoryFinder(String name, boolean stopAtFirst) { - super(name, stopAtFirst); - } - - /** - * Get the {@link Category} / {@link Question} association. - * @return - */ - public Map> getQuestionCategories() { - return questionCategories; - } - - /** - * Look for shared {@link Category}: categories refered by more than one question. - * @return - */ - public List getQuestionSharedCategories() { - List shared = new ArrayList(); - for (Entry> entry : questionCategories.entrySet()) { - if (entry.getValue().size() > 1) { - shared.add(entry.getKey()); - } - } - return shared; - } - - public void visit(Questionnaire questionnaire) { - } - - public void visit(Section section) { - } - - public void visit(Page page) { - } - - public void visit(Question question) { - } - - public void visit(QuestionCategory questionCategory) { - if(getName() == null || visitElement(questionCategory.getCategory())) { - if(!questionCategories.containsKey(questionCategory.getCategory())) { - ArrayList questions = new ArrayList(); - questions.add(questionCategory.getQuestion()); - questionCategories.put(questionCategory.getCategory(), questions); - } else { - questionCategories.get(questionCategory.getCategory()).add(questionCategory.getQuestion()); - } - } - } - - public void visit(Category category) { - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Class for finding {@link Category}. + * @author Yannick Marcon + * + */ +public class CategoryFinder extends AbstractFinderVisitor { + + /** + * A map for storing the {@link Category} / {@link Question} association. + */ + Map> questionCategories = new HashMap>(); + + /** + * Constructor, for searching all categories with their question association. + * @see #getQuestionCategories() + * @see #getQuestionSharedCategories() + */ + public CategoryFinder() { + super(null, false); + } + + /** + * Constructor, for searching first {@link Category} with given name. + * @param name + */ + public CategoryFinder(String name) { + super(name); + } + + /** + * Constructor, for searching {@link Category} with given name. + * @param name + * @param stopAtFirst + */ + public CategoryFinder(String name, boolean stopAtFirst) { + super(name, stopAtFirst); + } + + /** + * Get the {@link Category} / {@link Question} association. + * @return + */ + public Map> getQuestionCategories() { + return questionCategories; + } + + /** + * Look for shared {@link Category}: categories refered by more than one question. + * @return + */ + public List getQuestionSharedCategories() { + List shared = new ArrayList(); + for (Entry> entry : questionCategories.entrySet()) { + if (entry.getValue().size() > 1) { + shared.add(entry.getKey()); + } + } + return shared; + } + + public void visit(Questionnaire questionnaire) { + } + + public void visit(Section section) { + } + + public void visit(Page page) { + } + + public void visit(Question question) { + } + + public void visit(QuestionCategory questionCategory) { + if(getName() == null || visitElement(questionCategory.getCategory())) { + if(!questionCategories.containsKey(questionCategory.getCategory())) { + ArrayList questions = new ArrayList(); + questions.add(questionCategory.getQuestion()); + questionCategories.put(questionCategory.getCategory(), questions); + } else { + questionCategories.get(questionCategory.getCategory()).add(questionCategory.getQuestion()); + } + } + } + + public void visit(Category category) { + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/OpenAnswerDefinitionFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/OpenAnswerDefinitionFinder.java index d6f565ab1..470954622 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/OpenAnswerDefinitionFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/OpenAnswerDefinitionFinder.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Class for finding {@link OpenAnswerDefinition}. - * @author Yannick Marcon - * - */ -public class OpenAnswerDefinitionFinder extends AbstractFinderVisitor { - - /** - * Constructor, for searching first {@link OpenAnswerDefinition} with given name. - * @param name - */ - public OpenAnswerDefinitionFinder(String name) { - super(name); - } - - /** - * Constructor, for searching {@link OpenAnswerDefinition} with given name. - * @param name - * @param stopAtFirst - */ - public OpenAnswerDefinitionFinder(String name, boolean stopAtFirst) { - super(name, stopAtFirst); - } - - public void visit(Questionnaire questionnaire) { - } - - public void visit(Section section) { - } - - public void visit(Page page) { - } - - public void visit(Question question) { - } - - public void visit(QuestionCategory questionCategory) { - } - - public void visit(Category category) { - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - visitElement(openAnswerDefinition); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Class for finding {@link OpenAnswerDefinition}. + * @author Yannick Marcon + * + */ +public class OpenAnswerDefinitionFinder extends AbstractFinderVisitor { + + /** + * Constructor, for searching first {@link OpenAnswerDefinition} with given name. + * @param name + */ + public OpenAnswerDefinitionFinder(String name) { + super(name); + } + + /** + * Constructor, for searching {@link OpenAnswerDefinition} with given name. + * @param name + * @param stopAtFirst + */ + public OpenAnswerDefinitionFinder(String name, boolean stopAtFirst) { + super(name, stopAtFirst); + } + + public void visit(Questionnaire questionnaire) { + } + + public void visit(Section section) { + } + + public void visit(Page page) { + } + + public void visit(Question question) { + } + + public void visit(QuestionCategory questionCategory) { + } + + public void visit(Category category) { + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + visitElement(openAnswerDefinition); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/PageFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/PageFinder.java index 978d6fe94..87a205953 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/PageFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/PageFinder.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Class for finding {@link Page}. - * @author cag-ymarcon - * - */ -public class PageFinder extends AbstractFinderVisitor { - - /** - * Constructor, for searching first {@link Page} with given name. - * @param name - */ - public PageFinder(String name) { - super(name); - } - - /** - * Constructor, for searching {@link Page} with given name. - * @param name - * @param stopAtFirst - */ - public PageFinder(String name, boolean stopAtFirst) { - super(name, stopAtFirst); - } - - public void visit(Questionnaire questionnaire) { - } - - public void visit(Section section) { - } - - public void visit(Page page) { - visitElement(page); - } - - public void visit(Question question) { - } - - public void visit(QuestionCategory questionCategory) { - } - - public void visit(Category category) { - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Class for finding {@link Page}. + * @author cag-ymarcon + * + */ +public class PageFinder extends AbstractFinderVisitor { + + /** + * Constructor, for searching first {@link Page} with given name. + * @param name + */ + public PageFinder(String name) { + super(name); + } + + /** + * Constructor, for searching {@link Page} with given name. + * @param name + * @param stopAtFirst + */ + public PageFinder(String name, boolean stopAtFirst) { + super(name, stopAtFirst); + } + + public void visit(Questionnaire questionnaire) { + } + + public void visit(Section section) { + } + + public void visit(Page page) { + visitElement(page); + } + + public void visit(Question question) { + } + + public void visit(QuestionCategory questionCategory) { + } + + public void visit(Category category) { + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/QuestionFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/QuestionFinder.java index 5fad537d7..7482a6cf6 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/QuestionFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/QuestionFinder.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Class for finding {@link Question}. - * @author Yannick Marcon - * - */ -public class QuestionFinder extends AbstractFinderVisitor { - - /** - * Constructor, for searching first {@link Question} with given name. - * @param name - */ - public QuestionFinder(String name) { - super(name); - } - - /** - * Constructor, for searching {@link Question} with given name. - * @param name - * @param stopAtFirst - */ - public QuestionFinder(String name, boolean stopAtFirst) { - super(name, stopAtFirst); - } - - public void visit(Questionnaire questionnaire) { - } - - public void visit(Section section) { - } - - public void visit(Page page) { - } - - public void visit(Question question) { - visitElement(question); - } - - public void visit(QuestionCategory questionCategory) { - } - - public void visit(Category category) { - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Class for finding {@link Question}. + * @author Yannick Marcon + * + */ +public class QuestionFinder extends AbstractFinderVisitor { + + /** + * Constructor, for searching first {@link Question} with given name. + * @param name + */ + public QuestionFinder(String name) { + super(name); + } + + /** + * Constructor, for searching {@link Question} with given name. + * @param name + * @param stopAtFirst + */ + public QuestionFinder(String name, boolean stopAtFirst) { + super(name, stopAtFirst); + } + + public void visit(Questionnaire questionnaire) { + } + + public void visit(Section section) { + } + + public void visit(Page page) { + } + + public void visit(Question question) { + visitElement(question); + } + + public void visit(QuestionCategory questionCategory) { + } + + public void visit(Category category) { + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/SectionFinder.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/SectionFinder.java index 719210b41..fd57ef67a 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/SectionFinder.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/finder/SectionFinder.java @@ -1,57 +1,66 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; - -/** - * Class for finding {@link Section} - * @author cag-ymarcon - * - */ -public class SectionFinder extends AbstractFinderVisitor
{ - - /** - * Constructor, for searching first {@link Section} with given name. - * @param name - */ - public SectionFinder(String name) { - super(name); - } - - /** - * Constructor, for searching {@link Section} with given name. - * @param name - * @param stopAtFirst - */ - public SectionFinder(String name, boolean stopAtFirst) { - super(name, stopAtFirst); - } - - public void visit(Questionnaire questionnaire) { - } - - public void visit(Section section) { - visitElement(section); - } - - public void visit(Page page) { - } - - public void visit(Question question) { - } - - public void visit(QuestionCategory questionCategory) { - } - - public void visit(Category category) { - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.finder; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; + +/** + * Class for finding {@link Section} + * @author cag-ymarcon + * + */ +public class SectionFinder extends AbstractFinderVisitor
{ + + /** + * Constructor, for searching first {@link Section} with given name. + * @param name + */ + public SectionFinder(String name) { + super(name); + } + + /** + * Constructor, for searching {@link Section} with given name. + * @param name + * @param stopAtFirst + */ + public SectionFinder(String name, boolean stopAtFirst) { + super(name, stopAtFirst); + } + + public void visit(Questionnaire questionnaire) { + } + + public void visit(Section section) { + visitElement(section); + } + + public void visit(Page page) { + } + + public void visit(Question question) { + } + + public void visit(QuestionCategory questionCategory) { + } + + public void visit(Category category) { + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/IPropertyKeyProvider.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/IPropertyKeyProvider.java index db5124e66..b2e177237 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/IPropertyKeyProvider.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/IPropertyKeyProvider.java @@ -1,30 +1,39 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization; - -import java.util.List; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; - -/** - * Provides/ckecks the property localization key for a {@link ILocalizable} questionnaire element. - * @author Yannick Marcon - * - */ -public interface IPropertyKeyProvider { - - /** - * Get the property localization key. - * @param localizable - * @param property - * @return - * @throws IllegalArgumentException if given property is not associated to the localizable. - */ - public String getPropertyKey(ILocalizable localizable, String property); - - /** - * Get the property keys associated to given localizable. - * @param localizable - * @return - */ - public List getProperties(ILocalizable localizable); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization; + +import java.util.List; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; + +/** + * Provides/ckecks the property localization key for a {@link ILocalizable} questionnaire element. + * @author Yannick Marcon + * + */ +public interface IPropertyKeyProvider { + + /** + * Get the property localization key. + * @param localizable + * @param property + * @return + * @throws IllegalArgumentException if given property is not associated to the localizable. + */ + public String getPropertyKey(ILocalizable localizable, String property); + + /** + * Get the property keys associated to given localizable. + * @param localizable + * @return + */ + public List getProperties(ILocalizable localizable); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/impl/DefaultPropertyKeyProviderImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/impl/DefaultPropertyKeyProviderImpl.java index a06e07882..db5dab19e 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/impl/DefaultPropertyKeyProviderImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/impl/DefaultPropertyKeyProviderImpl.java @@ -1,176 +1,185 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.onyx.util.data.Data; - -public class DefaultPropertyKeyProviderImpl implements IPropertyKeyProvider, IVisitor { - - // - // Questionnaire element properties, with their default values. - // - private List questionnaireProperties = Arrays.asList("label", "description", "labelNext", "imageNext", "labelPrevious", "imagePrevious", "labelStart", "labelFinish", "labelInterrupt", "labelResume", "labelCancel"); - - private List sectionProperties = Arrays.asList("label"); - - private List pageProperties = Arrays.asList("label"); - - private List questionProperties = Arrays.asList("label", "instructions", "caption", "help", "image"); - - private List categoryProperties = Arrays.asList("label", "image"); - - private List openAnswerDefinitionProperties = new ArrayList(Arrays.asList("label", "unitLabel")); - - /** - * The property requested for. - */ - private String property; - - /** - * The properties for the visited localizable. - */ - private List properties; - - public List getProperties(ILocalizable localizable) { - this.property = null; - localizable.accept(this); - return properties; - } - - public String getPropertyKey(ILocalizable localizable, String property) { - this.property = property; - localizable.accept(this); - return localizable.getClass().getSimpleName() + "." + localizable.getName() + "." + property; - } - - // - // Questionnaire element properties setters and getters. - // - public void setQuestionnaireProperties(List questionnaireProperties) { - this.questionnaireProperties = questionnaireProperties; - } - - public void setSectionProperties(List sectionProperties) { - this.sectionProperties = sectionProperties; - } - - public void setPageProperties(List pageProperties) { - this.pageProperties = pageProperties; - } - - public void setQuestionProperties(List questionProperties) { - this.questionProperties = questionProperties; - } - - public void setCategoryProperties(List categoryProperties) { - this.categoryProperties = categoryProperties; - } - - public void setOpenAnswerDefinitionProperties(List openAnswerDefinitionProperties) { - this.openAnswerDefinitionProperties = openAnswerDefinitionProperties; - } - - protected List getQuestionnaireProperties() { - return questionnaireProperties; - } - - protected List getSectionProperties() { - return sectionProperties; - } - - protected List getPageProperties() { - return pageProperties; - } - - protected List getQuestionProperties() { - return questionProperties; - } - - protected List getCategoryProperties() { - return categoryProperties; - } - - protected List getOpenAnswerDefinitionProperties() { - return openAnswerDefinitionProperties; - } - - // - // visitor methods - // - public void visit(Questionnaire questionnaire) { - properties = getQuestionnaireProperties(); - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(questionnaire); - } - } - - public void visit(Section section) { - properties = getSectionProperties(); - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(section); - } - } - - public void visit(Page page) { - properties = getPageProperties(); - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(page); - } - } - - public void visit(Question question) { - properties = getQuestionProperties(); - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(question); - } - } - - public void visit(QuestionCategory questionCategory) { - visit(questionCategory.getCategory()); - } - - public void visit(Category category) { - properties = getCategoryProperties(); - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(category); - } - } - - public void visit(OpenAnswerDefinition openAnswerDefinition) { - properties = new ArrayList(getOpenAnswerDefinitionProperties()); - for(Data value : openAnswerDefinition.getDefaultValues()) { - properties.add(value.getValueAsString()); - } - - if(property != null && !properties.contains(property)) { - throw invalidPropertyException(openAnswerDefinition); - } - } - - /** - * Exception if a requested property is not part of questionnaire element allowed properties. - * @param localizable - * @return - */ - private IllegalArgumentException invalidPropertyException(ILocalizable localizable) { - return new IllegalArgumentException("Invalid property for class " + localizable.getClass().getName() + ": " + property); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.IVisitor; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Section; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.onyx.util.data.Data; + +public class DefaultPropertyKeyProviderImpl implements IPropertyKeyProvider, IVisitor { + + // + // Questionnaire element properties, with their default values. + // + private List questionnaireProperties = Arrays.asList("label", "description", "labelNext", "imageNext", "labelPrevious", "imagePrevious", "labelStart", "labelFinish", "labelInterrupt", "labelResume", "labelCancel"); + + private List sectionProperties = Arrays.asList("label"); + + private List pageProperties = Arrays.asList("label"); + + private List questionProperties = Arrays.asList("label", "instructions", "caption", "help", "image"); + + private List categoryProperties = Arrays.asList("label", "image"); + + private List openAnswerDefinitionProperties = new ArrayList(Arrays.asList("label", "unitLabel")); + + /** + * The property requested for. + */ + private String property; + + /** + * The properties for the visited localizable. + */ + private List properties; + + public List getProperties(ILocalizable localizable) { + this.property = null; + localizable.accept(this); + return properties; + } + + public String getPropertyKey(ILocalizable localizable, String property) { + this.property = property; + localizable.accept(this); + return localizable.getClass().getSimpleName() + "." + localizable.getName() + "." + property; + } + + // + // Questionnaire element properties setters and getters. + // + public void setQuestionnaireProperties(List questionnaireProperties) { + this.questionnaireProperties = questionnaireProperties; + } + + public void setSectionProperties(List sectionProperties) { + this.sectionProperties = sectionProperties; + } + + public void setPageProperties(List pageProperties) { + this.pageProperties = pageProperties; + } + + public void setQuestionProperties(List questionProperties) { + this.questionProperties = questionProperties; + } + + public void setCategoryProperties(List categoryProperties) { + this.categoryProperties = categoryProperties; + } + + public void setOpenAnswerDefinitionProperties(List openAnswerDefinitionProperties) { + this.openAnswerDefinitionProperties = openAnswerDefinitionProperties; + } + + protected List getQuestionnaireProperties() { + return questionnaireProperties; + } + + protected List getSectionProperties() { + return sectionProperties; + } + + protected List getPageProperties() { + return pageProperties; + } + + protected List getQuestionProperties() { + return questionProperties; + } + + protected List getCategoryProperties() { + return categoryProperties; + } + + protected List getOpenAnswerDefinitionProperties() { + return openAnswerDefinitionProperties; + } + + // + // visitor methods + // + public void visit(Questionnaire questionnaire) { + properties = getQuestionnaireProperties(); + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(questionnaire); + } + } + + public void visit(Section section) { + properties = getSectionProperties(); + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(section); + } + } + + public void visit(Page page) { + properties = getPageProperties(); + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(page); + } + } + + public void visit(Question question) { + properties = getQuestionProperties(); + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(question); + } + } + + public void visit(QuestionCategory questionCategory) { + visit(questionCategory.getCategory()); + } + + public void visit(Category category) { + properties = getCategoryProperties(); + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(category); + } + } + + public void visit(OpenAnswerDefinition openAnswerDefinition) { + properties = new ArrayList(getOpenAnswerDefinitionProperties()); + for(Data value : openAnswerDefinition.getDefaultValues()) { + properties.add(value.getValueAsString()); + } + + if(property != null && !properties.contains(property)) { + throw invalidPropertyException(openAnswerDefinition); + } + } + + /** + * Exception if a requested property is not part of questionnaire element allowed properties. + * @param localizable + * @return + */ + private IllegalArgumentException invalidPropertyException(ILocalizable localizable) { + return new IllegalArgumentException("Invalid property for class " + localizable.getClass().getName() + ": " + property); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationService.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationService.java index 9cd94ab0a..1c2f79350 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationService.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationService.java @@ -1,39 +1,48 @@ -package org.obiba.onyx.quartz.core.service; - -import java.util.Locale; - -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; - -public interface ActiveQuestionnaireAdministrationService { - - public Page getCurrentPage(); - - public Page getStartPage(); - - public Page getPreviousPage(); - - public Page getNextPage(); - - public Locale getLanguage(); - - public Questionnaire getQuestionnaire(); - - //public QuestionnaireParticipant getQuestionnaireParticipant(); - - public QuestionAnswer findQuestionAnswer(Question question); - - public QuestionAnswer answerQuestion(Question question, CategoryAnswer categoryAnswer); - - public void setQuestionnaire(Questionnaire questionnaire); - - public QuestionnaireParticipant start(Participant participant, Locale language); - - public void setDefaultLanguage(Locale language); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service; + +import java.util.Locale; + +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; + +public interface ActiveQuestionnaireAdministrationService { + + public Page getCurrentPage(); + + public Page getStartPage(); + + public Page getPreviousPage(); + + public Page getNextPage(); + + public Locale getLanguage(); + + public Questionnaire getQuestionnaire(); + + //public QuestionnaireParticipant getQuestionnaireParticipant(); + + public QuestionAnswer findQuestionAnswer(Question question); + + public QuestionAnswer answerQuestion(Question question, CategoryAnswer categoryAnswer); + + public void setQuestionnaire(Questionnaire questionnaire); + + public QuestionnaireParticipant start(Participant participant, Locale language); + + public void setDefaultLanguage(Locale language); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/INavigationStrategy.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/INavigationStrategy.java index 6652b103a..9dbb32384 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/INavigationStrategy.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/INavigationStrategy.java @@ -1,53 +1,62 @@ -package org.obiba.onyx.quartz.core.service; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; - -/** - * Interface for questionnaire navigation strategies. - * - * @author cag-dspathis - * - */ -public interface INavigationStrategy { - /** - * Returns the questionnaire's start page. - * - * @param service service that may be used by implementors to determine the start page (e.g., if the start page - * depends on whether certain questions have already been answered, this service may be used to check those questions) - * @return start page - */ - public Page getPageOnStart(ActiveQuestionnaireAdministrationService service); - - /** - * Returns the questionnaire page that should be displayed when the "next" event occurs (i.e., when the user navigates - * forwards). - * - * @param service service that may be used by implementors to determine the next page - * @param currentPage currently displayed page - * @return next page - */ - public Page getPageOnNext(ActiveQuestionnaireAdministrationService service, Page currentPage); - - /** - * Returns the questionnaire page that should be displayed when the "previous" event occurs (i.e., when the user - * navigates backwards). - * - * Note: When the user navigates backwards, the pages displayed should follow the path that was originally taken. For - * example, if the user went from page 1, to 2, to 4, the path back should be 4, to 2, to 1. Implementors must ensure - * that this method behaves accordingly. - * - * @param service service that may be used by implementors to determine the previous page - * @param currentPage currently displayed page - * @return previous page - */ - public Page getPageOnPrevious(ActiveQuestionnaireAdministrationService service, Page currentPage); - - /** - * Returns the questionnaire page that should be displayed when the questionnaire stage is resumed (i.e., after having - * been interrupted). - * - * @param service service that may be used by implementors to determine the page on which to resume - * @return page on which to resume - */ - public Page getPageOnResume(ActiveQuestionnaireAdministrationService service); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; + +/** + * Interface for questionnaire navigation strategies. + * + * @author cag-dspathis + * + */ +public interface INavigationStrategy { + /** + * Returns the questionnaire's start page. + * + * @param service service that may be used by implementors to determine the start page (e.g., if the start page + * depends on whether certain questions have already been answered, this service may be used to check those questions) + * @return start page + */ + public Page getPageOnStart(ActiveQuestionnaireAdministrationService service); + + /** + * Returns the questionnaire page that should be displayed when the "next" event occurs (i.e., when the user navigates + * forwards). + * + * @param service service that may be used by implementors to determine the next page + * @param currentPage currently displayed page + * @return next page + */ + public Page getPageOnNext(ActiveQuestionnaireAdministrationService service, Page currentPage); + + /** + * Returns the questionnaire page that should be displayed when the "previous" event occurs (i.e., when the user + * navigates backwards). + * + * Note: When the user navigates backwards, the pages displayed should follow the path that was originally taken. For + * example, if the user went from page 1, to 2, to 4, the path back should be 4, to 2, to 1. Implementors must ensure + * that this method behaves accordingly. + * + * @param service service that may be used by implementors to determine the previous page + * @param currentPage currently displayed page + * @return previous page + */ + public Page getPageOnPrevious(ActiveQuestionnaireAdministrationService service, Page currentPage); + + /** + * Returns the questionnaire page that should be displayed when the questionnaire stage is resumed (i.e., after having + * been interrupted). + * + * @param service service that may be used by implementors to determine the page on which to resume + * @return page on which to resume + */ + public Page getPageOnResume(ActiveQuestionnaireAdministrationService service); +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantService.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantService.java index 34ec2e501..f7276b8a5 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantService.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantService.java @@ -1,23 +1,32 @@ -package org.obiba.onyx.quartz.core.service; - -import java.io.Serializable; - -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; - -public interface QuestionnaireParticipantService { - - /** - * Get the last questionnaire for participant and questionnaire name. - * @param participant - * @param questionnaireName - * @return - */ - public QuestionnaireParticipant getLastQuestionnaireParticipant(Participant participant, String questionnaireName); - - /** - * Delete specified questionnaireParticipany - * @param questionnaireParticipantId - */ - public void deleteQuestionnaireParticipant(Serializable questionnaireParticipantId); -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service; + +import java.io.Serializable; + +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; + +public interface QuestionnaireParticipantService { + + /** + * Get the last questionnaire for participant and questionnaire name. + * @param participant + * @param questionnaireName + * @return + */ + public QuestionnaireParticipant getLastQuestionnaireParticipant(Participant participant, String questionnaireName); + + /** + * Delete specified questionnaireParticipany + * @param questionnaireParticipantId + */ + public void deleteQuestionnaireParticipant(Serializable questionnaireParticipantId); +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultActiveQuestionnaireAdministrationServiceImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultActiveQuestionnaireAdministrationServiceImpl.java index d76f238c6..73f793b10 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultActiveQuestionnaireAdministrationServiceImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultActiveQuestionnaireAdministrationServiceImpl.java @@ -1,96 +1,105 @@ -package org.obiba.onyx.quartz.core.service.impl; - -import java.util.Locale; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.quartz.core.service.INavigationStrategy; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class DefaultActiveQuestionnaireAdministrationServiceImpl extends PersistenceManagerAwareService implements ActiveQuestionnaireAdministrationService { - - private Questionnaire currentQuestionnaire; - - private QuestionnaireParticipant currentQuestionnaireParticipant; - - private Locale defaultLanguage; - - private INavigationStrategy navigationStrategy; - - public Questionnaire getQuestionnaire() { - return currentQuestionnaire; - } - - public void setQuestionnaire(Questionnaire questionnaire) { - this.currentQuestionnaire = questionnaire; - this.currentQuestionnaireParticipant = null; - } - - private QuestionnaireParticipant getQuestionnaireParticipant() { - return (getPersistenceManager().refresh(currentQuestionnaireParticipant)); - } - - public Locale getLanguage() { - if(currentQuestionnaireParticipant == null) return defaultLanguage; - return currentQuestionnaireParticipant.getLocale(); - } - - public void setNavigationStrategy(INavigationStrategy navigationStrategy) { - this.navigationStrategy = navigationStrategy; - } - - public QuestionnaireParticipant start(Participant participant, Locale language) { - - if(currentQuestionnaireParticipant != null) throw new IllegalArgumentException("Invalid questionnaireParticipant for specified questionnaire"); - - QuestionnaireParticipant questionnaireParticipantTemplate = new QuestionnaireParticipant(); - questionnaireParticipantTemplate.setParticipant(participant); - questionnaireParticipantTemplate.setQuestionnaireName(currentQuestionnaire.getName()); - questionnaireParticipantTemplate.setQuestionnaireVersion(currentQuestionnaire.getVersion()); - questionnaireParticipantTemplate.setLocale(language); - - currentQuestionnaireParticipant = getPersistenceManager().save(questionnaireParticipantTemplate); - - return currentQuestionnaireParticipant; - } - - public QuestionAnswer answerQuestion(Question question, CategoryAnswer categoryAnswer) { - // TODO Auto-generated method stub - return null; - } - - public QuestionAnswer findQuestionAnswer(Question question) { - // TODO Auto-generated method stub - return null; - } - - public Page getCurrentPage() { - // TODO Auto-generated method stub - return null; - } - - public Page getStartPage() { - return navigationStrategy.getPageOnStart(this); - } - - public Page getPreviousPage() { - return navigationStrategy.getPageOnPrevious(this, getCurrentPage()); - } - - public Page getNextPage() { - return navigationStrategy.getPageOnNext(this, getCurrentPage()); - } - - public void setDefaultLanguage(Locale language) { - this.defaultLanguage = language; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service.impl; + +import java.util.Locale; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.quartz.core.service.INavigationStrategy; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class DefaultActiveQuestionnaireAdministrationServiceImpl extends PersistenceManagerAwareService implements ActiveQuestionnaireAdministrationService { + + private Questionnaire currentQuestionnaire; + + private QuestionnaireParticipant currentQuestionnaireParticipant; + + private Locale defaultLanguage; + + private INavigationStrategy navigationStrategy; + + public Questionnaire getQuestionnaire() { + return currentQuestionnaire; + } + + public void setQuestionnaire(Questionnaire questionnaire) { + this.currentQuestionnaire = questionnaire; + this.currentQuestionnaireParticipant = null; + } + + private QuestionnaireParticipant getQuestionnaireParticipant() { + return (getPersistenceManager().refresh(currentQuestionnaireParticipant)); + } + + public Locale getLanguage() { + if(currentQuestionnaireParticipant == null) return defaultLanguage; + return currentQuestionnaireParticipant.getLocale(); + } + + public void setNavigationStrategy(INavigationStrategy navigationStrategy) { + this.navigationStrategy = navigationStrategy; + } + + public QuestionnaireParticipant start(Participant participant, Locale language) { + + if(currentQuestionnaireParticipant != null) throw new IllegalArgumentException("Invalid questionnaireParticipant for specified questionnaire"); + + QuestionnaireParticipant questionnaireParticipantTemplate = new QuestionnaireParticipant(); + questionnaireParticipantTemplate.setParticipant(participant); + questionnaireParticipantTemplate.setQuestionnaireName(currentQuestionnaire.getName()); + questionnaireParticipantTemplate.setQuestionnaireVersion(currentQuestionnaire.getVersion()); + questionnaireParticipantTemplate.setLocale(language); + + currentQuestionnaireParticipant = getPersistenceManager().save(questionnaireParticipantTemplate); + + return currentQuestionnaireParticipant; + } + + public QuestionAnswer answerQuestion(Question question, CategoryAnswer categoryAnswer) { + // TODO Auto-generated method stub + return null; + } + + public QuestionAnswer findQuestionAnswer(Question question) { + // TODO Auto-generated method stub + return null; + } + + public Page getCurrentPage() { + // TODO Auto-generated method stub + return null; + } + + public Page getStartPage() { + return navigationStrategy.getPageOnStart(this); + } + + public Page getPreviousPage() { + return navigationStrategy.getPageOnPrevious(this, getCurrentPage()); + } + + public Page getNextPage() { + return navigationStrategy.getPageOnNext(this, getCurrentPage()); + } + + public void setDefaultLanguage(Locale language) { + this.defaultLanguage = language; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultNavigationStrategyImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultNavigationStrategyImpl.java index 2cdc3af08..b787d66f2 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultNavigationStrategyImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultNavigationStrategyImpl.java @@ -1,159 +1,168 @@ -package org.obiba.onyx.quartz.core.service.impl; - -import java.util.List; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.quartz.core.service.INavigationStrategy; - -/** - * Default questionnaire navigation strategy. - * - * @author cag-dspathis - * - */ -public class DefaultNavigationStrategyImpl implements INavigationStrategy { - - /** - * Returns the earliest page of the questionnaire containing at least one (answerable) question that has not been - * answered. - * - * In effect, this method skips over pages with no questions to be answered. - * - * @param service service - * @return start page (first page with unanswered questions) - */ - public Page getPageOnStart(ActiveQuestionnaireAdministrationService service) { - Page startPage = null; - - Questionnaire questionnaire = service.getQuestionnaire(); - - List pages = questionnaire.getPages(); - - for(Page page : pages) { - if(NavigationStrategySupport.hasUnansweredQuestion(service, page)) { - startPage = page; - break; - } - } - - return startPage; - } - - /** - * Returns the earliest page, after the current page, containing at least one (answerable) question that has not been - * answered. - * - * In effect, this method skips over pages with no questions to be answered. - * - * @param service service - * @param currentPage currently displayed page - * @return next page (first page, after current page, with unanswered questions) - */ - public Page getPageOnNext(ActiveQuestionnaireAdministrationService service, Page currentPage) { - Page nextPage = null; - - Questionnaire questionnaire = service.getQuestionnaire(); - - List pages = questionnaire.getPages(); - - int currentPageIndex = pages.indexOf(currentPage); - - for(int i = currentPageIndex + 1; i < pages.size(); i++) { - Page page = pages.get(i); - - if(NavigationStrategySupport.hasUnansweredQuestion(service, page)) { - nextPage = page; - break; - } - } - - return nextPage; - } - - /** - * Returns the page from which the current page was arrived at. - * - * Earlier pages of the questionnaire that were skipped over when the user navigated to the current page (see - * getPageOnNext) will also be skipped over by this method. - * - * @param service service - * @param currentPage currently displayed page - * @return previous page (page displayed before the current page) - */ - public Page getPageOnPrevious(ActiveQuestionnaireAdministrationService service, Page currentPage) { - Page previousPage = null; - - Questionnaire questionnaire = service.getQuestionnaire(); - - List pages = questionnaire.getPages(); - - int startPageIndex = pages.indexOf(getPageOnStart(service)); - int currentPageIndex = pages.indexOf(currentPage); - - for (int i=startPageIndex; igetPageOnNext) if it - * does not. - * - * If there are pages containing questions with inactive answers, then the earliest of those pages is returned - * instead (the idea, being, that those questions need to be revisited first when resuming). - * - * @param service service - * @return - */ - public Page getPageOnResume(ActiveQuestionnaireAdministrationService service) { - Page resumePage = null; - - Questionnaire questionnaire = service.getQuestionnaire(); - - List pages = questionnaire.getPages(); - - int startPageIndex = pages.indexOf(getPageOnStart(service)); - - // Look for first page containing questions with inactive answers. - for (int i=startPageIndex; i=startPageIndex; i--) { - Page page = pages.get(i); - - if (NavigationStrategySupport.hasActiveAnswer(service, page)) { - resumePage = page; - break; - } - } - - if (resumePage != null) { - if (!NavigationStrategySupport.hasUnansweredQuestion(service, resumePage)) { - resumePage = getPageOnNext(service, resumePage); - } - } - } - - return resumePage; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service.impl; + +import java.util.List; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.quartz.core.service.INavigationStrategy; + +/** + * Default questionnaire navigation strategy. + * + * @author cag-dspathis + * + */ +public class DefaultNavigationStrategyImpl implements INavigationStrategy { + + /** + * Returns the earliest page of the questionnaire containing at least one (answerable) question that has not been + * answered. + * + * In effect, this method skips over pages with no questions to be answered. + * + * @param service service + * @return start page (first page with unanswered questions) + */ + public Page getPageOnStart(ActiveQuestionnaireAdministrationService service) { + Page startPage = null; + + Questionnaire questionnaire = service.getQuestionnaire(); + + List pages = questionnaire.getPages(); + + for(Page page : pages) { + if(NavigationStrategySupport.hasUnansweredQuestion(service, page)) { + startPage = page; + break; + } + } + + return startPage; + } + + /** + * Returns the earliest page, after the current page, containing at least one (answerable) question that has not been + * answered. + * + * In effect, this method skips over pages with no questions to be answered. + * + * @param service service + * @param currentPage currently displayed page + * @return next page (first page, after current page, with unanswered questions) + */ + public Page getPageOnNext(ActiveQuestionnaireAdministrationService service, Page currentPage) { + Page nextPage = null; + + Questionnaire questionnaire = service.getQuestionnaire(); + + List pages = questionnaire.getPages(); + + int currentPageIndex = pages.indexOf(currentPage); + + for(int i = currentPageIndex + 1; i < pages.size(); i++) { + Page page = pages.get(i); + + if(NavigationStrategySupport.hasUnansweredQuestion(service, page)) { + nextPage = page; + break; + } + } + + return nextPage; + } + + /** + * Returns the page from which the current page was arrived at. + * + * Earlier pages of the questionnaire that were skipped over when the user navigated to the current page (see + * getPageOnNext) will also be skipped over by this method. + * + * @param service service + * @param currentPage currently displayed page + * @return previous page (page displayed before the current page) + */ + public Page getPageOnPrevious(ActiveQuestionnaireAdministrationService service, Page currentPage) { + Page previousPage = null; + + Questionnaire questionnaire = service.getQuestionnaire(); + + List pages = questionnaire.getPages(); + + int startPageIndex = pages.indexOf(getPageOnStart(service)); + int currentPageIndex = pages.indexOf(currentPage); + + for (int i=startPageIndex; igetPageOnNext) if it + * does not. + * + * If there are pages containing questions with inactive answers, then the earliest of those pages is returned + * instead (the idea, being, that those questions need to be revisited first when resuming). + * + * @param service service + * @return + */ + public Page getPageOnResume(ActiveQuestionnaireAdministrationService service) { + Page resumePage = null; + + Questionnaire questionnaire = service.getQuestionnaire(); + + List pages = questionnaire.getPages(); + + int startPageIndex = pages.indexOf(getPageOnStart(service)); + + // Look for first page containing questions with inactive answers. + for (int i=startPageIndex; i=startPageIndex; i--) { + Page page = pages.get(i); + + if (NavigationStrategySupport.hasActiveAnswer(service, page)) { + resumePage = page; + break; + } + } + + if (resumePage != null) { + if (!NavigationStrategySupport.hasUnansweredQuestion(service, resumePage)) { + resumePage = getPageOnNext(service, resumePage); + } + } + } + + return resumePage; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultQuestionnaireParticipantServiceImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultQuestionnaireParticipantServiceImpl.java index 8d975c67b..2bfb9651a 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultQuestionnaireParticipantServiceImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/DefaultQuestionnaireParticipantServiceImpl.java @@ -1,41 +1,50 @@ -package org.obiba.onyx.quartz.core.service.impl; - -import java.io.Serializable; -import java.util.List; - -import org.obiba.core.service.impl.PersistenceManagerAwareService; -import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; - -public abstract class DefaultQuestionnaireParticipantServiceImpl extends PersistenceManagerAwareService implements QuestionnaireParticipantService { - - public void deleteQuestionnaireParticipant(Serializable questionnaireParticipantId) { - QuestionnaireParticipant questionnaireParticipant = loadQuestionnaireParticipant(questionnaireParticipantId); - - QuestionAnswer questionAnswerTemplate = new QuestionAnswer(); - questionAnswerTemplate.setQuestionnaireParticipant(questionnaireParticipant); - - for(QuestionAnswer questionAnswer : getPersistenceManager().match(questionAnswerTemplate)) { - CategoryAnswer template = new CategoryAnswer(); - template.setQuestionAnswer(questionAnswer); - List categoryAnswerList = getPersistenceManager().match(template); - - for(CategoryAnswer categoryAnswer : categoryAnswerList) { - getPersistenceManager().delete(categoryAnswer); - } - - getPersistenceManager().delete(questionAnswer); - } - - getPersistenceManager().delete(questionnaireParticipant); - } - - public QuestionnaireParticipant loadQuestionnaireParticipant(Serializable questionnaireParticipantId) { - QuestionnaireParticipant questionnaireParticipant = getPersistenceManager().get(QuestionnaireParticipant.class, questionnaireParticipantId); - if(questionnaireParticipant == null) throw new IllegalArgumentException("Invalid quetsionnaire participant id"); - return questionnaireParticipant; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service.impl; + +import java.io.Serializable; +import java.util.List; + +import org.obiba.core.service.impl.PersistenceManagerAwareService; +import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; + +public abstract class DefaultQuestionnaireParticipantServiceImpl extends PersistenceManagerAwareService implements QuestionnaireParticipantService { + + public void deleteQuestionnaireParticipant(Serializable questionnaireParticipantId) { + QuestionnaireParticipant questionnaireParticipant = loadQuestionnaireParticipant(questionnaireParticipantId); + + QuestionAnswer questionAnswerTemplate = new QuestionAnswer(); + questionAnswerTemplate.setQuestionnaireParticipant(questionnaireParticipant); + + for(QuestionAnswer questionAnswer : getPersistenceManager().match(questionAnswerTemplate)) { + CategoryAnswer template = new CategoryAnswer(); + template.setQuestionAnswer(questionAnswer); + List categoryAnswerList = getPersistenceManager().match(template); + + for(CategoryAnswer categoryAnswer : categoryAnswerList) { + getPersistenceManager().delete(categoryAnswer); + } + + getPersistenceManager().delete(questionAnswer); + } + + getPersistenceManager().delete(questionnaireParticipant); + } + + public QuestionnaireParticipant loadQuestionnaireParticipant(Serializable questionnaireParticipantId) { + QuestionnaireParticipant questionnaireParticipant = getPersistenceManager().get(QuestionnaireParticipant.class, questionnaireParticipantId); + if(questionnaireParticipant == null) throw new IllegalArgumentException("Invalid quetsionnaire participant id"); + return questionnaireParticipant; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/NavigationStrategySupport.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/NavigationStrategySupport.java index 00a58dd82..02b4934a7 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/NavigationStrategySupport.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/NavigationStrategySupport.java @@ -1,49 +1,58 @@ -package org.obiba.onyx.quartz.core.service.impl; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; - -/** - * This class provides a set of convenience methods for INavigationStrategy implementors. - * - * @author cag-dspathis - * - */ -public class NavigationStrategySupport { - - /** - * Indicates whether the specified page contains at least one unanswered (and answerable) question. - * - * @param service - * @param page - * @return - */ - public static boolean hasUnansweredQuestion(ActiveQuestionnaireAdministrationService service, Page page) { - // TODO: Implement! - return false; - } - - /** - * Indicates whether the specified page contains at least one question with an active answer. - * - * @param service - * @param page - * @return - */ - public static boolean hasActiveAnswer(ActiveQuestionnaireAdministrationService service, Page page) { - // TODO: Implement! - return false; - } - - /** - * Indicates whether the specified page contains at least one question with a inactive answer. - * - * @param service - * @param page - * @return - */ - public static boolean hasInactiveAnswer(ActiveQuestionnaireAdministrationService service, Page page) { - // TODO: Implement! - return false; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service.impl; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; + +/** + * This class provides a set of convenience methods for INavigationStrategy implementors. + * + * @author cag-dspathis + * + */ +public class NavigationStrategySupport { + + /** + * Indicates whether the specified page contains at least one unanswered (and answerable) question. + * + * @param service + * @param page + * @return + */ + public static boolean hasUnansweredQuestion(ActiveQuestionnaireAdministrationService service, Page page) { + // TODO: Implement! + return false; + } + + /** + * Indicates whether the specified page contains at least one question with an active answer. + * + * @param service + * @param page + * @return + */ + public static boolean hasActiveAnswer(ActiveQuestionnaireAdministrationService service, Page page) { + // TODO: Implement! + return false; + } + + /** + * Indicates whether the specified page contains at least one question with a inactive answer. + * + * @param service + * @param page + * @return + */ + public static boolean hasInactiveAnswer(ActiveQuestionnaireAdministrationService service, Page page) { + // TODO: Implement! + return false; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/hibernate/QuestionnaireParticipantServiceHibernateImpl.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/hibernate/QuestionnaireParticipantServiceHibernateImpl.java index e4239e212..e18b2b509 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/hibernate/QuestionnaireParticipantServiceHibernateImpl.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/service/impl/hibernate/QuestionnaireParticipantServiceHibernateImpl.java @@ -1,33 +1,42 @@ -package org.obiba.onyx.quartz.core.service.impl.hibernate; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.obiba.core.service.SortingClause; -import org.obiba.core.service.impl.hibernate.AssociationCriteria; -import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.impl.DefaultQuestionnaireParticipantServiceImpl; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class QuestionnaireParticipantServiceHibernateImpl extends DefaultQuestionnaireParticipantServiceImpl { - - private SessionFactory factory; - - public void setSessionFactory(SessionFactory factory) { - this.factory = factory; - } - - private Session getSession() { - return factory.getCurrentSession(); - } - - public QuestionnaireParticipant getLastQuestionnaireParticipant(Participant participant, String questionnaireName) { - Criteria criteria = AssociationCriteria.create(QuestionnaireParticipant.class, getSession()).add("questionnaireName", Operation.eq, questionnaireName).add("participant", Operation.eq, participant).getCriteria(); - - return (QuestionnaireParticipant) criteria.setMaxResults(1).uniqueResult(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service.impl.hibernate; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.obiba.core.service.SortingClause; +import org.obiba.core.service.impl.hibernate.AssociationCriteria; +import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.impl.DefaultQuestionnaireParticipantServiceImpl; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class QuestionnaireParticipantServiceHibernateImpl extends DefaultQuestionnaireParticipantServiceImpl { + + private SessionFactory factory; + + public void setSessionFactory(SessionFactory factory) { + this.factory = factory; + } + + private Session getSession() { + return factory.getCurrentSession(); + } + + public QuestionnaireParticipant getLastQuestionnaireParticipant(Participant participant, String questionnaireName) { + Criteria criteria = AssociationCriteria.create(QuestionnaireParticipant.class, getSession()).add("questionnaireName", Operation.eq, questionnaireName).add("participant", Operation.eq, participant).getCriteria(); + + return (QuestionnaireParticipant) criteria.setMaxResults(1).uniqueResult(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/QuartzPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/QuartzPanel.java index dc3fbe007..4db8ede16 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/QuartzPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/QuartzPanel.java @@ -1,119 +1,128 @@ -package org.obiba.onyx.quartz.core.wicket; - -import java.util.Locale; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.quartz.core.wicket.wizard.QuestionnaireWizardForm; -import org.obiba.onyx.wicket.IEngineComponentAware; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardPanel; - -public class QuartzPanel extends Panel implements IEngineComponentAware { - - private static final long serialVersionUID = 0L; - - @SpringBean - private QuestionnaireBundleManager questionnaireBundleManager; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private StageModel model; - - private ActionWindow actionWindow; - - private FeedbackPanel feedbackPanel; - - @SuppressWarnings("serial") - public QuartzPanel(String id, Stage stage) { - super(id); - - final Questionnaire questionnaire = questionnaireBundleManager.getBundle(stage.getName()).getQuestionnaire(); - - activeQuestionnaireAdministrationService.setQuestionnaire(questionnaire); - if (activeQuestionnaireAdministrationService.getLanguage() == null) setDefaultLanguage(); - - model = new StageModel(moduleRegistry, stage.getName()); - - add(new WizardPanel("content", new Model(questionnaire)) { - @Override - public WizardForm createForm(String componentId) { - return new QuestionnaireWizardForm(componentId, new Model(questionnaire)) { - - @Override - public void onCancel(AjaxRequestTarget target) { - IStageExecution exec = activeInterviewService.getStageExecution((Stage) model.getObject()); - ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); - if(actionDef != null) { - actionWindow.show(target, model, actionDef); - } - } - - @Override - public void onFinish(AjaxRequestTarget target, Form form) { - IStageExecution exec = activeInterviewService.getStageExecution((Stage) model.getObject()); - ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); - if(actionDef != null) { - actionWindow.show(target, model, actionDef); - } - } - - @Override - public void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedbackPanel); - } - - @Override - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - }; - } - - }); - } - - public void setActionWindwon(ActionWindow window) { - this.actionWindow = window; - } - - public void setFeedbackPanel(FeedbackPanel feedbackPanel) { - this.feedbackPanel = feedbackPanel; - } - - public FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - private void setDefaultLanguage() { - Locale sessionLocale = getSession().getLocale(); - - if (activeQuestionnaireAdministrationService.getQuestionnaire().getLocales().contains(sessionLocale)) - activeQuestionnaireAdministrationService.setDefaultLanguage(sessionLocale); - else activeQuestionnaireAdministrationService.setDefaultLanguage(activeQuestionnaireAdministrationService.getQuestionnaire().getLocales().get(0)); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket; + +import java.util.Locale; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.quartz.core.wicket.wizard.QuestionnaireWizardForm; +import org.obiba.onyx.wicket.IEngineComponentAware; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardPanel; + +public class QuartzPanel extends Panel implements IEngineComponentAware { + + private static final long serialVersionUID = 0L; + + @SpringBean + private QuestionnaireBundleManager questionnaireBundleManager; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private StageModel model; + + private ActionWindow actionWindow; + + private FeedbackPanel feedbackPanel; + + @SuppressWarnings("serial") + public QuartzPanel(String id, Stage stage) { + super(id); + + final Questionnaire questionnaire = questionnaireBundleManager.getBundle(stage.getName()).getQuestionnaire(); + + activeQuestionnaireAdministrationService.setQuestionnaire(questionnaire); + if (activeQuestionnaireAdministrationService.getLanguage() == null) setDefaultLanguage(); + + model = new StageModel(moduleRegistry, stage.getName()); + + add(new WizardPanel("content", new Model(questionnaire)) { + @Override + public WizardForm createForm(String componentId) { + return new QuestionnaireWizardForm(componentId, new Model(questionnaire)) { + + @Override + public void onCancel(AjaxRequestTarget target) { + IStageExecution exec = activeInterviewService.getStageExecution((Stage) model.getObject()); + ActionDefinition actionDef = exec.getActionDefinition(ActionType.STOP); + if(actionDef != null) { + actionWindow.show(target, model, actionDef); + } + } + + @Override + public void onFinish(AjaxRequestTarget target, Form form) { + IStageExecution exec = activeInterviewService.getStageExecution((Stage) model.getObject()); + ActionDefinition actionDef = exec.getSystemActionDefinition(ActionType.COMPLETE); + if(actionDef != null) { + actionWindow.show(target, model, actionDef); + } + } + + @Override + public void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedbackPanel); + } + + @Override + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + }; + } + + }); + } + + public void setActionWindwon(ActionWindow window) { + this.actionWindow = window; + } + + public void setFeedbackPanel(FeedbackPanel feedbackPanel) { + this.feedbackPanel = feedbackPanel; + } + + public FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + private void setDefaultLanguage() { + Locale sessionLocale = getSession().getLocale(); + + if (activeQuestionnaireAdministrationService.getQuestionnaire().getLocales().contains(sessionLocale)) + activeQuestionnaireAdministrationService.setDefaultLanguage(sessionLocale); + else activeQuestionnaireAdministrationService.setDefaultLanguage(activeQuestionnaireAdministrationService.getQuestionnaire().getLocales().get(0)); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IPageLayoutFactory.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IPageLayoutFactory.java index 9b0d946c5..b707ee336 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IPageLayoutFactory.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IPageLayoutFactory.java @@ -1,16 +1,25 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; - -/** - * Page layout factory. - * @author Yannick Marcon - * - */ -public interface IPageLayoutFactory { - - public PageLayout createLayout(String id, Page page); - - public String getName(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; + +/** + * Page layout factory. + * @author Yannick Marcon + * + */ +public interface IPageLayoutFactory { + + public PageLayout createLayout(String id, Page page); + + public String getName(); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IQuestionPanelFactory.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IQuestionPanelFactory.java index 5d32b9311..0df1cbe2f 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IQuestionPanelFactory.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/IQuestionPanelFactory.java @@ -1,11 +1,20 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; - -public interface IQuestionPanelFactory { - - public QuestionPanel createPanel(String id, Question question); - - public String getName(); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; + +public interface IQuestionPanelFactory { + + public QuestionPanel createPanel(String id, Question question); + + public String getName(); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayout.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayout.java index aef1ea40e..f9740bbd8 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayout.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayout.java @@ -1,28 +1,37 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; - -/** - * Page layout definition. - * @author Yannick Marcon - * - */ -public abstract class PageLayout extends Panel { - - public PageLayout(String id, IModel model) { - super(id, model); - } - - /** - * Called when page is left to go to next page. - */ - public abstract void onNext(AjaxRequestTarget target); - - /** - * Called when page is left to go to previous page. - */ - public abstract void onPrevious(AjaxRequestTarget target); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; + +/** + * Page layout definition. + * @author Yannick Marcon + * + */ +public abstract class PageLayout extends Panel { + + public PageLayout(String id, IModel model) { + super(id, model); + } + + /** + * Called when page is left to go to next page. + */ + public abstract void onNext(AjaxRequestTarget target); + + /** + * Called when page is left to go to previous page. + */ + public abstract void onPrevious(AjaxRequestTarget target); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayoutFactoryRegistry.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayoutFactoryRegistry.java index 49a32d125..9e4e8f686 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayoutFactoryRegistry.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageLayoutFactoryRegistry.java @@ -1,29 +1,38 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PageLayoutFactoryRegistry { - - private static final Logger log = LoggerFactory.getLogger(PageLayoutFactoryRegistry.class); - - private Map factories = Collections.synchronizedMap(new HashMap()); - - public void registerFactory(IPageLayoutFactory factory) { - log.info("Registering IPageLayoutFactory {}", factory.getName()); - factories.put(factory.getName(), factory); - } - - public void unregisterFactory(String name) { - factories.remove(name); - } - - public IPageLayoutFactory getFactory(String name) { - return factories.get(name); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PageLayoutFactoryRegistry { + + private static final Logger log = LoggerFactory.getLogger(PageLayoutFactoryRegistry.class); + + private Map factories = Collections.synchronizedMap(new HashMap()); + + public void registerFactory(IPageLayoutFactory factory) { + log.info("Registering IPageLayoutFactory {}", factory.getName()); + factories.put(factory.getName(), factory); + } + + public void unregisterFactory(String name) { + factories.remove(name); + } + + public IPageLayoutFactory getFactory(String name) { + return factories.get(name); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageQuestionsProvider.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageQuestionsProvider.java index 3064e4c3e..6edb248eb 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageQuestionsProvider.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/PageQuestionsProvider.java @@ -1,39 +1,48 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import java.util.Iterator; - -import org.apache.wicket.markup.repeater.data.IDataProvider; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; - -public class PageQuestionsProvider implements IDataProvider { - - private static final long serialVersionUID = 227294946626164090L; - - private Page page; - - public PageQuestionsProvider(Page page) { - this.page = page; - } - - @SuppressWarnings("unchecked") - public Iterator iterator(int first, int count) { - return page.getQuestions().iterator(); - } - - public IModel model(Object object) { - return new Model((Question) object); - } - - public int size() { - return page.getQuestions().size(); - } - - public void detach() { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import java.util.Iterator; + +import org.apache.wicket.markup.repeater.data.IDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; + +public class PageQuestionsProvider implements IDataProvider { + + private static final long serialVersionUID = 227294946626164090L; + + private Page page; + + public PageQuestionsProvider(Page page) { + this.page = page; + } + + @SuppressWarnings("unchecked") + public Iterator iterator(int first, int count) { + return page.getQuestions().iterator(); + } + + public IModel model(Object object) { + return new Model((Question) object); + } + + public int size() { + return page.getQuestions().size(); + } + + public void detach() { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanel.java index f68b2c62c..73c75616e 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanel.java @@ -1,28 +1,37 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; - -/** - * Base class for question display. - * @author Yannick Marcon - * - */ -public abstract class QuestionPanel extends Panel { - - public QuestionPanel(String id, IModel model) { - super(id, model); - } - - /** - * Called when page is left to go to next page. - */ - public abstract void onNext(AjaxRequestTarget target); - - /** - * Called when page is left to go to previous page. - */ - public abstract void onPrevious(AjaxRequestTarget target); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; + +/** + * Base class for question display. + * @author Yannick Marcon + * + */ +public abstract class QuestionPanel extends Panel { + + public QuestionPanel(String id, IModel model) { + super(id, model); + } + + /** + * Called when page is left to go to next page. + */ + public abstract void onNext(AjaxRequestTarget target); + + /** + * Called when page is left to go to previous page. + */ + public abstract void onPrevious(AjaxRequestTarget target); + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanelFactoryRegistry.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanelFactoryRegistry.java index 5567e85ef..724b27ac0 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanelFactoryRegistry.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionPanelFactoryRegistry.java @@ -1,29 +1,38 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class QuestionPanelFactoryRegistry { - - private static final Logger log = LoggerFactory.getLogger(QuestionPanelFactoryRegistry.class); - - private Map factories = Collections.synchronizedMap(new HashMap()); - - public void registerFactory(IQuestionPanelFactory factory) { - log.info("Registering IQuestionPanelFactory {}", factory.getName()); - factories.put(factory.getName(), factory); - } - - public void unregisterFactory(String name) { - factories.remove(name); - } - - public IQuestionPanelFactory getFactory(String name) { - return factories.get(name); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class QuestionPanelFactoryRegistry { + + private static final Logger log = LoggerFactory.getLogger(QuestionPanelFactoryRegistry.class); + + private Map factories = Collections.synchronizedMap(new HashMap()); + + public void registerFactory(IQuestionPanelFactory factory) { + log.info("Registering IQuestionPanelFactory {}", factory.getName()); + factories.put(factory.getName(), factory); + } + + public void unregisterFactory(String name) { + factories.remove(name); + } + + public IQuestionPanelFactory getFactory(String name) { + return factories.get(name); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionnaireUIFactoryRegistrationListener.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionnaireUIFactoryRegistrationListener.java index 864ec6879..0ec31cc85 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionnaireUIFactoryRegistrationListener.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/QuestionnaireUIFactoryRegistrationListener.java @@ -1,74 +1,83 @@ -package org.obiba.onyx.quartz.core.wicket.layout; - -import java.util.Map; - -import org.apache.wicket.protocol.http.WebApplication; -import org.obiba.wicket.application.WebApplicationStartupListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class QuestionnaireUIFactoryRegistrationListener implements WebApplicationStartupListener, ApplicationContextAware { - - private static final Logger log = LoggerFactory.getLogger(QuestionnaireUIFactoryRegistrationListener.class); - - private ApplicationContext applicationContext; - - private PageLayoutFactoryRegistry pageLayoutFactoryRegistry; - - private QuestionPanelFactoryRegistry questionPanelFactoryRegistry; - - @SuppressWarnings("unchecked") - public void shutdown(WebApplication application) { - Map pageLayoutFactories = applicationContext.getBeansOfType(IPageLayoutFactory.class); - if(pageLayoutFactories != null) { - for(IPageLayoutFactory factory : pageLayoutFactories.values()) { - log.info("Unregistering IPageLayoutFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); - pageLayoutFactoryRegistry.unregisterFactory(factory.getName()); - } - } - - Map questionPanelFactories = applicationContext.getBeansOfType(IQuestionPanelFactory.class); - if(questionPanelFactories != null) { - for(IQuestionPanelFactory factory : questionPanelFactories.values()) { - log.info("Unregistering IQuestionPanelFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); - questionPanelFactoryRegistry.unregisterFactory(factory.getName()); - } - } - } - - @SuppressWarnings("unchecked") - public void startup(WebApplication application) { - Map pageLayoutFactories = applicationContext.getBeansOfType(IPageLayoutFactory.class); - if(pageLayoutFactories != null) { - for(IPageLayoutFactory factory : pageLayoutFactories.values()) { - log.info("Registering IPageLayoutFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); - pageLayoutFactoryRegistry.registerFactory(factory); - } - } - - Map questionPanelFactories = applicationContext.getBeansOfType(IQuestionPanelFactory.class); - if(questionPanelFactories != null) { - for(IQuestionPanelFactory factory : questionPanelFactories.values()) { - log.info("Registering IQuestionPanelFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); - questionPanelFactoryRegistry.registerFactory(factory); - } - } - - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - public void setPageLayoutFactoryRegistry(PageLayoutFactoryRegistry pageLayoutFactoryRegistry) { - this.pageLayoutFactoryRegistry = pageLayoutFactoryRegistry; - } - - public void setQuestionPanelFactoryRegistry(QuestionPanelFactoryRegistry questionPanelFactoryRegistry) { - this.questionPanelFactoryRegistry = questionPanelFactoryRegistry; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout; + +import java.util.Map; + +import org.apache.wicket.protocol.http.WebApplication; +import org.obiba.wicket.application.WebApplicationStartupListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +public class QuestionnaireUIFactoryRegistrationListener implements WebApplicationStartupListener, ApplicationContextAware { + + private static final Logger log = LoggerFactory.getLogger(QuestionnaireUIFactoryRegistrationListener.class); + + private ApplicationContext applicationContext; + + private PageLayoutFactoryRegistry pageLayoutFactoryRegistry; + + private QuestionPanelFactoryRegistry questionPanelFactoryRegistry; + + @SuppressWarnings("unchecked") + public void shutdown(WebApplication application) { + Map pageLayoutFactories = applicationContext.getBeansOfType(IPageLayoutFactory.class); + if(pageLayoutFactories != null) { + for(IPageLayoutFactory factory : pageLayoutFactories.values()) { + log.info("Unregistering IPageLayoutFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); + pageLayoutFactoryRegistry.unregisterFactory(factory.getName()); + } + } + + Map questionPanelFactories = applicationContext.getBeansOfType(IQuestionPanelFactory.class); + if(questionPanelFactories != null) { + for(IQuestionPanelFactory factory : questionPanelFactories.values()) { + log.info("Unregistering IQuestionPanelFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); + questionPanelFactoryRegistry.unregisterFactory(factory.getName()); + } + } + } + + @SuppressWarnings("unchecked") + public void startup(WebApplication application) { + Map pageLayoutFactories = applicationContext.getBeansOfType(IPageLayoutFactory.class); + if(pageLayoutFactories != null) { + for(IPageLayoutFactory factory : pageLayoutFactories.values()) { + log.info("Registering IPageLayoutFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); + pageLayoutFactoryRegistry.registerFactory(factory); + } + } + + Map questionPanelFactories = applicationContext.getBeansOfType(IQuestionPanelFactory.class); + if(questionPanelFactories != null) { + for(IQuestionPanelFactory factory : questionPanelFactories.values()) { + log.info("Registering IQuestionPanelFactory '{}' of type {}", factory.getName(), factory.getClass().getSimpleName()); + questionPanelFactoryRegistry.registerFactory(factory); + } + } + + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public void setPageLayoutFactoryRegistry(PageLayoutFactoryRegistry pageLayoutFactoryRegistry) { + this.pageLayoutFactoryRegistry = pageLayoutFactoryRegistry; + } + + public void setQuestionPanelFactoryRegistry(QuestionPanelFactoryRegistry questionPanelFactoryRegistry) { + this.questionPanelFactoryRegistry = questionPanelFactoryRegistry; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayout.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayout.java index b573a99d4..888b81321 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayout.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayout.java @@ -1,61 +1,70 @@ -package org.obiba.onyx.quartz.core.wicket.layout.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.markup.repeater.data.DataView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.wicket.layout.PageLayout; -import org.obiba.onyx.quartz.core.wicket.layout.PageQuestionsProvider; -import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; -import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanelFactoryRegistry; -import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; - -public class DefaultPageLayout extends PageLayout { - - private static final long serialVersionUID = -1757316578083924986L; - - @SpringBean - private QuestionPanelFactoryRegistry questionPanelFactoryRegistry; - - private List questionPanels = new ArrayList(); - - @SuppressWarnings("serial") - public DefaultPageLayout(String id, IModel model) { - super(id, model); - - Page page = (Page) model.getObject(); - add(new Label(id, new QuestionnaireStringResourceModel(page, "label", null))); - - add(new DataView("questions", new PageQuestionsProvider(page)) { - - @Override - protected void populateItem(Item item) { - Question question = (Question) item.getModelObject(); - QuestionPanel panel = questionPanelFactoryRegistry.getFactory(question.getUIFactoryName()).createPanel("question", question); - questionPanels.add(panel); - item.add(panel); - } - - }); - } - - public void onNext(AjaxRequestTarget target) { - for(QuestionPanel panel : questionPanels) { - panel.onNext(target); - } - } - - public void onPrevious(AjaxRequestTarget target) { - for(QuestionPanel panel : questionPanels) { - panel.onPrevious(target); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.markup.repeater.data.DataView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.wicket.layout.PageLayout; +import org.obiba.onyx.quartz.core.wicket.layout.PageQuestionsProvider; +import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; +import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanelFactoryRegistry; +import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; + +public class DefaultPageLayout extends PageLayout { + + private static final long serialVersionUID = -1757316578083924986L; + + @SpringBean + private QuestionPanelFactoryRegistry questionPanelFactoryRegistry; + + private List questionPanels = new ArrayList(); + + @SuppressWarnings("serial") + public DefaultPageLayout(String id, IModel model) { + super(id, model); + + Page page = (Page) model.getObject(); + add(new Label(id, new QuestionnaireStringResourceModel(page, "label", null))); + + add(new DataView("questions", new PageQuestionsProvider(page)) { + + @Override + protected void populateItem(Item item) { + Question question = (Question) item.getModelObject(); + QuestionPanel panel = questionPanelFactoryRegistry.getFactory(question.getUIFactoryName()).createPanel("question", question); + questionPanels.add(panel); + item.add(panel); + } + + }); + } + + public void onNext(AjaxRequestTarget target) { + for(QuestionPanel panel : questionPanels) { + panel.onNext(target); + } + } + + public void onPrevious(AjaxRequestTarget target) { + for(QuestionPanel panel : questionPanels) { + panel.onPrevious(target); + } + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayoutFactory.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayoutFactory.java index 6608434f2..6b74a4cbf 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayoutFactory.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultPageLayoutFactory.java @@ -1,18 +1,27 @@ -package org.obiba.onyx.quartz.core.wicket.layout.impl; - -import org.apache.wicket.model.Model; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; -import org.obiba.onyx.quartz.core.wicket.layout.PageLayout; - -public class DefaultPageLayoutFactory implements IPageLayoutFactory { - - public PageLayout createLayout(String id, Page page) { - return new DefaultPageLayout(id, new Model(page)); - } - - public String getName() { - return "quartz." + getClass().getSimpleName(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout.impl; + +import org.apache.wicket.model.Model; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.wicket.layout.IPageLayoutFactory; +import org.obiba.onyx.quartz.core.wicket.layout.PageLayout; + +public class DefaultPageLayoutFactory implements IPageLayoutFactory { + + public PageLayout createLayout(String id, Page page) { + return new DefaultPageLayout(id, new Model(page)); + } + + public String getName() { + return "quartz." + getClass().getSimpleName(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultQuestionPanelFactory.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultQuestionPanelFactory.java index b9c985dc6..4d75c1d1c 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultQuestionPanelFactory.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/DefaultQuestionPanelFactory.java @@ -1,23 +1,32 @@ -package org.obiba.onyx.quartz.core.wicket.layout.impl; - -import org.apache.wicket.model.Model; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; -import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; - -public class DefaultQuestionPanelFactory implements IQuestionPanelFactory { - - public QuestionPanel createPanel(String id, Question question) { - if(question.isMultiple()) { - return new MultipleChoiceQuestionPanel(id, new Model(question)); - } - else { - return new SingleChoiceQuestionPanel(id, new Model(question)); - } - } - - public String getName() { - return "quartz." + getClass().getSimpleName(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout.impl; + +import org.apache.wicket.model.Model; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.wicket.layout.IQuestionPanelFactory; +import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; + +public class DefaultQuestionPanelFactory implements IQuestionPanelFactory { + + public QuestionPanel createPanel(String id, Question question) { + if(question.isMultiple()) { + return new MultipleChoiceQuestionPanel(id, new Model(question)); + } + else { + return new SingleChoiceQuestionPanel(id, new Model(question)); + } + } + + public String getName() { + return "quartz." + getClass().getSimpleName(); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/MultipleChoiceQuestionPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/MultipleChoiceQuestionPanel.java index bf9f168d5..8b29ff33d 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/MultipleChoiceQuestionPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/MultipleChoiceQuestionPanel.java @@ -1,31 +1,40 @@ -package org.obiba.onyx.quartz.core.wicket.layout.impl; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.IModel; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; -import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; - -public class MultipleChoiceQuestionPanel extends QuestionPanel { - - private static final long serialVersionUID = 2951128797454847260L; - - public MultipleChoiceQuestionPanel(String id, IModel model) { - super(id, model); - - Question question = (Question)model.getObject(); - add(new Label("label", new QuestionnaireStringResourceModel(question, "label", null))); - } - - public void onNext(AjaxRequestTarget target) { - // TODO Auto-generated method stub - - } - - public void onPrevious(AjaxRequestTarget target) { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout.impl; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; +import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; + +public class MultipleChoiceQuestionPanel extends QuestionPanel { + + private static final long serialVersionUID = 2951128797454847260L; + + public MultipleChoiceQuestionPanel(String id, IModel model) { + super(id, model); + + Question question = (Question)model.getObject(); + add(new Label("label", new QuestionnaireStringResourceModel(question, "label", null))); + } + + public void onNext(AjaxRequestTarget target) { + // TODO Auto-generated method stub + + } + + public void onPrevious(AjaxRequestTarget target) { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/SingleChoiceQuestionPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/SingleChoiceQuestionPanel.java index 69e5f1bd9..ccceb2d0d 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/SingleChoiceQuestionPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/layout/impl/SingleChoiceQuestionPanel.java @@ -1,99 +1,108 @@ -package org.obiba.onyx.quartz.core.wicket.layout.impl; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.FormComponentLabel; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.Radio; -import org.apache.wicket.markup.html.form.RadioGroup; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.list.ListView; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; -import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; -import org.obiba.onyx.util.data.Data; -import org.obiba.onyx.wicket.data.DataField; - -public class SingleChoiceQuestionPanel extends QuestionPanel { - - private static final long serialVersionUID = 2951128797454847260L; - - @SuppressWarnings("serial") - public SingleChoiceQuestionPanel(String id, IModel model) { - super(id, model); - - Question question = (Question) model.getObject(); - add(new Label("label", new QuestionnaireStringResourceModel(question, "label", null))); - add(new Label("instructions", new QuestionnaireStringResourceModel(question, "instructions", null))); - add(new Label("caption", new QuestionnaireStringResourceModel(question, "caption", null))); - - final RadioGroup radioGroup = new RadioGroup("categories", new Model()); - add(radioGroup); - ListView radioList = new ListView("category", question.getQuestionCategories()) { - - @Override - protected void populateItem(ListItem item) { - QuestionCategory questionCategory = (QuestionCategory) item.getModelObject(); - Radio radio = new Radio("radio", item.getModel()); - radio.setLabel(new QuestionnaireStringResourceModel(questionCategory, "label", null)); - - FormComponentLabel radioLabel = new FormComponentLabel("categoryLabel", radio); - item.add(radioLabel); - radioLabel.add(radio); - radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); - - if(questionCategory.getCategory().getOpenAnswerDefinition() != null) { - final OpenAnswerDefinition open = questionCategory.getCategory().getOpenAnswerDefinition(); - if (open.getDefaultValues().size()>1) { - radioLabel.add(new DataField("open", new Model(), open.getDataType(), open.getDefaultValues(), new IChoiceRenderer() { - - public Object getDisplayValue(Object object) { - Data data = (Data)object; - return (String)new QuestionnaireStringResourceModel(open, data.getValueAsString(), null).getObject(); - } - - public String getIdValue(Object object, int index) { - Data data = (Data)object; - return data.getValueAsString(); - } - - - }, (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); - } - else if (open.getDefaultValues().size()>0) { - radioLabel.add(new DataField("open", new Model(open.getDefaultValues().get(0)), open.getDataType(), (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); - } - else { - radioLabel.add(new DataField("open", new Model(), open.getDataType(), (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); - } - } else { - radioLabel.add(new EmptyPanel("open")); - } - - if(questionCategory.isSelected()) { - radioGroup.setModel(item.getModel()); - } - } - - }.setReuseItems(true); - radioGroup.add(radioList); - radioGroup.setRequired(question.isRequired()); - - } - - public void onNext(AjaxRequestTarget target) { - // TODO Auto-generated method stub - - } - - public void onPrevious(AjaxRequestTarget target) { - // TODO Auto-generated method stub - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.layout.impl; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.FormComponentLabel; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.Radio; +import org.apache.wicket.markup.html.form.RadioGroup; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.list.ListView; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.OpenAnswerDefinition; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.wicket.layout.QuestionPanel; +import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; +import org.obiba.onyx.util.data.Data; +import org.obiba.onyx.wicket.data.DataField; + +public class SingleChoiceQuestionPanel extends QuestionPanel { + + private static final long serialVersionUID = 2951128797454847260L; + + @SuppressWarnings("serial") + public SingleChoiceQuestionPanel(String id, IModel model) { + super(id, model); + + Question question = (Question) model.getObject(); + add(new Label("label", new QuestionnaireStringResourceModel(question, "label", null))); + add(new Label("instructions", new QuestionnaireStringResourceModel(question, "instructions", null))); + add(new Label("caption", new QuestionnaireStringResourceModel(question, "caption", null))); + + final RadioGroup radioGroup = new RadioGroup("categories", new Model()); + add(radioGroup); + ListView radioList = new ListView("category", question.getQuestionCategories()) { + + @Override + protected void populateItem(ListItem item) { + QuestionCategory questionCategory = (QuestionCategory) item.getModelObject(); + Radio radio = new Radio("radio", item.getModel()); + radio.setLabel(new QuestionnaireStringResourceModel(questionCategory, "label", null)); + + FormComponentLabel radioLabel = new FormComponentLabel("categoryLabel", radio); + item.add(radioLabel); + radioLabel.add(radio); + radioLabel.add(new Label("label", radio.getLabel()).setRenderBodyOnly(true)); + + if(questionCategory.getCategory().getOpenAnswerDefinition() != null) { + final OpenAnswerDefinition open = questionCategory.getCategory().getOpenAnswerDefinition(); + if (open.getDefaultValues().size()>1) { + radioLabel.add(new DataField("open", new Model(), open.getDataType(), open.getDefaultValues(), new IChoiceRenderer() { + + public Object getDisplayValue(Object object) { + Data data = (Data)object; + return (String)new QuestionnaireStringResourceModel(open, data.getValueAsString(), null).getObject(); + } + + public String getIdValue(Object object, int index) { + Data data = (Data)object; + return data.getValueAsString(); + } + + + }, (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); + } + else if (open.getDefaultValues().size()>0) { + radioLabel.add(new DataField("open", new Model(open.getDefaultValues().get(0)), open.getDataType(), (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); + } + else { + radioLabel.add(new DataField("open", new Model(), open.getDataType(), (String)new QuestionnaireStringResourceModel(open, "unitLabel", null).getObject())); + } + } else { + radioLabel.add(new EmptyPanel("open")); + } + + if(questionCategory.isSelected()) { + radioGroup.setModel(item.getModel()); + } + } + + }.setReuseItems(true); + radioGroup.add(radioList); + radioGroup.setRequired(question.isRequired()); + + } + + public void onNext(AjaxRequestTarget target) { + // TODO Auto-generated method stub + + } + + public void onPrevious(AjaxRequestTarget target) { + // TODO Auto-generated method stub + + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModel.java index 2940895fb..414c8ddf0 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModel.java @@ -1,116 +1,125 @@ -package org.obiba.onyx.quartz.core.wicket.model; - -import java.util.Locale; - -import org.apache.wicket.Application; -import org.apache.wicket.model.AbstractReadOnlyModel; -import org.apache.wicket.spring.SpringWebApplication; -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; -import org.springframework.context.ApplicationContext; -import org.springframework.context.MessageSource; - -public class QuestionnaireStringResourceModel extends AbstractReadOnlyModel { - - // - // Constants - // - - private static final long serialVersionUID = 1L; - - private static final int MAX_RESOLVE_STRING_REFERENCE_ATTEMPTS = 10; - - // - // Instance Variables - // - - private ILocalizable localizable; - - private String property; - - private Object[] stringArgs; - - // - // Constructors - // - - public QuestionnaireStringResourceModel(ILocalizable localizable, String property, Object[] stringArgs) { - this.localizable = localizable; - this.property = property; - - // Make a copy of the string arguments. - if(stringArgs != null && stringArgs.length != 0) { - this.stringArgs = new Object[stringArgs.length]; - System.arraycopy(stringArgs, 0, this.stringArgs, 0, this.stringArgs.length); - } - } - - // - // AbstractReadOnlyModel Methods - // - - @Override - public Object getObject() { - // Get the Spring application context. - ApplicationContext context = ((SpringWebApplication) Application.get()).getSpringContextLocator().getSpringContext(); - - // From the context, get the services required to resolve the string resource. - ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService = (ActiveQuestionnaireAdministrationService) context.getBean("activeQuestionnaireAdministrationService"); - QuestionnaireBundleManager bundleManager = (QuestionnaireBundleManager) context.getBean("questionnaireBundleManager"); - - // Now use these services to get current questionnaire bundle. - Locale locale = activeQuestionnaireAdministrationService.getLanguage(); - String bundleName = activeQuestionnaireAdministrationService.getQuestionnaire().getName(); - QuestionnaireBundle bundle = bundleManager.getBundle(bundleName); - - // Finally, resolve the string resource using the bundle's message source and the - // property key. - MessageSource messageSource = bundle.getMessageSource(); - String propertyKey = bundle.getPropertyKey(localizable, property); - - String stringResource = null; - - int resolveAttempts = 0; - - while(true) { - stringResource = messageSource.getMessage(propertyKey, stringArgs, locale); - - if(isStringReference(stringResource)) { - if(resolveAttempts == MAX_RESOLVE_STRING_REFERENCE_ATTEMPTS) { - throw new RuntimeException("Exceeded maximum number of attempts to resolve string reference"); - } - - resolveAttempts++; - propertyKey = extractKeyFromReference(stringResource); - } else { - break; - } - } - - return stringResource; - } - - // - // Methods - // - - /** - * Indicates whether the specified string resource is in fact a string reference (i.e., a reference to another string - * resource). - * - * References have the format: ${string} - * - * @param stringResource string resource - * @return true if the resource is a reference - */ - private boolean isStringReference(String stringResource) { - return (stringResource != null && stringResource.startsWith(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_PREFIX) && stringResource.endsWith(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_SUFFIX)); - } - - private String extractKeyFromReference(String stringReference) { - return stringReference.substring(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_PREFIX.length(), stringReference.length() - StringReferenceCompatibleMessageFormat.STRING_REFERENCE_SUFFIX.length()); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.model; + +import java.util.Locale; + +import org.apache.wicket.Application; +import org.apache.wicket.model.AbstractReadOnlyModel; +import org.apache.wicket.spring.SpringWebApplication; +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.MessageSource; + +public class QuestionnaireStringResourceModel extends AbstractReadOnlyModel { + + // + // Constants + // + + private static final long serialVersionUID = 1L; + + private static final int MAX_RESOLVE_STRING_REFERENCE_ATTEMPTS = 10; + + // + // Instance Variables + // + + private ILocalizable localizable; + + private String property; + + private Object[] stringArgs; + + // + // Constructors + // + + public QuestionnaireStringResourceModel(ILocalizable localizable, String property, Object[] stringArgs) { + this.localizable = localizable; + this.property = property; + + // Make a copy of the string arguments. + if(stringArgs != null && stringArgs.length != 0) { + this.stringArgs = new Object[stringArgs.length]; + System.arraycopy(stringArgs, 0, this.stringArgs, 0, this.stringArgs.length); + } + } + + // + // AbstractReadOnlyModel Methods + // + + @Override + public Object getObject() { + // Get the Spring application context. + ApplicationContext context = ((SpringWebApplication) Application.get()).getSpringContextLocator().getSpringContext(); + + // From the context, get the services required to resolve the string resource. + ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService = (ActiveQuestionnaireAdministrationService) context.getBean("activeQuestionnaireAdministrationService"); + QuestionnaireBundleManager bundleManager = (QuestionnaireBundleManager) context.getBean("questionnaireBundleManager"); + + // Now use these services to get current questionnaire bundle. + Locale locale = activeQuestionnaireAdministrationService.getLanguage(); + String bundleName = activeQuestionnaireAdministrationService.getQuestionnaire().getName(); + QuestionnaireBundle bundle = bundleManager.getBundle(bundleName); + + // Finally, resolve the string resource using the bundle's message source and the + // property key. + MessageSource messageSource = bundle.getMessageSource(); + String propertyKey = bundle.getPropertyKey(localizable, property); + + String stringResource = null; + + int resolveAttempts = 0; + + while(true) { + stringResource = messageSource.getMessage(propertyKey, stringArgs, locale); + + if(isStringReference(stringResource)) { + if(resolveAttempts == MAX_RESOLVE_STRING_REFERENCE_ATTEMPTS) { + throw new RuntimeException("Exceeded maximum number of attempts to resolve string reference"); + } + + resolveAttempts++; + propertyKey = extractKeyFromReference(stringResource); + } else { + break; + } + } + + return stringResource; + } + + // + // Methods + // + + /** + * Indicates whether the specified string resource is in fact a string reference (i.e., a reference to another string + * resource). + * + * References have the format: ${string} + * + * @param stringResource string resource + * @return true if the resource is a reference + */ + private boolean isStringReference(String stringResource) { + return (stringResource != null && stringResource.startsWith(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_PREFIX) && stringResource.endsWith(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_SUFFIX)); + } + + private String extractKeyFromReference(String stringReference) { + return stringReference.substring(StringReferenceCompatibleMessageFormat.STRING_REFERENCE_PREFIX.length(), stringReference.length() - StringReferenceCompatibleMessageFormat.STRING_REFERENCE_SUFFIX.length()); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/questionnaire/LanguageSelectorPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/questionnaire/LanguageSelectorPanel.java index 5c602f91f..46615ec0a 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/questionnaire/LanguageSelectorPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/questionnaire/LanguageSelectorPanel.java @@ -1,69 +1,78 @@ -package org.obiba.onyx.quartz.core.wicket.questionnaire; - -import java.util.List; -import java.util.Locale; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; - -public class LanguageSelectorPanel extends Panel { - - private static final long serialVersionUID = 5589767297291614169L; - - private Locale language = null; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; - - public Locale getLanguage() { - return this.language; - } - - public void setLanguage(Locale language) { - this.language = language; - } - - @SuppressWarnings("serial") - public LanguageSelectorPanel(String id) { - super(id); - - Questionnaire questionnaire = activeQuestionnaireAdministrationService.getQuestionnaire(); - this.setLanguage(activeQuestionnaireAdministrationService.getLanguage()); - - add(new Label("participant", activeInterviewService.getParticipant().getFullName())); - add(new Label("user", activeInterviewService.getInterview().getUser().getFullName())); - add(new Label("description", new QuestionnaireStringResourceModel(questionnaire, "description", null))); - - DropDownChoice ddcLocale = new DropDownChoice("localeSelect", new PropertyModel(LanguageSelectorPanel.this, "language"), questionnaire.getLocales(), new IChoiceRenderer() { - - private static final long serialVersionUID = -1858115721444491116L; - - public Object getDisplayValue(Object object) { - Locale lang = (Locale) object; - return lang.getDisplayLanguage(lang); - } - - public String getIdValue(Object object, int index) { - Locale lang = (Locale) object; - return lang.toString(); - } - - }); - - ddcLocale.setLabel(new StringResourceModel("Language", LanguageSelectorPanel.this, null)); - ddcLocale.setOutputMarkupId(true); - add(ddcLocale); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.questionnaire; + +import java.util.List; +import java.util.Locale; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; + +public class LanguageSelectorPanel extends Panel { + + private static final long serialVersionUID = 5589767297291614169L; + + private Locale language = null; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; + + public Locale getLanguage() { + return this.language; + } + + public void setLanguage(Locale language) { + this.language = language; + } + + @SuppressWarnings("serial") + public LanguageSelectorPanel(String id) { + super(id); + + Questionnaire questionnaire = activeQuestionnaireAdministrationService.getQuestionnaire(); + this.setLanguage(activeQuestionnaireAdministrationService.getLanguage()); + + add(new Label("participant", activeInterviewService.getParticipant().getFullName())); + add(new Label("user", activeInterviewService.getInterview().getUser().getFullName())); + add(new Label("description", new QuestionnaireStringResourceModel(questionnaire, "description", null))); + + DropDownChoice ddcLocale = new DropDownChoice("localeSelect", new PropertyModel(LanguageSelectorPanel.this, "language"), questionnaire.getLocales(), new IChoiceRenderer() { + + private static final long serialVersionUID = -1858115721444491116L; + + public Object getDisplayValue(Object object) { + Locale lang = (Locale) object; + return lang.getDisplayLanguage(lang); + } + + public String getIdValue(Object object, int index) { + Locale lang = (Locale) object; + return lang.toString(); + } + + }); + + ddcLocale.setLabel(new StringResourceModel("Language", LanguageSelectorPanel.this, null)); + ddcLocale.setOutputMarkupId(true); + add(ddcLocale); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/ConclusionStep.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/ConclusionStep.java index dfc1f7452..1025b0ed3 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/ConclusionStep.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/ConclusionStep.java @@ -1,40 +1,49 @@ -package org.obiba.onyx.quartz.core.wicket.wizard; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class ConclusionStep extends WizardStepPanel { - // - // Constants - // - - private static final long serialVersionUID = 1L; - - // - // Constructors - // - - public ConclusionStep(String id) { - super(id); - - // TODO: Initialize components. - } - - // - // WizardStepPanel Methods - // - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - form.getNextLink().setEnabled(false); - form.getPreviousLink().setEnabled(true); - form.getFinishLink().setEnabled(true); - - if(target != null) { - target.addComponent(form.getNextLink()); - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getFinishLink()); - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.wizard; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class ConclusionStep extends WizardStepPanel { + // + // Constants + // + + private static final long serialVersionUID = 1L; + + // + // Constructors + // + + public ConclusionStep(String id) { + super(id); + + // TODO: Initialize components. + } + + // + // WizardStepPanel Methods + // + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + form.getNextLink().setEnabled(false); + form.getPreviousLink().setEnabled(true); + form.getFinishLink().setEnabled(true); + + if(target != null) { + target.addComponent(form.getNextLink()); + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getFinishLink()); + } + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/LanguageSelectionStep.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/LanguageSelectionStep.java index 452a001cd..8cc02fba8 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/LanguageSelectionStep.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/LanguageSelectionStep.java @@ -1,61 +1,70 @@ -package org.obiba.onyx.quartz.core.wicket.wizard; - -import java.util.Locale; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; -import org.obiba.onyx.quartz.core.wicket.questionnaire.LanguageSelectorPanel; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public class LanguageSelectionStep extends WizardStepPanel { - - private static final long serialVersionUID = 5343357448108404508L; - - private LanguageSelectorPanel selectorPanel; - - @SpringBean - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SuppressWarnings("serial") - public LanguageSelectionStep(String id) { - super(id); - setOutputMarkupId(true); - - add(new Label(getTitleId(), new QuestionnaireStringResourceModel(activeQuestionnaireAdministrationService.getQuestionnaire(), "label", null))); - - add(selectorPanel = new LanguageSelectorPanel(getContentId())); - } - - @Override - public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { - QuestionnaireWizardForm questionnaireForm = (QuestionnaireWizardForm) form; - Locale language = selectorPanel.getLanguage(); - - if(language != null) { - activeQuestionnaireAdministrationService.start(activeInterviewService.getParticipant(), language); - setNextStep(questionnaireForm.getFirstPageStep()); - } else { - setNextStep(null); - } - } - - @Override - public void handleWizardState(WizardForm form, AjaxRequestTarget target) { - // No previous step - form.getPreviousLink().setEnabled(false); - form.getNextLink().setEnabled(true); - form.getFinishLink().setEnabled(false); - if(target != null) { - target.addComponent(form.getPreviousLink()); - target.addComponent(form.getNextLink()); - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.wizard; + +import java.util.Locale; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.quartz.core.wicket.model.QuestionnaireStringResourceModel; +import org.obiba.onyx.quartz.core.wicket.questionnaire.LanguageSelectorPanel; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public class LanguageSelectionStep extends WizardStepPanel { + + private static final long serialVersionUID = 5343357448108404508L; + + private LanguageSelectorPanel selectorPanel; + + @SpringBean + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SuppressWarnings("serial") + public LanguageSelectionStep(String id) { + super(id); + setOutputMarkupId(true); + + add(new Label(getTitleId(), new QuestionnaireStringResourceModel(activeQuestionnaireAdministrationService.getQuestionnaire(), "label", null))); + + add(selectorPanel = new LanguageSelectorPanel(getContentId())); + } + + @Override + public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { + QuestionnaireWizardForm questionnaireForm = (QuestionnaireWizardForm) form; + Locale language = selectorPanel.getLanguage(); + + if(language != null) { + activeQuestionnaireAdministrationService.start(activeInterviewService.getParticipant(), language); + setNextStep(questionnaireForm.getFirstPageStep()); + } else { + setNextStep(null); + } + } + + @Override + public void handleWizardState(WizardForm form, AjaxRequestTarget target) { + // No previous step + form.getPreviousLink().setEnabled(false); + form.getNextLink().setEnabled(true); + form.getFinishLink().setEnabled(false); + if(target != null) { + target.addComponent(form.getPreviousLink()); + target.addComponent(form.getNextLink()); + } + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/PageStepPanel.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/PageStepPanel.java index a84cb3af9..c70e83706 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/PageStepPanel.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/PageStepPanel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.wicket.wizard; import org.apache.wicket.ajax.AjaxRequestTarget; diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/QuestionnaireWizardForm.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/QuestionnaireWizardForm.java index 8de356e1a..426b91aa4 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/QuestionnaireWizardForm.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/core/wicket/wizard/QuestionnaireWizardForm.java @@ -1,101 +1,110 @@ -package org.obiba.onyx.quartz.core.wicket.wizard; - -import java.util.List; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.wicket.wizard.WizardForm; -import org.obiba.onyx.wicket.wizard.WizardStepPanel; - -public abstract class QuestionnaireWizardForm extends WizardForm { - - // - // Instance Variables - // - - @SpringBean - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; - - private WizardStepPanel languageSelectionStep; - - private WizardStepPanel conclusionStep; - - // - // Constructors - // - - public QuestionnaireWizardForm(String id, IModel questionnaireModel) { - super(id); - - setModel(questionnaireModel); - - WizardStepPanel startStep = null; - - // First step: Language selection. - languageSelectionStep = new LanguageSelectionStep(getStepId()); - - // Last step: Conclusion. - conclusionStep = new ConclusionStep(getStepId()); - - startStep = languageSelectionStep; - - add(startStep); - startStep.onStepInNext(this, null); - startStep.handleWizardState(this, null); - } - - // - // Methods - // - - /** - * Returns the first page step. - * - * @return first page step (or null if the questionnaire has no pages) - */ - public WizardStepPanel getFirstPageStep() { - Page startPage = activeQuestionnaireAdministrationService.getStartPage(); - return new PageStepPanel(getStepId(), startPage); - } - - /** - * Given the current page step, returns the previous step. - * - * If the current page step is the first page step, returns the language selection step. - * Otherwise, the previous page step is returned. - * - * @param currentStep current page step - * @return previous step - */ - public WizardStepPanel getPreviousStep(PageStepPanel currentStep) { - Page previousPage = activeQuestionnaireAdministrationService.getPreviousPage(); - - if(previousPage != null) { - return new PageStepPanel(getStepId(), previousPage); - } else { - return languageSelectionStep; - } - } - - /** - * Given the current page step, returns the next step. - * - * If the current page step is the last page step, returns the conclusion step. - * Otherwise, the next page step is returned. - * - * @param currentStep current page step - * @return next step - */ - public WizardStepPanel getNextStep(PageStepPanel currentStep) { - Page nextPage = activeQuestionnaireAdministrationService.getNextPage(); - - if(nextPage != null) { - return new PageStepPanel(getStepId(), nextPage); - } else { - return conclusionStep; - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.wizard; + +import java.util.List; + +import org.apache.wicket.model.IModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Page; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.wicket.wizard.WizardForm; +import org.obiba.onyx.wicket.wizard.WizardStepPanel; + +public abstract class QuestionnaireWizardForm extends WizardForm { + + // + // Instance Variables + // + + @SpringBean + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; + + private WizardStepPanel languageSelectionStep; + + private WizardStepPanel conclusionStep; + + // + // Constructors + // + + public QuestionnaireWizardForm(String id, IModel questionnaireModel) { + super(id); + + setModel(questionnaireModel); + + WizardStepPanel startStep = null; + + // First step: Language selection. + languageSelectionStep = new LanguageSelectionStep(getStepId()); + + // Last step: Conclusion. + conclusionStep = new ConclusionStep(getStepId()); + + startStep = languageSelectionStep; + + add(startStep); + startStep.onStepInNext(this, null); + startStep.handleWizardState(this, null); + } + + // + // Methods + // + + /** + * Returns the first page step. + * + * @return first page step (or null if the questionnaire has no pages) + */ + public WizardStepPanel getFirstPageStep() { + Page startPage = activeQuestionnaireAdministrationService.getStartPage(); + return new PageStepPanel(getStepId(), startPage); + } + + /** + * Given the current page step, returns the previous step. + * + * If the current page step is the first page step, returns the language selection step. + * Otherwise, the previous page step is returned. + * + * @param currentStep current page step + * @return previous step + */ + public WizardStepPanel getPreviousStep(PageStepPanel currentStep) { + Page previousPage = activeQuestionnaireAdministrationService.getPreviousPage(); + + if(previousPage != null) { + return new PageStepPanel(getStepId(), previousPage); + } else { + return languageSelectionStep; + } + } + + /** + * Given the current page step, returns the next step. + * + * If the current page step is the last page step, returns the conclusion step. + * Otherwise, the next page step is returned. + * + * @param currentStep current page step + * @return next step + */ + public WizardStepPanel getNextStep(PageStepPanel currentStep) { + Page nextPage = activeQuestionnaireAdministrationService.getNextPage(); + + if(nextPage != null) { + return new PageStepPanel(getStepId(), nextPage); + } else { + return conclusionStep; + } + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/QuartzModule.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/QuartzModule.java index c4d337234..23cea67b1 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/QuartzModule.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/QuartzModule.java @@ -1,111 +1,120 @@ -package org.obiba.onyx.quartz.engine; - -import java.util.List; - -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.StageExecutionContext; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class QuartzModule implements Module, ApplicationContextAware { - - private static final Logger log = LoggerFactory.getLogger(QuartzModule.class); - - private ApplicationContext applicationContext; - - private ActiveInterviewService activeInterviewService; - - private List stages; - - public String getName() { - return "quartz"; - } - - public void initialize() { - log.info("initialize"); - } - - public void shutdown() { - log.info("shutdown"); - } - - public List getStages() { - return stages; - } - - public void setStages(List stages) { - this.stages = stages; - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { - this.activeInterviewService = activeInterviewService; - } - - public IStageExecution createStageExecution(Interview interview, Stage stage) { - StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); - exec.setStage(stage); - exec.setInterview(interview); - - AbstractStageState ready = (AbstractStageState) applicationContext.getBean("quartzReadyState"); - AbstractStageState waiting = (AbstractStageState) applicationContext.getBean("quartzWaitingState"); - AbstractStageState notApplicable = (AbstractStageState) applicationContext.getBean("quartzNotApplicableState"); - AbstractStageState skipped = (AbstractStageState) applicationContext.getBean("quartzSkippedState"); - AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("quartzInProgressState"); - AbstractStageState completed = (AbstractStageState) applicationContext.getBean("quartzCompletedState"); - AbstractStageState interrupted = (AbstractStageState) applicationContext.getBean("quartzInterruptedState"); - - exec.addEdge(waiting, TransitionEvent.VALID, ready); - exec.addEdge(waiting, TransitionEvent.NOTAPPLICABLE, notApplicable); - - exec.addEdge(ready, TransitionEvent.INVALID, waiting); - exec.addEdge(ready, TransitionEvent.NOTAPPLICABLE, notApplicable); - exec.addEdge(ready, TransitionEvent.SKIP, skipped); - exec.addEdge(ready, TransitionEvent.START, inProgress); - - exec.addEdge(skipped, TransitionEvent.NOTAPPLICABLE, notApplicable); - exec.addEdge(skipped, TransitionEvent.CANCEL, ready); - - exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); - exec.addEdge(inProgress, TransitionEvent.INTERRUPT, interrupted); - exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); - - exec.addEdge(completed, TransitionEvent.CANCEL, ready); - exec.addEdge(completed, TransitionEvent.NOTAPPLICABLE, notApplicable); - exec.addEdge(completed, TransitionEvent.RESUME, inProgress); - - exec.addEdge(interrupted, TransitionEvent.CANCEL, ready); - exec.addEdge(interrupted, TransitionEvent.RESUME, inProgress); - exec.addEdge(interrupted, TransitionEvent.NOTAPPLICABLE, notApplicable); - - exec.addEdge(notApplicable, TransitionEvent.VALID, ready); - exec.addEdge(notApplicable, TransitionEvent.INVALID, waiting); - - if(stage.getStageDependencyCondition() == null) { - exec.setInitialState(ready); - } else { - if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == null) { - exec.setInitialState(waiting); - } else if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == true) { - exec.setInitialState(ready); - } else { - exec.setInitialState(notApplicable); - } - } - - return exec; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.engine; + +import java.util.List; + +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.StageExecutionContext; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +public class QuartzModule implements Module, ApplicationContextAware { + + private static final Logger log = LoggerFactory.getLogger(QuartzModule.class); + + private ApplicationContext applicationContext; + + private ActiveInterviewService activeInterviewService; + + private List stages; + + public String getName() { + return "quartz"; + } + + public void initialize() { + log.info("initialize"); + } + + public void shutdown() { + log.info("shutdown"); + } + + public List getStages() { + return stages; + } + + public void setStages(List stages) { + this.stages = stages; + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public void setActiveInterviewService(ActiveInterviewService activeInterviewService) { + this.activeInterviewService = activeInterviewService; + } + + public IStageExecution createStageExecution(Interview interview, Stage stage) { + StageExecutionContext exec = (StageExecutionContext) applicationContext.getBean("stageExecutionContext"); + exec.setStage(stage); + exec.setInterview(interview); + + AbstractStageState ready = (AbstractStageState) applicationContext.getBean("quartzReadyState"); + AbstractStageState waiting = (AbstractStageState) applicationContext.getBean("quartzWaitingState"); + AbstractStageState notApplicable = (AbstractStageState) applicationContext.getBean("quartzNotApplicableState"); + AbstractStageState skipped = (AbstractStageState) applicationContext.getBean("quartzSkippedState"); + AbstractStageState inProgress = (AbstractStageState) applicationContext.getBean("quartzInProgressState"); + AbstractStageState completed = (AbstractStageState) applicationContext.getBean("quartzCompletedState"); + AbstractStageState interrupted = (AbstractStageState) applicationContext.getBean("quartzInterruptedState"); + + exec.addEdge(waiting, TransitionEvent.VALID, ready); + exec.addEdge(waiting, TransitionEvent.NOTAPPLICABLE, notApplicable); + + exec.addEdge(ready, TransitionEvent.INVALID, waiting); + exec.addEdge(ready, TransitionEvent.NOTAPPLICABLE, notApplicable); + exec.addEdge(ready, TransitionEvent.SKIP, skipped); + exec.addEdge(ready, TransitionEvent.START, inProgress); + + exec.addEdge(skipped, TransitionEvent.NOTAPPLICABLE, notApplicable); + exec.addEdge(skipped, TransitionEvent.CANCEL, ready); + + exec.addEdge(inProgress, TransitionEvent.CANCEL, ready); + exec.addEdge(inProgress, TransitionEvent.INTERRUPT, interrupted); + exec.addEdge(inProgress, TransitionEvent.COMPLETE, completed); + + exec.addEdge(completed, TransitionEvent.CANCEL, ready); + exec.addEdge(completed, TransitionEvent.NOTAPPLICABLE, notApplicable); + exec.addEdge(completed, TransitionEvent.RESUME, inProgress); + + exec.addEdge(interrupted, TransitionEvent.CANCEL, ready); + exec.addEdge(interrupted, TransitionEvent.RESUME, inProgress); + exec.addEdge(interrupted, TransitionEvent.NOTAPPLICABLE, notApplicable); + + exec.addEdge(notApplicable, TransitionEvent.VALID, ready); + exec.addEdge(notApplicable, TransitionEvent.INVALID, waiting); + + if(stage.getStageDependencyCondition() == null) { + exec.setInitialState(ready); + } else { + if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == null) { + exec.setInitialState(waiting); + } else if(stage.getStageDependencyCondition().isDependencySatisfied(activeInterviewService) == true) { + exec.setInitialState(ready); + } else { + exec.setInitialState(notApplicable); + } + } + + return exec; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedState.java index cb10318e7..ec9476754 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedState.java @@ -1,76 +1,85 @@ -/** - * State complete for Quartz module - * - * @author acarey - * - * Coming from states: inProgress Possible forward states/actions/transitions: notApplicable, cancel, resume On cancel - * and notApplicable transitions, current questionnaireParticipant is deleted from database (with its dependencies) - */ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzCompletedState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(QuartzCompletedState.class); - - private QuestionnaireParticipantService questionnaireParticipantService; - - public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { - this.questionnaireParticipantService = questionnaireParticipantService; - } - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); - addAction(ActionDefinitionBuilder.create(ActionType.EXECUTE, "Resume").getActionDefinition()); - } - - public String getName() { - return "Quartz.Completed"; - } - - private void cancelQuestionnaireParticipant() { - QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); - questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); - } - - @Override - public void stop(Action action) { - log.info("Quartz Stage {} is cancelling", super.getStage().getName()); - cancelQuestionnaireParticipant(); - if(areDependenciesCompleted() != null && areDependenciesCompleted()) castEvent(TransitionEvent.CANCEL); - else - castEvent(TransitionEvent.INVALID); - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) cancelQuestionnaireParticipant(); - return super.wantTransitionEvent(transitionEvent); - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - public ActionType getStartingActionType() { - return ActionType.EXECUTE; - } - - @Override - public void execute(Action action) { - log.info("Quartz Stage {} is resuming", super.getStage().getName()); - castEvent(TransitionEvent.RESUME); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State complete for Quartz module + * + * @author acarey + * + * Coming from states: inProgress Possible forward states/actions/transitions: notApplicable, cancel, resume On cancel + * and notApplicable transitions, current questionnaireParticipant is deleted from database (with its dependencies) + */ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzCompletedState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(QuartzCompletedState.class); + + private QuestionnaireParticipantService questionnaireParticipantService; + + public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { + this.questionnaireParticipantService = questionnaireParticipantService; + } + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); + addAction(ActionDefinitionBuilder.create(ActionType.EXECUTE, "Resume").getActionDefinition()); + } + + public String getName() { + return "Quartz.Completed"; + } + + private void cancelQuestionnaireParticipant() { + QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); + questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); + } + + @Override + public void stop(Action action) { + log.info("Quartz Stage {} is cancelling", super.getStage().getName()); + cancelQuestionnaireParticipant(); + if(areDependenciesCompleted() != null && areDependenciesCompleted()) castEvent(TransitionEvent.CANCEL); + else + castEvent(TransitionEvent.INVALID); + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) cancelQuestionnaireParticipant(); + return super.wantTransitionEvent(transitionEvent); + } + + @Override + public boolean isCompleted() { + return true; + } + + @Override + public ActionType getStartingActionType() { + return ActionType.EXECUTE; + } + + @Override + public void execute(Action action) { + log.info("Quartz Stage {} is resuming", super.getStage().getName()); + castEvent(TransitionEvent.RESUME); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressState.java index deeb187cd..54dffd55f 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressState.java @@ -1,81 +1,90 @@ -/** - * State inProgress for Quartz module - * - * @author acarey - * - * Coming from states: ready Possible forward states/actions/transitions: cancel, complete, interrupt On cancel - * transition, current questionnaireParticipant is deleted from database (with its dependencies) - */ -package org.obiba.onyx.quartz.engine.state; - -import org.apache.wicket.Component; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; -import org.obiba.onyx.quartz.core.wicket.QuartzPanel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzInProgressState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(QuartzInProgressState.class); - - private QuestionnaireParticipantService questionnaireParticipantService; - - public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { - this.questionnaireParticipantService = questionnaireParticipantService; - } - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); - addAction(ActionDefinitionBuilder.create(ActionType.INTERRUPT, "Interrupt").getActionDefinition()); - addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); - } - - public String getName() { - return "Quartz.InProgress"; - } - - public Component getWidget(String id) { - return new QuartzPanel(id, getStage()); - } - - private void cancelQuestionnaireParticipant() { - QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); - questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); - } - - @Override - public void stop(Action action) { - log.info("Quartz Stage {} is stopping", super.getStage().getName()); - cancelQuestionnaireParticipant(); - if(areDependenciesCompleted() != null && areDependenciesCompleted()) { - castEvent(TransitionEvent.CANCEL); - } else { - castEvent(TransitionEvent.INVALID); - } - } - - @Override - public void complete(Action action) { - log.info("Quartz Stage {} is completing", super.getStage().getName()); - castEvent(TransitionEvent.COMPLETE); - } - - @Override - public boolean isInteractive() { - return true; - } - - @Override - public void interrupt(Action action) { - log.info("Quartz Stage {} is interrupting", super.getStage().getName()); - castEvent(TransitionEvent.INTERRUPT); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State inProgress for Quartz module + * + * @author acarey + * + * Coming from states: ready Possible forward states/actions/transitions: cancel, complete, interrupt On cancel + * transition, current questionnaireParticipant is deleted from database (with its dependencies) + */ +package org.obiba.onyx.quartz.engine.state; + +import org.apache.wicket.Component; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; +import org.obiba.onyx.quartz.core.wicket.QuartzPanel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzInProgressState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(QuartzInProgressState.class); + + private QuestionnaireParticipantService questionnaireParticipantService; + + public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { + this.questionnaireParticipantService = questionnaireParticipantService; + } + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); + addAction(ActionDefinitionBuilder.create(ActionType.INTERRUPT, "Interrupt").getActionDefinition()); + addSystemAction(ActionDefinitionBuilder.COMPLETE_ACTION); + } + + public String getName() { + return "Quartz.InProgress"; + } + + public Component getWidget(String id) { + return new QuartzPanel(id, getStage()); + } + + private void cancelQuestionnaireParticipant() { + QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); + questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); + } + + @Override + public void stop(Action action) { + log.info("Quartz Stage {} is stopping", super.getStage().getName()); + cancelQuestionnaireParticipant(); + if(areDependenciesCompleted() != null && areDependenciesCompleted()) { + castEvent(TransitionEvent.CANCEL); + } else { + castEvent(TransitionEvent.INVALID); + } + } + + @Override + public void complete(Action action) { + log.info("Quartz Stage {} is completing", super.getStage().getName()); + castEvent(TransitionEvent.COMPLETE); + } + + @Override + public boolean isInteractive() { + return true; + } + + @Override + public void interrupt(Action action) { + log.info("Quartz Stage {} is interrupting", super.getStage().getName()); + castEvent(TransitionEvent.INTERRUPT); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedState.java index c0512abf2..c8d33664b 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedState.java @@ -1,66 +1,75 @@ -/** - * State interrupted for Quartz module - * - * @author acarey - * - * Coming from states: inProgress Possible forward states/actions/transitions: cancel, resume, notApplicable? On cancel - * and notApplicable transitions, current questionnaireParticipant is deleted from database (with its dependencies) - */ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzInterruptedState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(QuartzInterruptedState.class); - - private QuestionnaireParticipantService questionnaireParticipantService; - - public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { - this.questionnaireParticipantService = questionnaireParticipantService; - } - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); - addAction(ActionDefinitionBuilder.create(ActionType.EXECUTE, "Resume").getActionDefinition()); - } - - public String getName() { - return "Quartz.Interrupted"; - } - - private void cancelQuestionnaireParticipant() { - QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); - questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); - } - - @Override - public void stop(Action action) { - log.info("Quartz Stage {} is canceling", super.getStage().getName()); - cancelQuestionnaireParticipant(); - if(areDependenciesCompleted() != null && areDependenciesCompleted()) castEvent(TransitionEvent.CANCEL); - else - castEvent(TransitionEvent.INVALID); - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) cancelQuestionnaireParticipant(); - return super.wantTransitionEvent(transitionEvent); - } - - @Override - public void execute(Action action) { - log.info("Quartz Stage {} is resuming", super.getStage().getName()); - castEvent(TransitionEvent.RESUME); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State interrupted for Quartz module + * + * @author acarey + * + * Coming from states: inProgress Possible forward states/actions/transitions: cancel, resume, notApplicable? On cancel + * and notApplicable transitions, current questionnaireParticipant is deleted from database (with its dependencies) + */ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzInterruptedState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(QuartzInterruptedState.class); + + private QuestionnaireParticipantService questionnaireParticipantService; + + public void setQuestionnaireParticipantService(QuestionnaireParticipantService questionnaireParticipantService) { + this.questionnaireParticipantService = questionnaireParticipantService; + } + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.create(ActionType.STOP, "Cancel").setDescription("You may explain why you are cancelling this stage.").getActionDefinition()); + addAction(ActionDefinitionBuilder.create(ActionType.EXECUTE, "Resume").getActionDefinition()); + } + + public String getName() { + return "Quartz.Interrupted"; + } + + private void cancelQuestionnaireParticipant() { + QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(activeInterviewService.getParticipant(), super.getStage().getName()); + questionnaireParticipantService.deleteQuestionnaireParticipant(questionnaireParticipant.getId()); + } + + @Override + public void stop(Action action) { + log.info("Quartz Stage {} is canceling", super.getStage().getName()); + cancelQuestionnaireParticipant(); + if(areDependenciesCompleted() != null && areDependenciesCompleted()) castEvent(TransitionEvent.CANCEL); + else + castEvent(TransitionEvent.INVALID); + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) cancelQuestionnaireParticipant(); + return super.wantTransitionEvent(transitionEvent); + } + + @Override + public void execute(Action action) { + log.info("Quartz Stage {} is resuming", super.getStage().getName()); + castEvent(TransitionEvent.RESUME); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzNotApplicableState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzNotApplicableState.java index 6425ad5c9..682f93e96 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzNotApplicableState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzNotApplicableState.java @@ -1,34 +1,43 @@ -/** - * State notApplicable for Quartz module - * - * @author acarey - * - * Coming from states: waiting, ready, skipped, completed - */ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzNotApplicableState extends AbstractStageState implements InitializingBean { - - public void afterPropertiesSet() throws Exception { - } - - public String getName() { - return "Quartz.NotApplicable"; - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; - else - return true; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State notApplicable for Quartz module + * + * @author acarey + * + * Coming from states: waiting, ready, skipped, completed + */ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzNotApplicableState extends AbstractStageState implements InitializingBean { + + public void afterPropertiesSet() throws Exception { + } + + public String getName() { + return "Quartz.NotApplicable"; + } + + @Override + public boolean isCompleted() { + return true; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.NOTAPPLICABLE)) return false; + else + return true; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzReadyState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzReadyState.java index e42c7a438..311c5d882 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzReadyState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzReadyState.java @@ -1,55 +1,64 @@ -/** - * State ready for Quartz module - * - * @author acarey - * - * Coming from states: waiting, skipped, completed - * Possible forward states/actions/transitions: invalid, start, notApplicable - */ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzReadyState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(QuartzReadyState.class); - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.START_ACTION); - ActionDefinition def = ActionDefinitionBuilder.create(ActionType.SKIP, "Skip").setDescription("You may explain why this stage is skipped.").getActionDefinition(); - addAction(def); - } - - public String getName() { - return "Quartz.Ready"; - } - - @Override - public void execute(Action action) { - super.execute(action); - log.info("Quartz Stage {} is starting", super.getStage().getName()); - castEvent(TransitionEvent.START); - } - - @Override - public void skip(Action action) { - super.skip(action); - log.info("Quartz Stage {} is skipping", super.getStage().getName()); - castEvent(TransitionEvent.SKIP); - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.VALID)) return false; - else - return true; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State ready for Quartz module + * + * @author acarey + * + * Coming from states: waiting, skipped, completed + * Possible forward states/actions/transitions: invalid, start, notApplicable + */ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzReadyState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(QuartzReadyState.class); + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.START_ACTION); + ActionDefinition def = ActionDefinitionBuilder.create(ActionType.SKIP, "Skip").setDescription("You may explain why this stage is skipped.").getActionDefinition(); + addAction(def); + } + + public String getName() { + return "Quartz.Ready"; + } + + @Override + public void execute(Action action) { + super.execute(action); + log.info("Quartz Stage {} is starting", super.getStage().getName()); + castEvent(TransitionEvent.START); + } + + @Override + public void skip(Action action) { + super.skip(action); + log.info("Quartz Stage {} is skipping", super.getStage().getName()); + castEvent(TransitionEvent.SKIP); + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.VALID)) return false; + else + return true; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzSkippedState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzSkippedState.java index 5fed26fee..10b03853a 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzSkippedState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzSkippedState.java @@ -1,76 +1,85 @@ -/** - * State skipped for Quartz module - * - * @author acarey - * - * Coming from states: ready Possible forward states/actions/transitions: cancel, notApplicable - */ -package org.obiba.onyx.quartz.engine.state; - -import java.util.Locale; - -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzSkippedState extends AbstractStageState implements InitializingBean { - - private static final Logger log = LoggerFactory.getLogger(QuartzSkippedState.class); - - public void afterPropertiesSet() throws Exception { - addAction(ActionDefinitionBuilder.CANCEL_SKIPPED_ACTION); - } - - public String getName() { - return "Quartz.Skipped"; - } - - @Override - public void stop(Action action) { - log.info("Quartz Stage {} is cancelling", super.getStage().getName()); - if(areDependenciesCompleted() != null && areDependenciesCompleted()) { - castEvent(TransitionEvent.CANCEL); - } else { - castEvent(TransitionEvent.INVALID); - } - } - - @Override - public void onTransition(IStageExecution execution, TransitionEvent event) { - // case not applicable transition - Boolean var = areDependenciesCompleted(); - if(var != null && var == false) castEvent(TransitionEvent.NOTAPPLICABLE); - } - - @Override - public String getMessage() { - Locale locale = userSessionService.getLocale(); - - String state = getName(); - String reason = (getReason() != null) ? getReason().getEventReason() : null; - - String message = context.getMessage(state, null, locale); - - if(reason != null) { - message += " (" + context.getMessage(reason, null, locale) + ")"; - } - - return message; - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - public ActionType getStartingActionType() { - return ActionType.SKIP; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State skipped for Quartz module + * + * @author acarey + * + * Coming from states: ready Possible forward states/actions/transitions: cancel, notApplicable + */ +package org.obiba.onyx.quartz.engine.state; + +import java.util.Locale; + +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzSkippedState extends AbstractStageState implements InitializingBean { + + private static final Logger log = LoggerFactory.getLogger(QuartzSkippedState.class); + + public void afterPropertiesSet() throws Exception { + addAction(ActionDefinitionBuilder.CANCEL_SKIPPED_ACTION); + } + + public String getName() { + return "Quartz.Skipped"; + } + + @Override + public void stop(Action action) { + log.info("Quartz Stage {} is cancelling", super.getStage().getName()); + if(areDependenciesCompleted() != null && areDependenciesCompleted()) { + castEvent(TransitionEvent.CANCEL); + } else { + castEvent(TransitionEvent.INVALID); + } + } + + @Override + public void onTransition(IStageExecution execution, TransitionEvent event) { + // case not applicable transition + Boolean var = areDependenciesCompleted(); + if(var != null && var == false) castEvent(TransitionEvent.NOTAPPLICABLE); + } + + @Override + public String getMessage() { + Locale locale = userSessionService.getLocale(); + + String state = getName(); + String reason = (getReason() != null) ? getReason().getEventReason() : null; + + String message = context.getMessage(state, null, locale); + + if(reason != null) { + message += " (" + context.getMessage(reason, null, locale) + ")"; + } + + return message; + } + + @Override + public boolean isCompleted() { + return true; + } + + @Override + public ActionType getStartingActionType() { + return ActionType.SKIP; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzStageDependencyCondition.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzStageDependencyCondition.java index ea3f3fdf6..1619a0326 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzStageDependencyCondition.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzStageDependencyCondition.java @@ -1,39 +1,48 @@ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.onyx.engine.state.IStageExecution; - -public class QuartzStageDependencyCondition extends StageDependencyCondition { - - private String stageName; - - public QuartzStageDependencyCondition() { - } - - public QuartzStageDependencyCondition(String name) { - this.stageName = name; - } - - @Override - public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { - IStageExecution stageExecution = activeInterviewService.getStageExecution(stageName); - - if(!stageExecution.isCompleted()) return null; - else - return true; - } - - @Override - public boolean isDependentOn(String stageName) { - return this.stageName.equals(stageName); - } - - public String getStageName() { - return stageName; - } - - public void setStageName(String stageName) { - this.stageName = stageName; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.onyx.engine.state.IStageExecution; + +public class QuartzStageDependencyCondition extends StageDependencyCondition { + + private String stageName; + + public QuartzStageDependencyCondition() { + } + + public QuartzStageDependencyCondition(String name) { + this.stageName = name; + } + + @Override + public Boolean isDependencySatisfied(ActiveInterviewService activeInterviewService) { + IStageExecution stageExecution = activeInterviewService.getStageExecution(stageName); + + if(!stageExecution.isCompleted()) return null; + else + return true; + } + + @Override + public boolean isDependentOn(String stageName) { + return this.stageName.equals(stageName); + } + + public String getStageName() { + return stageName; + } + + public void setStageName(String stageName) { + this.stageName = stageName; + } +} diff --git a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzWaitingState.java b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzWaitingState.java index f92723274..0f8fb8e7c 100644 --- a/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzWaitingState.java +++ b/onyx-modules/quartz/quartz-core/src/main/java/org/obiba/onyx/quartz/engine/state/QuartzWaitingState.java @@ -1,30 +1,39 @@ -/** - * State waiting for Quartz module - * - * @author acarey - * - * Coming from states: ready Possible forward states/actions/transitions: valid, notApplicable - */ -package org.obiba.onyx.quartz.engine.state; - -import org.obiba.onyx.engine.state.AbstractStageState; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.springframework.beans.factory.InitializingBean; - -public class QuartzWaitingState extends AbstractStageState implements InitializingBean { - - public void afterPropertiesSet() throws Exception { - } - - public String getName() { - return "Quartz.Waiting"; - } - - @Override - protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { - if(transitionEvent.equals(TransitionEvent.INVALID)) return false; - else - return true; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +/** + * State waiting for Quartz module + * + * @author acarey + * + * Coming from states: ready Possible forward states/actions/transitions: valid, notApplicable + */ +package org.obiba.onyx.quartz.engine.state; + +import org.obiba.onyx.engine.state.AbstractStageState; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.springframework.beans.factory.InitializingBean; + +public class QuartzWaitingState extends AbstractStageState implements InitializingBean { + + public void afterPropertiesSet() throws Exception { + } + + public String getName() { + return "Quartz.Waiting"; + } + + @Override + protected boolean wantTransitionEvent(TransitionEvent transitionEvent) { + if(transitionEvent.equals(TransitionEvent.INVALID)) return false; + else + return true; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImplTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImplTest.java index 033af1f4d..dd94a900b 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImplTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleImplTest.java @@ -1,124 +1,133 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; -import java.util.Properties; -import java.util.Set; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.util.FileUtil; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; - -public class QuestionnaireBundleImplTest { - - private QuestionnaireBundleManager bundleManager; - - private File rootDirectory; - - private File bundleRootDirectory; - - private QuestionnaireBundle bundle; - - private Questionnaire questionnaire; - - @Before - public void setUp() throws IOException { - // Create the root directory for the bundle manager tests. If it exists - // already, delete it to start clean. - rootDirectory = new File("target", "bundleImpl-test"); - - if(rootDirectory.exists()) { - FileUtil.delete(rootDirectory); - } - - // Create the bundle root directory (including any missing ancestors). - bundleRootDirectory = new File(rootDirectory, "questionnaires"); - bundleRootDirectory.mkdirs(); - - // Create the test questionnaire. - questionnaire = new Questionnaire("q1", "1.0.0"); - - // Create the bundle manager. - bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); - ((QuestionnaireBundleManagerImpl)bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); - - // Create the test bundle. - bundle = bundleManager.createBundle(questionnaire); - } - - @After - public void tearDown() throws IOException { - if(rootDirectory != null && rootDirectory.exists()) { - FileUtil.delete(rootDirectory); - } - } - - @Test - public void testSetLanguage() { - File bundleVersionDir = new File(new File(bundleRootDirectory, bundle.getName()), bundle.getQuestionnaire().getVersion()); - Locale enLocale = new Locale("en"); - Properties enLanguage = new Properties(); - - // Set the language for the "en" locale. - bundle.setLanguage(enLocale, enLanguage); - - // Verify that the language file was created. - File enLanguageFile = new File(bundleVersionDir, "questionnaire_" + enLocale + ".properties"); - Assert.assertTrue(enLanguageFile.isFile()); - } - - @Test - public void testGetLanguage() { - // - // Set languages for two locales, "en" and "fr". - // - Locale enLocale = new Locale("en"); - Properties enLanguage = new Properties(); - enLanguage.setProperty("Questionnaire.q1.label", "value"); - bundle.setLanguage(enLocale, enLanguage); - - Locale frLocale = new Locale("fr"); - Properties frLanguage = new Properties(); - frLanguage.setProperty("Questionnaire.q1.label", "valeur"); - bundle.setLanguage(frLocale, frLanguage); - - // Get the language for the "fr" locale. - Properties testLanguage = bundle.getLanguage(frLocale); - - // Verify that the correct language (French) was returned. - Assert.assertNotNull(testLanguage); - Assert.assertEquals("valeur", testLanguage.getProperty("Questionnaire.q1.label")); - } - - @Test - public void testGetAvailableLanguages() { - // - // Set languages for two locales, "en" and "fr". - // - Locale enLocale = new Locale("en"); - Properties enLanguage = new Properties(); - enLanguage.setProperty("key", "value"); - bundle.setLanguage(enLocale, enLanguage); - - Locale frLocale = new Locale("fr"); - Properties frLanguage = new Properties(); - frLanguage.setProperty("key", "valeur"); - bundle.setLanguage(frLocale, frLanguage); - - // Get all available languages. - Set languages = bundle.getAvailableLanguages(); - - // Verify that the correct set of languages (locales) was returned. - Assert.assertNotNull(languages); - Assert.assertEquals(2, languages.size()); - Assert.assertTrue(languages.contains(enLocale)); - Assert.assertTrue(languages.contains(frLocale)); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; + +import java.io.File; +import java.io.IOException; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.util.FileUtil; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; + +public class QuestionnaireBundleImplTest { + + private QuestionnaireBundleManager bundleManager; + + private File rootDirectory; + + private File bundleRootDirectory; + + private QuestionnaireBundle bundle; + + private Questionnaire questionnaire; + + @Before + public void setUp() throws IOException { + // Create the root directory for the bundle manager tests. If it exists + // already, delete it to start clean. + rootDirectory = new File("target", "bundleImpl-test"); + + if(rootDirectory.exists()) { + FileUtil.delete(rootDirectory); + } + + // Create the bundle root directory (including any missing ancestors). + bundleRootDirectory = new File(rootDirectory, "questionnaires"); + bundleRootDirectory.mkdirs(); + + // Create the test questionnaire. + questionnaire = new Questionnaire("q1", "1.0.0"); + + // Create the bundle manager. + bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); + ((QuestionnaireBundleManagerImpl)bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); + + // Create the test bundle. + bundle = bundleManager.createBundle(questionnaire); + } + + @After + public void tearDown() throws IOException { + if(rootDirectory != null && rootDirectory.exists()) { + FileUtil.delete(rootDirectory); + } + } + + @Test + public void testSetLanguage() { + File bundleVersionDir = new File(new File(bundleRootDirectory, bundle.getName()), bundle.getQuestionnaire().getVersion()); + Locale enLocale = new Locale("en"); + Properties enLanguage = new Properties(); + + // Set the language for the "en" locale. + bundle.setLanguage(enLocale, enLanguage); + + // Verify that the language file was created. + File enLanguageFile = new File(bundleVersionDir, "questionnaire_" + enLocale + ".properties"); + Assert.assertTrue(enLanguageFile.isFile()); + } + + @Test + public void testGetLanguage() { + // + // Set languages for two locales, "en" and "fr". + // + Locale enLocale = new Locale("en"); + Properties enLanguage = new Properties(); + enLanguage.setProperty("Questionnaire.q1.label", "value"); + bundle.setLanguage(enLocale, enLanguage); + + Locale frLocale = new Locale("fr"); + Properties frLanguage = new Properties(); + frLanguage.setProperty("Questionnaire.q1.label", "valeur"); + bundle.setLanguage(frLocale, frLanguage); + + // Get the language for the "fr" locale. + Properties testLanguage = bundle.getLanguage(frLocale); + + // Verify that the correct language (French) was returned. + Assert.assertNotNull(testLanguage); + Assert.assertEquals("valeur", testLanguage.getProperty("Questionnaire.q1.label")); + } + + @Test + public void testGetAvailableLanguages() { + // + // Set languages for two locales, "en" and "fr". + // + Locale enLocale = new Locale("en"); + Properties enLanguage = new Properties(); + enLanguage.setProperty("key", "value"); + bundle.setLanguage(enLocale, enLanguage); + + Locale frLocale = new Locale("fr"); + Properties frLanguage = new Properties(); + frLanguage.setProperty("key", "valeur"); + bundle.setLanguage(frLocale, frLanguage); + + // Get all available languages. + Set languages = bundle.getAvailableLanguages(); + + // Verify that the correct set of languages (locales) was returned. + Assert.assertNotNull(languages); + Assert.assertEquals(2, languages.size()); + Assert.assertTrue(languages.contains(enLocale)); + Assert.assertTrue(languages.contains(frLocale)); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImplTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImplTest.java index 275fac22c..2784548d0 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImplTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/bundle/impl/QuestionnaireBundleManagerImplTest.java @@ -1,126 +1,135 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; - -import java.io.File; -import java.io.IOException; -import java.util.Set; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.util.FileUtil; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; - -public class QuestionnaireBundleManagerImplTest { - - private QuestionnaireBundleManager bundleManager; - - private File rootDirectory; - - private File bundleRootDirectory; - - @Before - public void setUp() throws IOException { - // Create the root directory for the bundle manager tests. If it exists - // already, delete it to start clean. - rootDirectory = new File("target", "bundleManagerImpl-test"); - - if(rootDirectory.exists()) { - FileUtil.delete(rootDirectory); - } - - // Create the bundle root directory (including any missing ancestors). - bundleRootDirectory = new File(rootDirectory, "questionnaires"); - bundleRootDirectory.mkdirs(); - - // Create the bundle manager. - bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); - ((QuestionnaireBundleManagerImpl)bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); - } - - @After - public void tearDown() throws IOException { - if(rootDirectory != null && rootDirectory.exists()) { - FileUtil.delete(rootDirectory); - } - } - - @Test - public void testCreateBundle() { - Questionnaire questionnaire = new Questionnaire("q1", "1.0"); - - // Create the bundle. - try { - bundleManager.createBundle(questionnaire); - } catch(IOException ex) { - Assert.fail("Failed to create bundle"); - } - - // Verify that the bundle version directory was created. - File bundleVersionDir = new File(new File(bundleRootDirectory, questionnaire.getName()), questionnaire.getVersion()); - Assert.assertTrue(bundleVersionDir.isDirectory()); - - // Verify that the questionnaire file was created. - File questionnaireFile = new File(bundleVersionDir, "questionnaire.xml"); - Assert.assertTrue(questionnaireFile.isFile()); - } - - @Test - public void testGetBundle() { - // Create three versions of bundle "q1". - Questionnaire q1v100 = new Questionnaire("q1", "1.0.0"); - Questionnaire q1v101 = new Questionnaire("q1", "1.0.1"); - Questionnaire q1v200 = new Questionnaire("q1", "2.0.0"); - - try { - bundleManager.createBundle(q1v100); - bundleManager.createBundle(q1v101); - bundleManager.createBundle(q1v200); - } catch(IOException ex) { - Assert.fail("Failed to create bundles"); - } - - // Now try to get the bundle that was created. The latest - // version (2.0.0) should be returned. - QuestionnaireBundle bundle = bundleManager.getBundle("q1"); - - // Verify that the bundle was found. - Assert.assertNotNull(bundle); - Assert.assertEquals("q1", bundle.getName()); - Assert.assertEquals("2.0.0", bundle.getQuestionnaire().getVersion()); - } - - @Test - public void testBundles() { - // Create two versions of two different bundles. - Questionnaire q1v100 = new Questionnaire("q1", "1.0.0"); - Questionnaire q1v101 = new Questionnaire("q1", "1.0.1"); - QuestionnaireBundle q1v101Bundle = null; - - Questionnaire q2v100 = new Questionnaire("q2", "1.0.0"); - Questionnaire q2v200 = new Questionnaire("q2", "2.0.0"); - QuestionnaireBundle q2v200Bundle = null; - - try { - bundleManager.createBundle(q1v100); - q1v101Bundle = bundleManager.createBundle(q1v101); - bundleManager.createBundle(q2v100); - q2v200Bundle = bundleManager.createBundle(q2v200); - } catch(IOException ex) { - Assert.fail("Failed to create bundles"); - } - - // Now try to get all the bundles. The latest versions - // 1.0.1 for q1, and 2.0.0 for q2) should be returned. - Set bundles = bundleManager.bundles(); - - // Verify that the correct set of bundles was returned. - Assert.assertNotNull(bundles); - Assert.assertEquals(2, bundles.size()); - Assert.assertTrue(bundles.contains(q1v101Bundle)); - Assert.assertTrue(bundles.contains(q2v200Bundle)); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.bundle.impl; + +import java.io.File; +import java.io.IOException; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.util.FileUtil; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; + +public class QuestionnaireBundleManagerImplTest { + + private QuestionnaireBundleManager bundleManager; + + private File rootDirectory; + + private File bundleRootDirectory; + + @Before + public void setUp() throws IOException { + // Create the root directory for the bundle manager tests. If it exists + // already, delete it to start clean. + rootDirectory = new File("target", "bundleManagerImpl-test"); + + if(rootDirectory.exists()) { + FileUtil.delete(rootDirectory); + } + + // Create the bundle root directory (including any missing ancestors). + bundleRootDirectory = new File(rootDirectory, "questionnaires"); + bundleRootDirectory.mkdirs(); + + // Create the bundle manager. + bundleManager = new QuestionnaireBundleManagerImpl(bundleRootDirectory); + ((QuestionnaireBundleManagerImpl)bundleManager).setPropertyKeyProvider(new DefaultPropertyKeyProviderImpl()); + } + + @After + public void tearDown() throws IOException { + if(rootDirectory != null && rootDirectory.exists()) { + FileUtil.delete(rootDirectory); + } + } + + @Test + public void testCreateBundle() { + Questionnaire questionnaire = new Questionnaire("q1", "1.0"); + + // Create the bundle. + try { + bundleManager.createBundle(questionnaire); + } catch(IOException ex) { + Assert.fail("Failed to create bundle"); + } + + // Verify that the bundle version directory was created. + File bundleVersionDir = new File(new File(bundleRootDirectory, questionnaire.getName()), questionnaire.getVersion()); + Assert.assertTrue(bundleVersionDir.isDirectory()); + + // Verify that the questionnaire file was created. + File questionnaireFile = new File(bundleVersionDir, "questionnaire.xml"); + Assert.assertTrue(questionnaireFile.isFile()); + } + + @Test + public void testGetBundle() { + // Create three versions of bundle "q1". + Questionnaire q1v100 = new Questionnaire("q1", "1.0.0"); + Questionnaire q1v101 = new Questionnaire("q1", "1.0.1"); + Questionnaire q1v200 = new Questionnaire("q1", "2.0.0"); + + try { + bundleManager.createBundle(q1v100); + bundleManager.createBundle(q1v101); + bundleManager.createBundle(q1v200); + } catch(IOException ex) { + Assert.fail("Failed to create bundles"); + } + + // Now try to get the bundle that was created. The latest + // version (2.0.0) should be returned. + QuestionnaireBundle bundle = bundleManager.getBundle("q1"); + + // Verify that the bundle was found. + Assert.assertNotNull(bundle); + Assert.assertEquals("q1", bundle.getName()); + Assert.assertEquals("2.0.0", bundle.getQuestionnaire().getVersion()); + } + + @Test + public void testBundles() { + // Create two versions of two different bundles. + Questionnaire q1v100 = new Questionnaire("q1", "1.0.0"); + Questionnaire q1v101 = new Questionnaire("q1", "1.0.1"); + QuestionnaireBundle q1v101Bundle = null; + + Questionnaire q2v100 = new Questionnaire("q2", "1.0.0"); + Questionnaire q2v200 = new Questionnaire("q2", "2.0.0"); + QuestionnaireBundle q2v200Bundle = null; + + try { + bundleManager.createBundle(q1v100); + q1v101Bundle = bundleManager.createBundle(q1v101); + bundleManager.createBundle(q2v100); + q2v200Bundle = bundleManager.createBundle(q2v200); + } catch(IOException ex) { + Assert.fail("Failed to create bundles"); + } + + // Now try to get all the bundles. The latest versions + // 1.0.1 for q1, and 2.0.0 for q2) should be returned. + Set bundles = bundleManager.bundles(); + + // Verify that the correct set of bundles was returned. + Assert.assertNotNull(bundles); + Assert.assertEquals(2, bundles.size()); + Assert.assertTrue(bundles.contains(q1v101Bundle)); + Assert.assertTrue(bundles.contains(q2v200Bundle)); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilderTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilderTest.java index 79a700387..447332c78 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilderTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireBuilderTest.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.util; import java.util.Properties; diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamerTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamerTest.java index f151f814a..9f161f17f 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamerTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/QuestionnaireStreamerTest.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.quartz.core.engine.questionnaire.util; import java.io.File; diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/QuestionnaireLocalizationTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/QuestionnaireLocalizationTest.java index af159f2a8..1bc8aea29 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/QuestionnaireLocalizationTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/engine/questionnaire/util/localization/QuestionnaireLocalizationTest.java @@ -1,67 +1,76 @@ -package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization; - -import junit.framework.Assert; - -import org.junit.Test; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; -import org.obiba.onyx.util.data.DataBuilder; -import org.obiba.onyx.util.data.DataType; -import org.springframework.beans.factory.annotation.Autowired; - -public class QuestionnaireLocalizationTest extends BaseDefaultSpringContextTestCase { - - @Autowired(required=true) - private IPropertyKeyProvider propertyKeyProvider; - - private static final String YES = "YES"; - - private static final String NO = "NO"; - - private static final String DONT_KNOW = "DONT_KNOW"; - - private static final String OTHER_SPECIFY = "OTHER_SPECIFY"; - - @Test - public void testDefaultLocalization() { - QuestionnaireBuilder builder = QuestionnaireBuilder.createQuestionnaire("HealthQuestionnaire", "1.0"); - - builder.withSection("S1").withSection("S1_1").withPage("P1"); - builder.inPage("P1").withQuestion("Q1").withSharedCategories(YES, NO, DONT_KNOW); - builder.inPage("P1").withQuestion("Q2").withCategories("1", "2").withSharedCategory(DONT_KNOW).setExportName("888"); - - builder.inSection("S1_1").withPage("P2").withQuestion("Q3").withSharedCategory(YES).withSharedCategories(NO, DONT_KNOW); - - builder.inSection("S1").withSection("S1_2").withPage("P3"); - builder.inPage("P3").withQuestion("Q4").withSharedCategories(YES, NO, DONT_KNOW); - - builder.withSection("S2").withSection("S2_1").withPage("P4"); - builder.inPage("P4").withQuestion("Q5").withCategory("NAME").withOpenAnswerDefinition("AGE", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues(DataBuilder.buildInteger(40), DataBuilder.buildInteger(70)); - builder.inQuestion("Q5").withCategory(OTHER_SPECIFY).withOpenAnswerDefinition("SPECIFY", DataType.TEXT).setOpenAnswerDefinitionDefaultData("Left", "Right").setOpenAnswerDefinitionUnit("kg").setOpenAnswerDefinitionFormat("[a-z,A-Z]+"); - - try { - propertyKeyProvider.getPropertyKey(builder.getQuestionnaire(), "tata"); - Assert.fail("Property check failed."); - } catch(IllegalArgumentException e) { - } - - try { - propertyKeyProvider.getPropertyKey(builder.inSection("S1").getElement(), "tata"); - Assert.fail("Property check failed."); - } catch(IllegalArgumentException e) { - } - - try { - propertyKeyProvider.getPropertyKey(builder.inPage("P1").getElement(), "tata"); - Assert.fail("Property check failed."); - } catch(IllegalArgumentException e) { - } - - try { - propertyKeyProvider.getPropertyKey(builder.inQuestion("Q1").getElement(), "tata"); - Assert.fail("Property check failed."); - } catch(IllegalArgumentException e) { - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.engine.questionnaire.util.localization; + +import junit.framework.Assert; + +import org.junit.Test; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.QuestionnaireBuilder; +import org.obiba.onyx.util.data.DataBuilder; +import org.obiba.onyx.util.data.DataType; +import org.springframework.beans.factory.annotation.Autowired; + +public class QuestionnaireLocalizationTest extends BaseDefaultSpringContextTestCase { + + @Autowired(required=true) + private IPropertyKeyProvider propertyKeyProvider; + + private static final String YES = "YES"; + + private static final String NO = "NO"; + + private static final String DONT_KNOW = "DONT_KNOW"; + + private static final String OTHER_SPECIFY = "OTHER_SPECIFY"; + + @Test + public void testDefaultLocalization() { + QuestionnaireBuilder builder = QuestionnaireBuilder.createQuestionnaire("HealthQuestionnaire", "1.0"); + + builder.withSection("S1").withSection("S1_1").withPage("P1"); + builder.inPage("P1").withQuestion("Q1").withSharedCategories(YES, NO, DONT_KNOW); + builder.inPage("P1").withQuestion("Q2").withCategories("1", "2").withSharedCategory(DONT_KNOW).setExportName("888"); + + builder.inSection("S1_1").withPage("P2").withQuestion("Q3").withSharedCategory(YES).withSharedCategories(NO, DONT_KNOW); + + builder.inSection("S1").withSection("S1_2").withPage("P3"); + builder.inPage("P3").withQuestion("Q4").withSharedCategories(YES, NO, DONT_KNOW); + + builder.withSection("S2").withSection("S2_1").withPage("P4"); + builder.inPage("P4").withQuestion("Q5").withCategory("NAME").withOpenAnswerDefinition("AGE", DataType.INTEGER).setOpenAnswerDefinitionAbsoluteValues(DataBuilder.buildInteger(40), DataBuilder.buildInteger(70)); + builder.inQuestion("Q5").withCategory(OTHER_SPECIFY).withOpenAnswerDefinition("SPECIFY", DataType.TEXT).setOpenAnswerDefinitionDefaultData("Left", "Right").setOpenAnswerDefinitionUnit("kg").setOpenAnswerDefinitionFormat("[a-z,A-Z]+"); + + try { + propertyKeyProvider.getPropertyKey(builder.getQuestionnaire(), "tata"); + Assert.fail("Property check failed."); + } catch(IllegalArgumentException e) { + } + + try { + propertyKeyProvider.getPropertyKey(builder.inSection("S1").getElement(), "tata"); + Assert.fail("Property check failed."); + } catch(IllegalArgumentException e) { + } + + try { + propertyKeyProvider.getPropertyKey(builder.inPage("P1").getElement(), "tata"); + Assert.fail("Property check failed."); + } catch(IllegalArgumentException e) { + } + + try { + propertyKeyProvider.getPropertyKey(builder.inQuestion("Q1").getElement(), "tata"); + Assert.fail("Property check failed."); + } catch(IllegalArgumentException e) { + } + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationServiceTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationServiceTest.java index f7df2e35f..532c7bb75 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationServiceTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/ActiveQuestionnaireAdministrationServiceTest.java @@ -1,55 +1,64 @@ -package org.obiba.onyx.quartz.core.service; - -import java.util.Locale; - -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.context.request.SessionScope; - -public class ActiveQuestionnaireAdministrationServiceTest extends BaseDefaultSpringContextTestCase { - - @Autowired - PersistenceManager persistenceManager; - - ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; - - @Before - public void setUp() { - ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("test-spring-context.xml"); - applicationContext.getBeanFactory().registerScope("session", new SessionScope()); - - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpSession session = new MockHttpSession(); - request.setSession(session); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); - - activeQuestionnaireAdministrationService = (ActiveQuestionnaireAdministrationService) applicationContext.getBean("activeQuestionnaireAdministrationService"); - } - - @Test - @Dataset - public void testStart() { - activeQuestionnaireAdministrationService.setQuestionnaire(new Questionnaire("QUE1", "1.0")); - Participant participant = persistenceManager.get(Participant.class, Long.valueOf("1")); - QuestionnaireParticipant questionnaireParticipant = activeQuestionnaireAdministrationService.start(participant, Locale.GERMAN); - Assert.assertEquals(questionnaireParticipant.getLocale(), Locale.GERMAN); - Assert.assertEquals(questionnaireParticipant.getQuestionnaireName(), "QUE1"); - Assert.assertEquals(questionnaireParticipant.getQuestionnaireVersion(), "1.0"); - Assert.assertEquals(questionnaireParticipant.getParticipant(), participant); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service; + +import java.util.Locale; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.context.request.SessionScope; + +public class ActiveQuestionnaireAdministrationServiceTest extends BaseDefaultSpringContextTestCase { + + @Autowired + PersistenceManager persistenceManager; + + ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationService; + + @Before + public void setUp() { + ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("test-spring-context.xml"); + applicationContext.getBeanFactory().registerScope("session", new SessionScope()); + + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpSession session = new MockHttpSession(); + request.setSession(session); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + + activeQuestionnaireAdministrationService = (ActiveQuestionnaireAdministrationService) applicationContext.getBean("activeQuestionnaireAdministrationService"); + } + + @Test + @Dataset + public void testStart() { + activeQuestionnaireAdministrationService.setQuestionnaire(new Questionnaire("QUE1", "1.0")); + Participant participant = persistenceManager.get(Participant.class, Long.valueOf("1")); + QuestionnaireParticipant questionnaireParticipant = activeQuestionnaireAdministrationService.start(participant, Locale.GERMAN); + Assert.assertEquals(questionnaireParticipant.getLocale(), Locale.GERMAN); + Assert.assertEquals(questionnaireParticipant.getQuestionnaireName(), "QUE1"); + Assert.assertEquals(questionnaireParticipant.getQuestionnaireVersion(), "1.0"); + Assert.assertEquals(questionnaireParticipant.getParticipant(), participant); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantServiceTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantServiceTest.java index ecdca5978..323173b63 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantServiceTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/service/QuestionnaireParticipantServiceTest.java @@ -1,44 +1,53 @@ -package org.obiba.onyx.quartz.core.service; - -import junit.framework.Assert; - -import org.junit.Test; -import org.obiba.core.service.PersistenceManager; -import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; -import org.obiba.core.test.spring.Dataset; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.springframework.beans.factory.annotation.Autowired; - -public class QuestionnaireParticipantServiceTest extends BaseDefaultSpringContextTestCase { - - @Autowired(required=true) - PersistenceManager persistenceManager; - - @Autowired(required = true) - QuestionnaireParticipantService questionnaireParticipantService; - - @Test - @Dataset - public void testGetLastQuestionnaireParticipant() { - Participant participant = persistenceManager.get(Participant.class, Long.valueOf("1")); - QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(participant, "QUE1"); - Assert.assertEquals((long) 1, questionnaireParticipant.getId()); - } - - @Test - @Dataset - public void testDeleteQuestionnaireParticipant() { - questionnaireParticipantService.deleteQuestionnaireParticipant(Long.valueOf("2")); - Assert.assertNull(persistenceManager.get(QuestionnaireParticipant.class, Long.valueOf("2"))); - Assert.assertNotNull(persistenceManager.get(QuestionnaireParticipant.class, Long.valueOf("1"))); - Assert.assertNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("1"))); - Assert.assertNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("2"))); - Assert.assertNotNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("3"))); - Assert.assertNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("2"))); - Assert.assertNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("3"))); - Assert.assertNotNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("4"))); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.service; + +import junit.framework.Assert; + +import org.junit.Test; +import org.obiba.core.service.PersistenceManager; +import org.obiba.core.test.spring.BaseDefaultSpringContextTestCase; +import org.obiba.core.test.spring.Dataset; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.quartz.core.domain.answer.CategoryAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionAnswer; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.springframework.beans.factory.annotation.Autowired; + +public class QuestionnaireParticipantServiceTest extends BaseDefaultSpringContextTestCase { + + @Autowired(required=true) + PersistenceManager persistenceManager; + + @Autowired(required = true) + QuestionnaireParticipantService questionnaireParticipantService; + + @Test + @Dataset + public void testGetLastQuestionnaireParticipant() { + Participant participant = persistenceManager.get(Participant.class, Long.valueOf("1")); + QuestionnaireParticipant questionnaireParticipant = questionnaireParticipantService.getLastQuestionnaireParticipant(participant, "QUE1"); + Assert.assertEquals((long) 1, questionnaireParticipant.getId()); + } + + @Test + @Dataset + public void testDeleteQuestionnaireParticipant() { + questionnaireParticipantService.deleteQuestionnaireParticipant(Long.valueOf("2")); + Assert.assertNull(persistenceManager.get(QuestionnaireParticipant.class, Long.valueOf("2"))); + Assert.assertNotNull(persistenceManager.get(QuestionnaireParticipant.class, Long.valueOf("1"))); + Assert.assertNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("1"))); + Assert.assertNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("2"))); + Assert.assertNotNull(persistenceManager.get(QuestionAnswer.class, Long.valueOf("3"))); + Assert.assertNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("2"))); + Assert.assertNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("3"))); + Assert.assertNotNull(persistenceManager.get(CategoryAnswer.class, Long.valueOf("4"))); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/QuartzPanelTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/QuartzPanelTest.java index cfedaa50a..9ad64bef1 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/QuartzPanelTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/QuartzPanelTest.java @@ -1,162 +1,171 @@ -package org.obiba.onyx.quartz.core.wicket; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.util.Locale; - -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.apache.wicket.util.tester.FormTester; -import org.apache.wicket.util.tester.TestPanelSource; -import org.apache.wicket.util.tester.WicketTester; -import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.wicket.test.MockSpringApplication; -import org.springframework.context.MessageSource; - - -public class QuartzPanelTest { - - private WicketTester tester; - - private ActiveInterviewService activeInterviewServiceMock; - - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationServiceMock; - - private QuestionnaireBundleManager questionnaireBundleManagerMock; - - private EntityQueryService queryServiceMock; - - private QuestionnaireBundle questionnaireBundleMock; - - private MessageSource messageSourceMock; - - @Before - public void setUp() { - ApplicationContextMock mockCtx = new ApplicationContextMock(); - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - activeQuestionnaireAdministrationServiceMock = createMock(ActiveQuestionnaireAdministrationService.class); - questionnaireBundleManagerMock = createMock(QuestionnaireBundleManager.class); - queryServiceMock = createMock(EntityQueryService.class); - questionnaireBundleMock = createMock(QuestionnaireBundle.class); - messageSourceMock = createMock(MessageSource.class); - - mockCtx.putBean("activeInterviewService", activeInterviewServiceMock); - mockCtx.putBean("activeQuestionnaireAdministrationService", activeQuestionnaireAdministrationServiceMock); - mockCtx.putBean("questionnaireBundleManager", questionnaireBundleManagerMock); - mockCtx.putBean("queryService", queryServiceMock); - mockCtx.putBean("moduleRegistry", new ModuleRegistry()); - - MockSpringApplication application = new MockSpringApplication(); - application.setApplicationContext(mockCtx); - tester = new WicketTester(application); - } - - @Test - public void testOnStepOutNext() { - - expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); - expect(activeInterviewServiceMock.getInterview()).andReturn(newTestInterview()); - expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(newTestQuestionnaire()).times(4); - expect((questionnaireBundleManagerMock.getBundle("QUE1"))).andReturn(questionnaireBundleMock).times(3); - expect(questionnaireBundleMock.getQuestionnaire()).andReturn(newTestQuestionnaire()); - activeQuestionnaireAdministrationServiceMock.setQuestionnaire((Questionnaire) EasyMock.anyObject()); - - //calls for the label and description properties in LanguageSelectorPanel - expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(Locale.FRENCH).times(4); - expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSourceMock).times(2); - expect(questionnaireBundleMock.getPropertyKey((Questionnaire) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new String()).times(2); - expect(messageSourceMock.getMessage("", null, Locale.FRENCH)).andReturn("").times(2); - - //expect(activeQuestionnaireAdministrationServiceMock.start((Participant) (EasyMock.anyObject()), (Locale) (EasyMock.anyObject()))).andReturn(new QuestionnaireParticipant()); - - replay(activeInterviewServiceMock); - replay(activeQuestionnaireAdministrationServiceMock); - replay(questionnaireBundleManagerMock); - replay(questionnaireBundleMock); - replay(queryServiceMock); - replay(messageSourceMock); - - tester.startPanel(new TestPanelSource() { - - private static final long serialVersionUID = 1L; - - public Panel getTestPanel(String panelId) { - - QuartzPanel quartzPanel = new QuartzPanel(panelId, newTestStage()); - quartzPanel.setModel(new Model(newTestQuestionnaire())); - return (quartzPanel); - - } - }); - - FormTester formTester = tester.newFormTester("panel:content:form"); - formTester.select("step:panel:localeSelect", 1); - - //tester.executeAjaxEvent("panel:content:form:nextLink", "onclick"); - - verify(activeInterviewServiceMock); - verify(activeQuestionnaireAdministrationServiceMock); - verify(questionnaireBundleManagerMock); - verify(questionnaireBundleMock); - verify(queryServiceMock); - verify(messageSourceMock); - } - - private Participant newTestParticipant() { - Participant p = new Participant(); - - p.setId(1); - p.setFirstName("Natasha"); - p.setLastName("Dupont"); - p.setBarcode("barcode1"); - - return (p); - } - - private Interview newTestInterview() { - Interview i = new Interview(); - User u = new User(); - - u.setId(1); - u.setLastName("Administrator"); - u.setFirstName("Onyx"); - i.setUser(u); - - return (i); - } - - private Stage newTestStage() { - Stage s = new Stage(); - - s.setName("QUE1"); - - return (s); - } - - private Questionnaire newTestQuestionnaire() { - Questionnaire q = new Questionnaire("QUE1", "1.0"); - - q.addLocale(Locale.FRENCH); - q.addLocale(Locale.ENGLISH); - - return q; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.util.Locale; + +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.apache.wicket.util.tester.FormTester; +import org.apache.wicket.util.tester.TestPanelSource; +import org.apache.wicket.util.tester.WicketTester; +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.wicket.test.MockSpringApplication; +import org.springframework.context.MessageSource; + + +public class QuartzPanelTest { + + private WicketTester tester; + + private ActiveInterviewService activeInterviewServiceMock; + + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationServiceMock; + + private QuestionnaireBundleManager questionnaireBundleManagerMock; + + private EntityQueryService queryServiceMock; + + private QuestionnaireBundle questionnaireBundleMock; + + private MessageSource messageSourceMock; + + @Before + public void setUp() { + ApplicationContextMock mockCtx = new ApplicationContextMock(); + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + activeQuestionnaireAdministrationServiceMock = createMock(ActiveQuestionnaireAdministrationService.class); + questionnaireBundleManagerMock = createMock(QuestionnaireBundleManager.class); + queryServiceMock = createMock(EntityQueryService.class); + questionnaireBundleMock = createMock(QuestionnaireBundle.class); + messageSourceMock = createMock(MessageSource.class); + + mockCtx.putBean("activeInterviewService", activeInterviewServiceMock); + mockCtx.putBean("activeQuestionnaireAdministrationService", activeQuestionnaireAdministrationServiceMock); + mockCtx.putBean("questionnaireBundleManager", questionnaireBundleManagerMock); + mockCtx.putBean("queryService", queryServiceMock); + mockCtx.putBean("moduleRegistry", new ModuleRegistry()); + + MockSpringApplication application = new MockSpringApplication(); + application.setApplicationContext(mockCtx); + tester = new WicketTester(application); + } + + @Test + public void testOnStepOutNext() { + + expect(activeInterviewServiceMock.getParticipant()).andReturn(newTestParticipant()); + expect(activeInterviewServiceMock.getInterview()).andReturn(newTestInterview()); + expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(newTestQuestionnaire()).times(4); + expect((questionnaireBundleManagerMock.getBundle("QUE1"))).andReturn(questionnaireBundleMock).times(3); + expect(questionnaireBundleMock.getQuestionnaire()).andReturn(newTestQuestionnaire()); + activeQuestionnaireAdministrationServiceMock.setQuestionnaire((Questionnaire) EasyMock.anyObject()); + + //calls for the label and description properties in LanguageSelectorPanel + expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(Locale.FRENCH).times(4); + expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSourceMock).times(2); + expect(questionnaireBundleMock.getPropertyKey((Questionnaire) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new String()).times(2); + expect(messageSourceMock.getMessage("", null, Locale.FRENCH)).andReturn("").times(2); + + //expect(activeQuestionnaireAdministrationServiceMock.start((Participant) (EasyMock.anyObject()), (Locale) (EasyMock.anyObject()))).andReturn(new QuestionnaireParticipant()); + + replay(activeInterviewServiceMock); + replay(activeQuestionnaireAdministrationServiceMock); + replay(questionnaireBundleManagerMock); + replay(questionnaireBundleMock); + replay(queryServiceMock); + replay(messageSourceMock); + + tester.startPanel(new TestPanelSource() { + + private static final long serialVersionUID = 1L; + + public Panel getTestPanel(String panelId) { + + QuartzPanel quartzPanel = new QuartzPanel(panelId, newTestStage()); + quartzPanel.setModel(new Model(newTestQuestionnaire())); + return (quartzPanel); + + } + }); + + FormTester formTester = tester.newFormTester("panel:content:form"); + formTester.select("step:panel:localeSelect", 1); + + //tester.executeAjaxEvent("panel:content:form:nextLink", "onclick"); + + verify(activeInterviewServiceMock); + verify(activeQuestionnaireAdministrationServiceMock); + verify(questionnaireBundleManagerMock); + verify(questionnaireBundleMock); + verify(queryServiceMock); + verify(messageSourceMock); + } + + private Participant newTestParticipant() { + Participant p = new Participant(); + + p.setId(1); + p.setFirstName("Natasha"); + p.setLastName("Dupont"); + p.setBarcode("barcode1"); + + return (p); + } + + private Interview newTestInterview() { + Interview i = new Interview(); + User u = new User(); + + u.setId(1); + u.setLastName("Administrator"); + u.setFirstName("Onyx"); + i.setUser(u); + + return (i); + } + + private Stage newTestStage() { + Stage s = new Stage(); + + s.setName("QUE1"); + + return (s); + } + + private Questionnaire newTestQuestionnaire() { + Questionnaire q = new Questionnaire("QUE1", "1.0"); + + q.addLocale(Locale.FRENCH); + q.addLocale(Locale.ENGLISH); + + return q; + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModelTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModelTest.java index a8247b902..d4a57a631 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModelTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/core/wicket/model/QuestionnaireStringResourceModelTest.java @@ -1,184 +1,193 @@ -package org.obiba.onyx.quartz.core.wicket.model; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.text.MessageFormat; -import java.util.Locale; - -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.apache.wicket.util.tester.WicketTester; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; -import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; -import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; -import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; -import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; -import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; -import org.obiba.wicket.test.MockSpringApplication; -import org.springframework.context.support.StaticMessageSource; - -public class QuestionnaireStringResourceModelTest { - - private ApplicationContextMock applicationContextMock; - - private QuestionnaireBundleManager questionnaireBundleManagerMock; - - private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationServiceMock; - - private Locale locale; - - private Questionnaire questionnaire; - - private QuestionCategory questionCategory; - - private QuestionnaireBundle questionnaireBundleMock; - - private StaticMessageSource messageSource; - - private IPropertyKeyProvider propertyKeyProvider; - - @Before - public void setUp() { - applicationContextMock = new ApplicationContextMock(); - - questionnaireBundleManagerMock = createMock(QuestionnaireBundleManager.class); - applicationContextMock.putBean("questionnaireBundleManager", questionnaireBundleManagerMock); - - activeQuestionnaireAdministrationServiceMock = createMock(ActiveQuestionnaireAdministrationService.class); - applicationContextMock.putBean("activeQuestionnaireAdministrationService", activeQuestionnaireAdministrationServiceMock); - - locale = new Locale("en"); - - questionnaire = new Questionnaire("Q1", "1.0"); - - questionCategory = new QuestionCategory(); - questionCategory.setQuestion(new Question("Q1")); - questionCategory.setCategory(new Category("DONT_KNOW")); - - questionnaireBundleMock = createMock(QuestionnaireBundle.class); - - messageSource = new StaticMessageSource() { - @Override - protected MessageFormat createMessageFormat(String msg, Locale locale) { - return new StringReferenceCompatibleMessageFormat((msg != null ? msg : ""), locale); - } - }; - messageSource.addMessage("Questionnaire.Q1.label", locale, "Test questionnaire label"); - messageSource.addMessage("Questionnaire.Q1.description", locale, "Test questionnaire description with arguments: {0}, {1}"); - messageSource.addMessage("QuestionCategory.Q1.DONT_KNOW.label", locale, "${Category.DONT_KNOW.label}"); - messageSource.addMessage("Category.DONT_KNOW.label", locale, "Don''t know"); - - propertyKeyProvider = new DefaultPropertyKeyProviderImpl(); - - MockSpringApplication application = new MockSpringApplication(); - application.setApplicationContext(applicationContextMock); - - new WicketTester(application); - } - - @Test - public void testResolveStringWithNoArgs() { - ILocalizable localizable = questionnaire; - String property = "label"; - - // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to - // retrieve the current locale and questionnaire. - expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); - expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); - - // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. - expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); - - // Expect that methods are called on questionnaireBundleMock to retrieve the message source - // and required property key. - expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); - expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); - - replay(activeQuestionnaireAdministrationServiceMock); - replay(questionnaireBundleManagerMock); - replay(questionnaireBundleMock); - - QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, property, null); - String stringResource = (String) model.getObject(); - - verify(activeQuestionnaireAdministrationServiceMock); - verify(questionnaireBundleManagerMock); - verify(questionnaireBundleMock); - - Assert.assertEquals("Test questionnaire label", stringResource); - } - - @Test - public void testResolveStringWithArgs() { - ILocalizable localizable = questionnaire; - String property = "description"; - - // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to - // retrieve the current locale and questionnaire. - expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); - expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); - - // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. - expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); - - // Expect that methods are called on questionnaireBundleMock to retrieve the message source - // and required property key. - expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); - expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); - - replay(activeQuestionnaireAdministrationServiceMock); - replay(questionnaireBundleManagerMock); - replay(questionnaireBundleMock); - - QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, "description", new String[] { "firstarg", "secondarg" }); - String stringResource = (String) model.getObject(); - - verify(activeQuestionnaireAdministrationServiceMock); - verify(questionnaireBundleManagerMock); - verify(questionnaireBundleMock); - - Assert.assertEquals("Test questionnaire description with arguments: firstarg, secondarg", stringResource); - } - - @Test - public void testResolveStringWithReferences() { - ILocalizable localizable = questionCategory; - String property = "label"; - - // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to - // retrieve the current locale and questionnaire. - expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); - expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); - - // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. - expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); - - // Expect that methods are called on questionnaireBundleMock to retrieve the message source - // and required property key. - expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); - expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); - - replay(activeQuestionnaireAdministrationServiceMock); - replay(questionnaireBundleManagerMock); - replay(questionnaireBundleMock); - - QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, "label", null); - String stringResource = (String) model.getObject(); - - verify(activeQuestionnaireAdministrationServiceMock); - verify(questionnaireBundleManagerMock); - verify(questionnaireBundleMock); - - Assert.assertEquals("Don't know", stringResource); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.core.wicket.model; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.text.MessageFormat; +import java.util.Locale; + +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.apache.wicket.util.tester.WicketTester; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.quartz.core.engine.questionnaire.ILocalizable; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundle; +import org.obiba.onyx.quartz.core.engine.questionnaire.bundle.QuestionnaireBundleManager; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Category; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Question; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.QuestionCategory; +import org.obiba.onyx.quartz.core.engine.questionnaire.question.Questionnaire; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.IPropertyKeyProvider; +import org.obiba.onyx.quartz.core.engine.questionnaire.util.localization.impl.DefaultPropertyKeyProviderImpl; +import org.obiba.onyx.quartz.core.service.ActiveQuestionnaireAdministrationService; +import org.obiba.onyx.util.StringReferenceCompatibleMessageFormat; +import org.obiba.wicket.test.MockSpringApplication; +import org.springframework.context.support.StaticMessageSource; + +public class QuestionnaireStringResourceModelTest { + + private ApplicationContextMock applicationContextMock; + + private QuestionnaireBundleManager questionnaireBundleManagerMock; + + private ActiveQuestionnaireAdministrationService activeQuestionnaireAdministrationServiceMock; + + private Locale locale; + + private Questionnaire questionnaire; + + private QuestionCategory questionCategory; + + private QuestionnaireBundle questionnaireBundleMock; + + private StaticMessageSource messageSource; + + private IPropertyKeyProvider propertyKeyProvider; + + @Before + public void setUp() { + applicationContextMock = new ApplicationContextMock(); + + questionnaireBundleManagerMock = createMock(QuestionnaireBundleManager.class); + applicationContextMock.putBean("questionnaireBundleManager", questionnaireBundleManagerMock); + + activeQuestionnaireAdministrationServiceMock = createMock(ActiveQuestionnaireAdministrationService.class); + applicationContextMock.putBean("activeQuestionnaireAdministrationService", activeQuestionnaireAdministrationServiceMock); + + locale = new Locale("en"); + + questionnaire = new Questionnaire("Q1", "1.0"); + + questionCategory = new QuestionCategory(); + questionCategory.setQuestion(new Question("Q1")); + questionCategory.setCategory(new Category("DONT_KNOW")); + + questionnaireBundleMock = createMock(QuestionnaireBundle.class); + + messageSource = new StaticMessageSource() { + @Override + protected MessageFormat createMessageFormat(String msg, Locale locale) { + return new StringReferenceCompatibleMessageFormat((msg != null ? msg : ""), locale); + } + }; + messageSource.addMessage("Questionnaire.Q1.label", locale, "Test questionnaire label"); + messageSource.addMessage("Questionnaire.Q1.description", locale, "Test questionnaire description with arguments: {0}, {1}"); + messageSource.addMessage("QuestionCategory.Q1.DONT_KNOW.label", locale, "${Category.DONT_KNOW.label}"); + messageSource.addMessage("Category.DONT_KNOW.label", locale, "Don''t know"); + + propertyKeyProvider = new DefaultPropertyKeyProviderImpl(); + + MockSpringApplication application = new MockSpringApplication(); + application.setApplicationContext(applicationContextMock); + + new WicketTester(application); + } + + @Test + public void testResolveStringWithNoArgs() { + ILocalizable localizable = questionnaire; + String property = "label"; + + // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to + // retrieve the current locale and questionnaire. + expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); + expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); + + // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. + expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); + + // Expect that methods are called on questionnaireBundleMock to retrieve the message source + // and required property key. + expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); + expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); + + replay(activeQuestionnaireAdministrationServiceMock); + replay(questionnaireBundleManagerMock); + replay(questionnaireBundleMock); + + QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, property, null); + String stringResource = (String) model.getObject(); + + verify(activeQuestionnaireAdministrationServiceMock); + verify(questionnaireBundleManagerMock); + verify(questionnaireBundleMock); + + Assert.assertEquals("Test questionnaire label", stringResource); + } + + @Test + public void testResolveStringWithArgs() { + ILocalizable localizable = questionnaire; + String property = "description"; + + // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to + // retrieve the current locale and questionnaire. + expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); + expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); + + // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. + expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); + + // Expect that methods are called on questionnaireBundleMock to retrieve the message source + // and required property key. + expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); + expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); + + replay(activeQuestionnaireAdministrationServiceMock); + replay(questionnaireBundleManagerMock); + replay(questionnaireBundleMock); + + QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, "description", new String[] { "firstarg", "secondarg" }); + String stringResource = (String) model.getObject(); + + verify(activeQuestionnaireAdministrationServiceMock); + verify(questionnaireBundleManagerMock); + verify(questionnaireBundleMock); + + Assert.assertEquals("Test questionnaire description with arguments: firstarg, secondarg", stringResource); + } + + @Test + public void testResolveStringWithReferences() { + ILocalizable localizable = questionCategory; + String property = "label"; + + // Expect that methods are called on activeQuestionnaireAdministrationServiceMock to + // retrieve the current locale and questionnaire. + expect(activeQuestionnaireAdministrationServiceMock.getLanguage()).andReturn(locale); + expect(activeQuestionnaireAdministrationServiceMock.getQuestionnaire()).andReturn(questionnaire); + + // Expect that questionnaireBundleManagerMock is used to retrieve the current questionnaire bundle. + expect(questionnaireBundleManagerMock.getBundle("Q1")).andReturn(questionnaireBundleMock); + + // Expect that methods are called on questionnaireBundleMock to retrieve the message source + // and required property key. + expect(questionnaireBundleMock.getMessageSource()).andReturn(messageSource); + expect(questionnaireBundleMock.getPropertyKey(localizable, property)).andReturn(propertyKeyProvider.getPropertyKey(localizable, property)); + + replay(activeQuestionnaireAdministrationServiceMock); + replay(questionnaireBundleManagerMock); + replay(questionnaireBundleMock); + + QuestionnaireStringResourceModel model = new QuestionnaireStringResourceModel(localizable, "label", null); + String stringResource = (String) model.getObject(); + + verify(activeQuestionnaireAdministrationServiceMock); + verify(questionnaireBundleManagerMock); + verify(questionnaireBundleMock); + + Assert.assertEquals("Don't know", stringResource); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedStateTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedStateTest.java index 8ae924508..6deaa5b1c 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedStateTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzCompletedStateTest.java @@ -1,138 +1,147 @@ -package org.obiba.onyx.quartz.engine.state; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.Serializable; - -import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.ITransitionEventSink; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; - -public class QuartzCompletedStateTest { - - private ITransitionEventSink eventSinkMock; - - private QuestionnaireParticipantService questionnaireParticipantServiceMock; - - private ActiveInterviewService activeInterviewServiceMock; - - private QuartzCompletedState completedState; - - /** - * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable - */ - - @Before - public void setUp() { - eventSinkMock = createMock(ITransitionEventSink.class); - questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenCancel() { - - completedState = new QuartzCompletedState() { - @Override - protected Boolean areDependenciesCompleted() { - return true; - } - }; - - setCompletedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.CANCEL); - - Action completeAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - completedState.stop(completeAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenInvalid() { - - completedState = new QuartzCompletedState() { - @Override - protected Boolean areDependenciesCompleted() { - return null; - } - }; - - setCompletedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.INVALID); - - Action completeAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - completedState.stop(completeAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenNotApplicable() { - - completedState = new QuartzCompletedState(); - setCompletedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - // testing when notApplicable Transition event is passed: deletion should happen - completedState.wantTransitionEvent(TransitionEvent.NOTAPPLICABLE); - - // testing when another Transition event is passed: NO deletion should happen - completedState.wantTransitionEvent(TransitionEvent.INVALID); - - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - private void setCompletedState() { - completedState.setStage(newTestStage()); - completedState.setEventSink(eventSinkMock); - completedState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); - completedState.setActiveInterviewService(activeInterviewServiceMock); - } - - private Stage newTestStage() { - Stage s = new Stage(); - s.setName("QUE1"); - return (s); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.engine.state; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.io.Serializable; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.ITransitionEventSink; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; + +public class QuartzCompletedStateTest { + + private ITransitionEventSink eventSinkMock; + + private QuestionnaireParticipantService questionnaireParticipantServiceMock; + + private ActiveInterviewService activeInterviewServiceMock; + + private QuartzCompletedState completedState; + + /** + * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable + */ + + @Before + public void setUp() { + eventSinkMock = createMock(ITransitionEventSink.class); + questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenCancel() { + + completedState = new QuartzCompletedState() { + @Override + protected Boolean areDependenciesCompleted() { + return true; + } + }; + + setCompletedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.CANCEL); + + Action completeAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + completedState.stop(completeAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenInvalid() { + + completedState = new QuartzCompletedState() { + @Override + protected Boolean areDependenciesCompleted() { + return null; + } + }; + + setCompletedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.INVALID); + + Action completeAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + completedState.stop(completeAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenNotApplicable() { + + completedState = new QuartzCompletedState(); + setCompletedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + // testing when notApplicable Transition event is passed: deletion should happen + completedState.wantTransitionEvent(TransitionEvent.NOTAPPLICABLE); + + // testing when another Transition event is passed: NO deletion should happen + completedState.wantTransitionEvent(TransitionEvent.INVALID); + + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + private void setCompletedState() { + completedState.setStage(newTestStage()); + completedState.setEventSink(eventSinkMock); + completedState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); + completedState.setActiveInterviewService(activeInterviewServiceMock); + } + + private Stage newTestStage() { + Stage s = new Stage(); + s.setName("QUE1"); + return (s); + } +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressStateTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressStateTest.java index d4738c8e9..555244a8e 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressStateTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInProgressStateTest.java @@ -1,116 +1,125 @@ -package org.obiba.onyx.quartz.engine.state; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.Serializable; - -import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.ITransitionEventSink; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; - -public class QuartzInProgressStateTest { - - private ITransitionEventSink eventSinkMock; - - private QuestionnaireParticipantService questionnaireParticipantServiceMock; - - private ActiveInterviewService activeInterviewServiceMock; - - private QuartzInProgressState inProgressState; - - /** - * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable - */ - - @Before - public void setUp() { - eventSinkMock = createMock(ITransitionEventSink.class); - questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenCancel() { - - inProgressState = new QuartzInProgressState() { - @Override - protected Boolean areDependenciesCompleted() { - return true; - } - }; - - setInProgressState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.CANCEL); - - Action inProgressAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - inProgressState.stop(inProgressAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenInvalid() { - - inProgressState = new QuartzInProgressState() { - @Override - protected Boolean areDependenciesCompleted() { - return null; - } - }; - - setInProgressState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.INVALID); - - Action inProgressAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - inProgressState.stop(inProgressAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - private void setInProgressState() { - inProgressState.setStage(newTestStage()); - inProgressState.setEventSink(eventSinkMock); - inProgressState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); - inProgressState.setActiveInterviewService(activeInterviewServiceMock); - } - - private Stage newTestStage() { - Stage s = new Stage(); - s.setName("QUE1"); - return (s); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.engine.state; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.io.Serializable; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.ITransitionEventSink; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; + +public class QuartzInProgressStateTest { + + private ITransitionEventSink eventSinkMock; + + private QuestionnaireParticipantService questionnaireParticipantServiceMock; + + private ActiveInterviewService activeInterviewServiceMock; + + private QuartzInProgressState inProgressState; + + /** + * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable + */ + + @Before + public void setUp() { + eventSinkMock = createMock(ITransitionEventSink.class); + questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenCancel() { + + inProgressState = new QuartzInProgressState() { + @Override + protected Boolean areDependenciesCompleted() { + return true; + } + }; + + setInProgressState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.CANCEL); + + Action inProgressAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + inProgressState.stop(inProgressAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenInvalid() { + + inProgressState = new QuartzInProgressState() { + @Override + protected Boolean areDependenciesCompleted() { + return null; + } + }; + + setInProgressState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.INVALID); + + Action inProgressAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + inProgressState.stop(inProgressAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + private void setInProgressState() { + inProgressState.setStage(newTestStage()); + inProgressState.setEventSink(eventSinkMock); + inProgressState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); + inProgressState.setActiveInterviewService(activeInterviewServiceMock); + } + + private Stage newTestStage() { + Stage s = new Stage(); + s.setName("QUE1"); + return (s); + } + +} diff --git a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedStateTest.java b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedStateTest.java index 3d18ae342..0b8f60166 100644 --- a/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedStateTest.java +++ b/onyx-modules/quartz/quartz-core/src/test/java/org/obiba/onyx/quartz/engine/state/QuartzInterruptedStateTest.java @@ -1,138 +1,147 @@ -package org.obiba.onyx.quartz.engine.state; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.Serializable; - -import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.ITransitionEventSink; -import org.obiba.onyx.engine.state.TransitionEvent; -import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; -import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; - -public class QuartzInterruptedStateTest { - - private ITransitionEventSink eventSinkMock; - - private QuestionnaireParticipantService questionnaireParticipantServiceMock; - - private ActiveInterviewService activeInterviewServiceMock; - - private QuartzInterruptedState interruptedState; - - /** - * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable - */ - - @Before - public void setUp() { - eventSinkMock = createMock(ITransitionEventSink.class); - questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenCancel() { - - interruptedState = new QuartzInterruptedState() { - @Override - protected Boolean areDependenciesCompleted() { - return true; - } - }; - - setInterruptedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.CANCEL); - - Action completeAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - interruptedState.stop(completeAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenInvalid() { - - interruptedState = new QuartzInterruptedState() { - @Override - protected Boolean areDependenciesCompleted() { - return null; - } - }; - - setInterruptedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - eventSinkMock.castEvent(TransitionEvent.INVALID); - - Action completeAction = new Action(); - - replay(eventSinkMock); - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - interruptedState.stop(completeAction); - - verify(eventSinkMock); - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - @Test - public void testQuestionnaireParticipantDeleteWhenNotApplicable() { - - interruptedState = new QuartzInterruptedState(); - setInterruptedState(); - - expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); - expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); - questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); - - replay(activeInterviewServiceMock); - replay(questionnaireParticipantServiceMock); - - // testing when notApplicable Transition event is passed: deletion should happen - interruptedState.wantTransitionEvent(TransitionEvent.NOTAPPLICABLE); - - // testing when another Transition event is passed: NO deletion should happen - interruptedState.wantTransitionEvent(TransitionEvent.INVALID); - - verify(activeInterviewServiceMock); - verify(questionnaireParticipantServiceMock); - } - - private void setInterruptedState() { - interruptedState.setStage(newTestStage()); - interruptedState.setEventSink(eventSinkMock); - interruptedState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); - interruptedState.setActiveInterviewService(activeInterviewServiceMock); - } - - private Stage newTestStage() { - Stage s = new Stage(); - s.setName("QUE1"); - return (s); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.quartz.engine.state; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.io.Serializable; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.ITransitionEventSink; +import org.obiba.onyx.engine.state.TransitionEvent; +import org.obiba.onyx.quartz.core.domain.answer.QuestionnaireParticipant; +import org.obiba.onyx.quartz.core.service.QuestionnaireParticipantService; + +public class QuartzInterruptedStateTest { + + private ITransitionEventSink eventSinkMock; + + private QuestionnaireParticipantService questionnaireParticipantServiceMock; + + private ActiveInterviewService activeInterviewServiceMock; + + private QuartzInterruptedState interruptedState; + + /** + * Tests that the questionnaireParticipant is deleted if stage canceled or not applicable + */ + + @Before + public void setUp() { + eventSinkMock = createMock(ITransitionEventSink.class); + questionnaireParticipantServiceMock = createMock(QuestionnaireParticipantService.class); + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenCancel() { + + interruptedState = new QuartzInterruptedState() { + @Override + protected Boolean areDependenciesCompleted() { + return true; + } + }; + + setInterruptedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.CANCEL); + + Action completeAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + interruptedState.stop(completeAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenInvalid() { + + interruptedState = new QuartzInterruptedState() { + @Override + protected Boolean areDependenciesCompleted() { + return null; + } + }; + + setInterruptedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + eventSinkMock.castEvent(TransitionEvent.INVALID); + + Action completeAction = new Action(); + + replay(eventSinkMock); + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + interruptedState.stop(completeAction); + + verify(eventSinkMock); + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + @Test + public void testQuestionnaireParticipantDeleteWhenNotApplicable() { + + interruptedState = new QuartzInterruptedState(); + setInterruptedState(); + + expect(activeInterviewServiceMock.getParticipant()).andReturn(new Participant()); + expect(questionnaireParticipantServiceMock.getLastQuestionnaireParticipant((Participant) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(new QuestionnaireParticipant()); + questionnaireParticipantServiceMock.deleteQuestionnaireParticipant((Serializable) EasyMock.anyObject()); + + replay(activeInterviewServiceMock); + replay(questionnaireParticipantServiceMock); + + // testing when notApplicable Transition event is passed: deletion should happen + interruptedState.wantTransitionEvent(TransitionEvent.NOTAPPLICABLE); + + // testing when another Transition event is passed: NO deletion should happen + interruptedState.wantTransitionEvent(TransitionEvent.INVALID); + + verify(activeInterviewServiceMock); + verify(questionnaireParticipantServiceMock); + } + + private void setInterruptedState() { + interruptedState.setStage(newTestStage()); + interruptedState.setEventSink(eventSinkMock); + interruptedState.setQuestionnaireParticipantService(questionnaireParticipantServiceMock); + interruptedState.setActiveInterviewService(activeInterviewServiceMock); + } + + private Stage newTestStage() { + Stage s = new Stage(); + s.setName("QUE1"); + return (s); + } +} diff --git a/onyx-util/src/main/java/org/obiba/onyx/util/StringReferenceCompatibleMessageFormat.java b/onyx-util/src/main/java/org/obiba/onyx/util/StringReferenceCompatibleMessageFormat.java index 8493e1bab..64d7f7f4b 100644 --- a/onyx-util/src/main/java/org/obiba/onyx/util/StringReferenceCompatibleMessageFormat.java +++ b/onyx-util/src/main/java/org/obiba/onyx/util/StringReferenceCompatibleMessageFormat.java @@ -1,50 +1,59 @@ -package org.obiba.onyx.util; - -import java.text.MessageFormat; -import java.util.Locale; - -public class StringReferenceCompatibleMessageFormat extends MessageFormat { - - // - // Constants - // - private static final long serialVersionUID = 1L; - - public static final String STRING_REFERENCE_PREFIX = "${"; - - public static final String STRING_REFERENCE_SUFFIX = "}"; - - // - // Constructors - // - - public StringReferenceCompatibleMessageFormat(String pattern) { - super(adjustPattern(pattern)); - } - - public StringReferenceCompatibleMessageFormat(String pattern, Locale locale) { - super(adjustPattern(pattern), locale); - } - - // - // Methods - // - - /** - * This methods checks whether the specified pattern is a string reference. If so, it adds single quotes around the - * pattern. - * - * @param pattern - * @return quoted pattern if it is a string reference, otherwise original pattern - */ - private static String adjustPattern(String pattern) { - // Quote patterns that are string references (i.e., beginning with "${" and ending with "}") - // to prevent the contents from being parsed as a number. Note that, as usual, the quotes will - // not be included in the formatted string. - if(pattern != null && pattern.startsWith(STRING_REFERENCE_PREFIX) && pattern.endsWith(STRING_REFERENCE_SUFFIX)) { - pattern = "'" + pattern + "'"; - } - - return pattern; - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util; + +import java.text.MessageFormat; +import java.util.Locale; + +public class StringReferenceCompatibleMessageFormat extends MessageFormat { + + // + // Constants + // + private static final long serialVersionUID = 1L; + + public static final String STRING_REFERENCE_PREFIX = "${"; + + public static final String STRING_REFERENCE_SUFFIX = "}"; + + // + // Constructors + // + + public StringReferenceCompatibleMessageFormat(String pattern) { + super(adjustPattern(pattern)); + } + + public StringReferenceCompatibleMessageFormat(String pattern, Locale locale) { + super(adjustPattern(pattern), locale); + } + + // + // Methods + // + + /** + * This methods checks whether the specified pattern is a string reference. If so, it adds single quotes around the + * pattern. + * + * @param pattern + * @return quoted pattern if it is a string reference, otherwise original pattern + */ + private static String adjustPattern(String pattern) { + // Quote patterns that are string references (i.e., beginning with "${" and ending with "}") + // to prevent the contents from being parsed as a number. Note that, as usual, the quotes will + // not be included in the formatted string. + if(pattern != null && pattern.startsWith(STRING_REFERENCE_PREFIX) && pattern.endsWith(STRING_REFERENCE_SUFFIX)) { + pattern = "'" + pattern + "'"; + } + + return pattern; + } +} diff --git a/onyx-util/src/main/java/org/obiba/onyx/util/StringUtil.java b/onyx-util/src/main/java/org/obiba/onyx/util/StringUtil.java index a24d6840b..f0e450860 100644 --- a/onyx-util/src/main/java/org/obiba/onyx/util/StringUtil.java +++ b/onyx-util/src/main/java/org/obiba/onyx/util/StringUtil.java @@ -1,38 +1,47 @@ -package org.obiba.onyx.util; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import au.com.bytecode.opencsv.CSVReader; - -public class StringUtil { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(StringUtil.class); - - public static List parseCSVString(String csvString) { - List strings = new ArrayList(); - - log.debug("csvString={}", csvString); - CSVReader reader = new CSVReader(new StringReader(csvString)); - try { - String[] array = reader.readNext(); - if (array != null) { - for (String str : array) { - strings.add(str); - } - } - } catch(IOException e) { - log.error("Failed parsing CSV string:" + csvString, e); - } - log.debug("strings={}", strings); - - return strings; - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import au.com.bytecode.opencsv.CSVReader; + +public class StringUtil { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(StringUtil.class); + + public static List parseCSVString(String csvString) { + List strings = new ArrayList(); + + log.debug("csvString={}", csvString); + CSVReader reader = new CSVReader(new StringReader(csvString)); + try { + String[] array = reader.readNext(); + if (array != null) { + for (String str : array) { + strings.add(str); + } + } + } catch(IOException e) { + log.error("Failed parsing CSV string:" + csvString, e); + } + log.debug("strings={}", strings); + + return strings; + } + +} diff --git a/onyx-util/src/main/java/org/obiba/onyx/util/data/Data.java b/onyx-util/src/main/java/org/obiba/onyx/util/data/Data.java index 64eef3a83..80a9976ac 100644 --- a/onyx-util/src/main/java/org/obiba/onyx/util/data/Data.java +++ b/onyx-util/src/main/java/org/obiba/onyx/util/data/Data.java @@ -1,153 +1,162 @@ -package org.obiba.onyx.util.data; - -import java.io.Serializable; -import java.util.Date; - -public class Data implements Serializable { - - private static final long serialVersionUID = -2470483891384378865L; - - private Serializable value; - - private DataType type; - - public Data(DataType type) { - this.type = type; - } - - public Data(DataType type, Serializable value) { - this.type = type; - setValue(value); - } - - public DataType getType() { - return type; - } - - @SuppressWarnings("unchecked") - public T getValue() { - return (T) value; - } - - public void setValue(Serializable value) { - if(value != null) { - Class valueClass = value.getClass(); - - switch(type) { - case BOOLEAN: - if(!valueClass.isAssignableFrom(Boolean.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - case DATE: - if(!(value instanceof Date)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - case DECIMAL: - if(!valueClass.isAssignableFrom(Double.class) && !valueClass.isAssignableFrom(Float.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - case INTEGER: - if(!valueClass.isAssignableFrom(Long.class) && !valueClass.isAssignableFrom(Integer.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - case TEXT: - if(!valueClass.isAssignableFrom(String.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - case DATA: - if(!valueClass.isAssignableFrom(byte[].class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); - break; - - default: - break; - } - } - this.value = value; - } - - public String getValueAsString() { - if(type != DataType.DATA) { - return value != null ? value.toString() : null; - } - // TODO determine how to output a meaningful value for byte arrays - return ""; - } - - @Override - public String toString() { - return "[" + type + ":" + value + "]"; - } - - @Override - public int hashCode() { - int hashCode = 0; - - if (value != null) { - if (type != DataType.DATA) { - hashCode = value.hashCode(); - } - else { - byte[] bytes = (byte[])value; - int byteCount = bytes.length; - hashCode = byteCount != 0 ? (byteCount + bytes[0] + bytes[byteCount - 1]) % 17 : Integer.MAX_VALUE; - } - } - - return hashCode; - } - - @Override - public boolean equals(Object otherObj) { - boolean isEqual = false; - - if (otherObj instanceof Data) { - Data otherData = (Data)otherObj; - - if (otherData.getType().equals(type)) { - if (value != null) { - switch(type) { - case BOOLEAN: - case INTEGER: - case DECIMAL: - case DATE: - case TEXT: - isEqual = value.equals(otherData.getValue()); - break; - case DATA: - isEqual = byteArraysEqual((byte[])value, (byte[])otherData.getValue()); - break; - } - } - else { - isEqual = (otherData.getValue() == null); - } - } - } - - return isEqual; - } - - private boolean byteArraysEqual(byte[] firstArray, byte[] secondArray) { - boolean arraysEqual = false; - - if (firstArray != null && secondArray != null) { - if (firstArray.length == secondArray.length) { - boolean mismatch = false; - - for (int i=0; i. + ******************************************************************************/ +package org.obiba.onyx.util.data; + +import java.io.Serializable; +import java.util.Date; + +public class Data implements Serializable { + + private static final long serialVersionUID = -2470483891384378865L; + + private Serializable value; + + private DataType type; + + public Data(DataType type) { + this.type = type; + } + + public Data(DataType type, Serializable value) { + this.type = type; + setValue(value); + } + + public DataType getType() { + return type; + } + + @SuppressWarnings("unchecked") + public T getValue() { + return (T) value; + } + + public void setValue(Serializable value) { + if(value != null) { + Class valueClass = value.getClass(); + + switch(type) { + case BOOLEAN: + if(!valueClass.isAssignableFrom(Boolean.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + case DATE: + if(!(value instanceof Date)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + case DECIMAL: + if(!valueClass.isAssignableFrom(Double.class) && !valueClass.isAssignableFrom(Float.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + case INTEGER: + if(!valueClass.isAssignableFrom(Long.class) && !valueClass.isAssignableFrom(Integer.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + case TEXT: + if(!valueClass.isAssignableFrom(String.class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + case DATA: + if(!valueClass.isAssignableFrom(byte[].class)) throw new IllegalArgumentException("DataType " + type + " expected, " + valueClass.getName() + " received."); + break; + + default: + break; + } + } + this.value = value; + } + + public String getValueAsString() { + if(type != DataType.DATA) { + return value != null ? value.toString() : null; + } + // TODO determine how to output a meaningful value for byte arrays + return ""; + } + + @Override + public String toString() { + return "[" + type + ":" + value + "]"; + } + + @Override + public int hashCode() { + int hashCode = 0; + + if (value != null) { + if (type != DataType.DATA) { + hashCode = value.hashCode(); + } + else { + byte[] bytes = (byte[])value; + int byteCount = bytes.length; + hashCode = byteCount != 0 ? (byteCount + bytes[0] + bytes[byteCount - 1]) % 17 : Integer.MAX_VALUE; + } + } + + return hashCode; + } + + @Override + public boolean equals(Object otherObj) { + boolean isEqual = false; + + if (otherObj instanceof Data) { + Data otherData = (Data)otherObj; + + if (otherData.getType().equals(type)) { + if (value != null) { + switch(type) { + case BOOLEAN: + case INTEGER: + case DECIMAL: + case DATE: + case TEXT: + isEqual = value.equals(otherData.getValue()); + break; + case DATA: + isEqual = byteArraysEqual((byte[])value, (byte[])otherData.getValue()); + break; + } + } + else { + isEqual = (otherData.getValue() == null); + } + } + } + + return isEqual; + } + + private boolean byteArraysEqual(byte[] firstArray, byte[] secondArray) { + boolean arraysEqual = false; + + if (firstArray != null && secondArray != null) { + if (firstArray.length == secondArray.length) { + boolean mismatch = false; + + for (int i=0; i 0) { - convertedStream.write(readBuffer, 0, bytesRead); - } - } catch(IOException couldNotReadStream) { - log.error("Error while reading binary data stream", couldNotReadStream); - throw new RuntimeException(couldNotReadStream); - } - - return new Data(DataType.DATA, convertedStream.toByteArray()); - } - - public static Data buildBinary(File file) { - - FileInputStream inputStream; - try { - inputStream = new FileInputStream(file); - } catch(FileNotFoundException fileNotFound) { - log.error("The file specified was not found", fileNotFound); - throw new RuntimeException(fileNotFound); - } - return buildBinary(inputStream); - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util.data; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DataBuilder { + + private static final Logger log = LoggerFactory.getLogger(DataBuilder.class); + + public static Data buildBoolean(Boolean booleanValue) { + return new Data(DataType.BOOLEAN, booleanValue); + } + + public static Data buildBoolean(String booleanValue) { + return new Data(DataType.BOOLEAN, Boolean.parseBoolean(booleanValue)); + } + + public static Data buildDate(Date date) { + return new Data(DataType.DATE, date); + } + + public static Data buildDate(String date) { + try { + return new Data(DataType.DATE, SimpleDateFormat.getInstance().parse(date)); + } catch(ParseException e) { + throw new IllegalArgumentException("Unable to parse date string: " + date, e); + } + } + + public static Data buildDecimal(Double doubleValue) { + return new Data(DataType.DECIMAL, doubleValue); + } + + public static Data buildDecimal(String doubleValue) { + return new Data(DataType.DECIMAL, Double.parseDouble(doubleValue)); + } + + public static Data buildDecimal(Float floatValue) { + return new Data(DataType.DECIMAL, floatValue); + } + + public static Data buildInteger(Long longValue) { + return new Data(DataType.INTEGER, longValue); + } + + public static Data buildInteger(String longValue) { + return new Data(DataType.INTEGER, Long.parseLong(longValue)); + } + + public static Data buildInteger(Integer integerValue) { + return new Data(DataType.INTEGER, integerValue); + } + + public static Data buildText(String text) { + return new Data(DataType.TEXT, text); + } + + public static Data build(DataType type, String value) { + switch(type) { + case BOOLEAN: + return buildBoolean(value); + case DECIMAL: + return buildDecimal(value); + case INTEGER: + return buildInteger(value); + case TEXT: + return buildText(value); + case DATE: + return buildDate(value); + } + return null; + } + + public static Data buildBinary(InputStream inputStream) { + + ByteArrayOutputStream convertedStream = new ByteArrayOutputStream(); + byte[] readBuffer = new byte[1024]; + int bytesRead; + + try { + while((bytesRead = inputStream.read(readBuffer)) > 0) { + convertedStream.write(readBuffer, 0, bytesRead); + } + } catch(IOException couldNotReadStream) { + log.error("Error while reading binary data stream", couldNotReadStream); + throw new RuntimeException(couldNotReadStream); + } + + return new Data(DataType.DATA, convertedStream.toByteArray()); + } + + public static Data buildBinary(File file) { + + FileInputStream inputStream; + try { + inputStream = new FileInputStream(file); + } catch(FileNotFoundException fileNotFound) { + log.error("The file specified was not found", fileNotFound); + throw new RuntimeException(fileNotFound); + } + return buildBinary(inputStream); + + } + +} diff --git a/onyx-util/src/main/java/org/obiba/onyx/util/data/DataType.java b/onyx-util/src/main/java/org/obiba/onyx/util/data/DataType.java index 0100585f6..274d343b8 100644 --- a/onyx-util/src/main/java/org/obiba/onyx/util/data/DataType.java +++ b/onyx-util/src/main/java/org/obiba/onyx/util/data/DataType.java @@ -1,5 +1,14 @@ -package org.obiba.onyx.util.data; - -public enum DataType { - BOOLEAN, DATA, DATE, DECIMAL, INTEGER, TEXT -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util.data; + +public enum DataType { + BOOLEAN, DATA, DATE, DECIMAL, INTEGER, TEXT +} diff --git a/onyx-util/src/main/java/org/obiba/onyx/util/testconfig/CustomScope.java b/onyx-util/src/main/java/org/obiba/onyx/util/testconfig/CustomScope.java index 395cce9ba..bad92ff34 100644 --- a/onyx-util/src/main/java/org/obiba/onyx/util/testconfig/CustomScope.java +++ b/onyx-util/src/main/java/org/obiba/onyx/util/testconfig/CustomScope.java @@ -1,24 +1,33 @@ -package org.obiba.onyx.util.testconfig; - -import org.springframework.beans.factory.config.Scope; -import org.springframework.beans.factory.ObjectFactory; - - -public class CustomScope implements Scope { - - public String getConversationId() { - return null; - } - - public Object get(String name, ObjectFactory objectFactory) { - return objectFactory.getObject(); - } - - public Object remove(String name) { - return null; - } - - public void registerDestructionCallback(String name, Runnable callback) { - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util.testconfig; + +import org.springframework.beans.factory.config.Scope; +import org.springframework.beans.factory.ObjectFactory; + + +public class CustomScope implements Scope { + + public String getConversationId() { + return null; + } + + public Object get(String name, ObjectFactory objectFactory) { + return objectFactory.getObject(); + } + + public Object remove(String name) { + return null; + } + + public void registerDestructionCallback(String name, Runnable callback) { + } + +} diff --git a/onyx-util/src/test/java/org/obiba/onyx/util/data/DataBuilderTest.java b/onyx-util/src/test/java/org/obiba/onyx/util/data/DataBuilderTest.java index c9514c967..75948ba9c 100644 --- a/onyx-util/src/test/java/org/obiba/onyx/util/data/DataBuilderTest.java +++ b/onyx-util/src/test/java/org/obiba/onyx/util/data/DataBuilderTest.java @@ -1,95 +1,104 @@ -package org.obiba.onyx.util.data; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Date; -import java.util.zip.Adler32; -import java.util.zip.CheckedInputStream; - -import org.junit.Assert; -import org.junit.Test; - -public class DataBuilderTest { - - @Test - public void testBuildBoolean() { - Data booleanData = DataBuilder.buildBoolean(true); - Assert.assertEquals(booleanData.getType(), DataType.BOOLEAN); - Assert.assertEquals(booleanData.getValue(), true); - } - - @Test - public void testBuildDate() { - Date date = new Date(System.currentTimeMillis()); - - Data dateData = DataBuilder.buildDate(date); - Assert.assertEquals(dateData.getType(), DataType.DATE); - Assert.assertEquals(dateData.getValue(), date); - } - - @Test - public void testBuildDecimal() { - Data decimalData = DataBuilder.buildDecimal(new Double("1.12345")); - Assert.assertEquals(decimalData.getType(), DataType.DECIMAL); - Assert.assertEquals(decimalData.getValue(), new Double("1.12345")); - - decimalData = DataBuilder.buildDecimal(new Float("1.12345")); - Assert.assertEquals(decimalData.getType(), DataType.DECIMAL); - Assert.assertEquals(decimalData.getValue(), new Float("1.12345")); - } - - @Test - public void testBuildInteger() { - Data decimalData = DataBuilder.buildInteger(new Integer("12345")); - Assert.assertEquals(decimalData.getType(), DataType.INTEGER); - Assert.assertEquals(decimalData.getValue(), new Integer("12345")); - - decimalData = DataBuilder.buildInteger(new Long("12345")); - Assert.assertEquals(decimalData.getType(), DataType.INTEGER); - Assert.assertEquals(decimalData.getValue(), new Long("12345")); - } - - @Test - public void testBuildText() { - Data decimalData = DataBuilder.buildText("this is a test"); - Assert.assertEquals(decimalData.getType(), DataType.TEXT); - Assert.assertEquals(decimalData.getValue(), "this is a test"); - } - - @Test - public void testBuildBinary() throws IOException, URISyntaxException { - - // Get source file size - File file = new File(getClass().getResource("/test.jpg").toURI()); - long fileSize = file.length(); - - // Get source file checksum - CheckedInputStream inputStream = new CheckedInputStream(new FileInputStream(file), new Adler32()); - byte[] tempBuf = new byte[1024]; - while(inputStream.read(tempBuf) > -1) { - } - - Data binaryData = DataBuilder.buildBinary(new FileInputStream(file)); - checkIntegrity(fileSize, inputStream, binaryData); - - binaryData = DataBuilder.buildBinary(file); - checkIntegrity(fileSize, inputStream, binaryData); - - } - - private void checkIntegrity(long fileSize, CheckedInputStream inputStream, Data binaryData) { - - Assert.assertEquals(binaryData.getType(), DataType.DATA); - - // Verify that source file and target byte[] are of the same length - Assert.assertEquals(((byte[]) binaryData.getValue()).length, fileSize); - - // Verify that source file and target byte[] have the same checksum - Adler32 checksumTest = new Adler32(); - checksumTest.update((byte[]) binaryData.getValue()); - Assert.assertEquals(checksumTest.getValue(), inputStream.getChecksum().getValue()); - Assert.assertEquals(((byte[]) binaryData.getValue()).length, fileSize); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.util.data; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.zip.Adler32; +import java.util.zip.CheckedInputStream; + +import org.junit.Assert; +import org.junit.Test; + +public class DataBuilderTest { + + @Test + public void testBuildBoolean() { + Data booleanData = DataBuilder.buildBoolean(true); + Assert.assertEquals(booleanData.getType(), DataType.BOOLEAN); + Assert.assertEquals(booleanData.getValue(), true); + } + + @Test + public void testBuildDate() { + Date date = new Date(System.currentTimeMillis()); + + Data dateData = DataBuilder.buildDate(date); + Assert.assertEquals(dateData.getType(), DataType.DATE); + Assert.assertEquals(dateData.getValue(), date); + } + + @Test + public void testBuildDecimal() { + Data decimalData = DataBuilder.buildDecimal(new Double("1.12345")); + Assert.assertEquals(decimalData.getType(), DataType.DECIMAL); + Assert.assertEquals(decimalData.getValue(), new Double("1.12345")); + + decimalData = DataBuilder.buildDecimal(new Float("1.12345")); + Assert.assertEquals(decimalData.getType(), DataType.DECIMAL); + Assert.assertEquals(decimalData.getValue(), new Float("1.12345")); + } + + @Test + public void testBuildInteger() { + Data decimalData = DataBuilder.buildInteger(new Integer("12345")); + Assert.assertEquals(decimalData.getType(), DataType.INTEGER); + Assert.assertEquals(decimalData.getValue(), new Integer("12345")); + + decimalData = DataBuilder.buildInteger(new Long("12345")); + Assert.assertEquals(decimalData.getType(), DataType.INTEGER); + Assert.assertEquals(decimalData.getValue(), new Long("12345")); + } + + @Test + public void testBuildText() { + Data decimalData = DataBuilder.buildText("this is a test"); + Assert.assertEquals(decimalData.getType(), DataType.TEXT); + Assert.assertEquals(decimalData.getValue(), "this is a test"); + } + + @Test + public void testBuildBinary() throws IOException, URISyntaxException { + + // Get source file size + File file = new File(getClass().getResource("/test.jpg").toURI()); + long fileSize = file.length(); + + // Get source file checksum + CheckedInputStream inputStream = new CheckedInputStream(new FileInputStream(file), new Adler32()); + byte[] tempBuf = new byte[1024]; + while(inputStream.read(tempBuf) > -1) { + } + + Data binaryData = DataBuilder.buildBinary(new FileInputStream(file)); + checkIntegrity(fileSize, inputStream, binaryData); + + binaryData = DataBuilder.buildBinary(file); + checkIntegrity(fileSize, inputStream, binaryData); + + } + + private void checkIntegrity(long fileSize, CheckedInputStream inputStream, Data binaryData) { + + Assert.assertEquals(binaryData.getType(), DataType.DATA); + + // Verify that source file and target byte[] are of the same length + Assert.assertEquals(((byte[]) binaryData.getValue()).length, fileSize); + + // Verify that source file and target byte[] have the same checksum + Adler32 checksumTest = new Adler32(); + checksumTest.update((byte[]) binaryData.getValue()); + Assert.assertEquals(checksumTest.getValue(), inputStream.getChecksum().getValue()); + Assert.assertEquals(((byte[]) binaryData.getValue()).length, fileSize); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxApplication.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxApplication.java index 62474a323..039c19fec 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxApplication.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxApplication.java @@ -1,173 +1,182 @@ -package org.obiba.onyx.webapp; - -import java.util.Map; - -import org.apache.wicket.Application; -import org.apache.wicket.Component; -import org.apache.wicket.Page; -import org.apache.wicket.Request; -import org.apache.wicket.Response; -import org.apache.wicket.RestartResponseAtInterceptPageException; -import org.apache.wicket.Session; -import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener; -import org.apache.wicket.authorization.UnauthorizedInstantiationException; -import org.apache.wicket.authorization.strategies.role.RoleAuthorizationStrategy; -import org.apache.wicket.markup.html.pages.AccessDeniedPage; -import org.apache.wicket.spring.SpringWebApplication; -import org.apache.wicket.spring.injection.annot.SpringComponentInjector; -import org.apache.wicket.util.lang.PackageName; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.authentication.UserRolesAuthorizer; -import org.obiba.onyx.webapp.config.page.ApplicationConfigurationPage; -import org.obiba.onyx.webapp.home.page.HomePage; -import org.obiba.onyx.webapp.login.page.LoginPage; -import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; -import org.obiba.onyx.webapp.stage.page.StagePage; -import org.obiba.runtime.Version; -import org.obiba.wicket.application.WebApplicationStartupListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class OnyxApplication extends SpringWebApplication implements IUnauthorizedComponentInstantiationListener { - - private final Logger log = LoggerFactory.getLogger(OnyxApplication.class); - - private UserService userService; - - private Version version; - - public UserService getUserService() { - return userService; - } - - public void setUserService(UserService userService) { - this.userService = userService; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - protected void init() { - log.info("Onyx Web Application is starting"); - super.init(); - - super.addComponentInstantiationListener(new SpringComponentInjector(this, super.internalGetApplicationContext())); - - forEachListeners(new IListenerCallback() { - public void handleListener(String beanName, WebApplicationStartupListener listener) { - listener.startup(OnyxApplication.this); - } - - public boolean terminateOnException() { - return true; - } - }); - - // nice urls - mount("participant", PackageName.forClass(ParticipantSearchPage.class)); - mount("stage", PackageName.forClass(StagePage.class)); - - getSecuritySettings().setAuthorizationStrategy(new RoleAuthorizationStrategy(new UserRolesAuthorizer())); - getSecuritySettings().setUnauthorizedComponentInstantiationListener(this); - - log.info("Onyx Web Application has been started"); - } - - @Override - protected void onDestroy() { - log.info("Onyx Web Application is stoping"); - forEachListeners(new IListenerCallback() { - public void handleListener(String beanName, WebApplicationStartupListener listener) { - listener.shutdown(OnyxApplication.this); - } - - public boolean terminateOnException() { - return false; - } - }); - log.info("Onyx Web Application has been stoped"); - super.onDestroy(); - } - - @Override - public Class getHomePage() { - User template = new User(); - template.setDeleted(false); - - if(userService.getUserCount(template) > 0) { - if(OnyxAuthenticatedSession.get().isSignedIn()) { - return HomePage.class; - } else { - return LoginPage.class; - } - } else { - return ApplicationConfigurationPage.class; - } - } - - public boolean isDevelopmentMode() { - return Application.DEVELOPMENT.equalsIgnoreCase(getConfigurationType()); - } - - /** - * Finds implementations of {@link WebApplicationStartupListener} in Spring's Application Context and executes the - * specified callback for each instance found. - * @param callback the callback implementation to call for each listener instance - */ - @SuppressWarnings("unchecked") - private void forEachListeners(IListenerCallback callback) { - Map listeners = super.internalGetApplicationContext().getBeansOfType(WebApplicationStartupListener.class); - if(listeners != null) { - for(Map.Entry entry : listeners.entrySet()) { - log.info("Executing WebApplicationStartupListener named {} of type {}", entry.getKey(), entry.getValue().getClass().getSimpleName()); - try { - callback.handleListener(entry.getKey(), entry.getValue()); - } catch(RuntimeException e) { - log.error("Error executing WebApplicationStartupListener named {} of type {}", entry.getKey(), entry.getValue().getClass().getSimpleName()); - log.error("Reported error : ", e); - if(callback.terminateOnException()) throw e; - } - } - } - } - - /** - * Called for each WebApplicationStartupListener found in Spring's application context. Implementations should either - * call startup or shutdown. - */ - private interface IListenerCallback { - public void handleListener(String beanName, WebApplicationStartupListener listener); - - public boolean terminateOnException(); - } - - @Override - public Session newSession(Request request, Response response) { - return new OnyxAuthenticatedSession(this, request); - } - - public void onUnauthorizedInstantiation(Component component) { - // If there is a sign in page class declared, and the unauthorized component is a page, but it's not the sign in - // page - if(component instanceof Page) { - if(!OnyxAuthenticatedSession.get().isSignedIn()) { - // Redirect to intercept page to let the user sign in - throw new RestartResponseAtInterceptPageException(LoginPage.class); - } else { - // User is signed in but doesn't have the proper access rights. Display error and redirect accordingly. - throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class); - } - } else { - // The component was not a page, so show an error message in the FeedbackPanel of the page - component.error("You do not have sufficient privileges to see this component."); - throw new UnauthorizedInstantiationException(component.getClass()); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp; + +import java.util.Map; + +import org.apache.wicket.Application; +import org.apache.wicket.Component; +import org.apache.wicket.Page; +import org.apache.wicket.Request; +import org.apache.wicket.Response; +import org.apache.wicket.RestartResponseAtInterceptPageException; +import org.apache.wicket.Session; +import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener; +import org.apache.wicket.authorization.UnauthorizedInstantiationException; +import org.apache.wicket.authorization.strategies.role.RoleAuthorizationStrategy; +import org.apache.wicket.markup.html.pages.AccessDeniedPage; +import org.apache.wicket.spring.SpringWebApplication; +import org.apache.wicket.spring.injection.annot.SpringComponentInjector; +import org.apache.wicket.util.lang.PackageName; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.authentication.UserRolesAuthorizer; +import org.obiba.onyx.webapp.config.page.ApplicationConfigurationPage; +import org.obiba.onyx.webapp.home.page.HomePage; +import org.obiba.onyx.webapp.login.page.LoginPage; +import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; +import org.obiba.onyx.webapp.stage.page.StagePage; +import org.obiba.runtime.Version; +import org.obiba.wicket.application.WebApplicationStartupListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OnyxApplication extends SpringWebApplication implements IUnauthorizedComponentInstantiationListener { + + private final Logger log = LoggerFactory.getLogger(OnyxApplication.class); + + private UserService userService; + + private Version version; + + public UserService getUserService() { + return userService; + } + + public void setUserService(UserService userService) { + this.userService = userService; + } + + public Version getVersion() { + return version; + } + + public void setVersion(Version version) { + this.version = version; + } + + protected void init() { + log.info("Onyx Web Application is starting"); + super.init(); + + super.addComponentInstantiationListener(new SpringComponentInjector(this, super.internalGetApplicationContext())); + + forEachListeners(new IListenerCallback() { + public void handleListener(String beanName, WebApplicationStartupListener listener) { + listener.startup(OnyxApplication.this); + } + + public boolean terminateOnException() { + return true; + } + }); + + // nice urls + mount("participant", PackageName.forClass(ParticipantSearchPage.class)); + mount("stage", PackageName.forClass(StagePage.class)); + + getSecuritySettings().setAuthorizationStrategy(new RoleAuthorizationStrategy(new UserRolesAuthorizer())); + getSecuritySettings().setUnauthorizedComponentInstantiationListener(this); + + log.info("Onyx Web Application has been started"); + } + + @Override + protected void onDestroy() { + log.info("Onyx Web Application is stoping"); + forEachListeners(new IListenerCallback() { + public void handleListener(String beanName, WebApplicationStartupListener listener) { + listener.shutdown(OnyxApplication.this); + } + + public boolean terminateOnException() { + return false; + } + }); + log.info("Onyx Web Application has been stoped"); + super.onDestroy(); + } + + @Override + public Class getHomePage() { + User template = new User(); + template.setDeleted(false); + + if(userService.getUserCount(template) > 0) { + if(OnyxAuthenticatedSession.get().isSignedIn()) { + return HomePage.class; + } else { + return LoginPage.class; + } + } else { + return ApplicationConfigurationPage.class; + } + } + + public boolean isDevelopmentMode() { + return Application.DEVELOPMENT.equalsIgnoreCase(getConfigurationType()); + } + + /** + * Finds implementations of {@link WebApplicationStartupListener} in Spring's Application Context and executes the + * specified callback for each instance found. + * @param callback the callback implementation to call for each listener instance + */ + @SuppressWarnings("unchecked") + private void forEachListeners(IListenerCallback callback) { + Map listeners = super.internalGetApplicationContext().getBeansOfType(WebApplicationStartupListener.class); + if(listeners != null) { + for(Map.Entry entry : listeners.entrySet()) { + log.info("Executing WebApplicationStartupListener named {} of type {}", entry.getKey(), entry.getValue().getClass().getSimpleName()); + try { + callback.handleListener(entry.getKey(), entry.getValue()); + } catch(RuntimeException e) { + log.error("Error executing WebApplicationStartupListener named {} of type {}", entry.getKey(), entry.getValue().getClass().getSimpleName()); + log.error("Reported error : ", e); + if(callback.terminateOnException()) throw e; + } + } + } + } + + /** + * Called for each WebApplicationStartupListener found in Spring's application context. Implementations should either + * call startup or shutdown. + */ + private interface IListenerCallback { + public void handleListener(String beanName, WebApplicationStartupListener listener); + + public boolean terminateOnException(); + } + + @Override + public Session newSession(Request request, Response response) { + return new OnyxAuthenticatedSession(this, request); + } + + public void onUnauthorizedInstantiation(Component component) { + // If there is a sign in page class declared, and the unauthorized component is a page, but it's not the sign in + // page + if(component instanceof Page) { + if(!OnyxAuthenticatedSession.get().isSignedIn()) { + // Redirect to intercept page to let the user sign in + throw new RestartResponseAtInterceptPageException(LoginPage.class); + } else { + // User is signed in but doesn't have the proper access rights. Display error and redirect accordingly. + throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class); + } + } else { + // The component was not a page, so show an error message in the FeedbackPanel of the page + component.error("You do not have sufficient privileges to see this component."); + throw new UnauthorizedInstantiationException(component.getClass()); + } + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxAuthenticatedSession.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxAuthenticatedSession.java index 651a93b66..db3e79f63 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxAuthenticatedSession.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/OnyxAuthenticatedSession.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp; import org.apache.wicket.Request; diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/action/panel/ActionsPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/action/panel/ActionsPanel.java index 8aae03143..d600ef523 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/action/panel/ActionsPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/action/panel/ActionsPanel.java @@ -1,47 +1,56 @@ -package org.obiba.onyx.webapp.action.panel; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.ResourceModel; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.wicket.action.ActionWindow; - -public class ActionsPanel extends Panel { - - private static final long serialVersionUID = 5855667390712874428L; - - @SuppressWarnings( { "serial", "serial" }) - public ActionsPanel(String id, IModel stageModel, IStageExecution exec, final ActionWindow modal) { - super(id); - setOutputMarkupId(true); - setModel(stageModel); - - RepeatingView repeating = new RepeatingView("repeating"); - add(repeating); - - for(final ActionDefinition actionDef : exec.getActionDefinitions()) { - WebMarkupContainer item = new WebMarkupContainer(repeating.newChildId()); - repeating.add(item); - - AjaxLink link = new AjaxLink("link") { - - @Override - public void onClick(AjaxRequestTarget target) { - modal.show(target, ActionsPanel.this.getModel(), actionDef); - } - - }; - link.add(new Label("action", new ResourceModel(actionDef.getLabel(), actionDef.getLabel()))); - item.add(link); - - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.action.panel; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.ResourceModel; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.wicket.action.ActionWindow; + +public class ActionsPanel extends Panel { + + private static final long serialVersionUID = 5855667390712874428L; + + @SuppressWarnings( { "serial", "serial" }) + public ActionsPanel(String id, IModel stageModel, IStageExecution exec, final ActionWindow modal) { + super(id); + setOutputMarkupId(true); + setModel(stageModel); + + RepeatingView repeating = new RepeatingView("repeating"); + add(repeating); + + for(final ActionDefinition actionDef : exec.getActionDefinitions()) { + WebMarkupContainer item = new WebMarkupContainer(repeating.newChildId()); + repeating.add(item); + + AjaxLink link = new AjaxLink("link") { + + @Override + public void onClick(AjaxRequestTarget target) { + modal.show(target, ActionsPanel.this.getModel(), actionDef); + } + + }; + link.add(new Label("action", new ResourceModel(actionDef.getLabel(), actionDef.getLabel()))); + item.add(link); + + } + + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/authentication/UserRolesAuthorizer.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/authentication/UserRolesAuthorizer.java index 5f759c8e4..533569ffc 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/authentication/UserRolesAuthorizer.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/authentication/UserRolesAuthorizer.java @@ -1,15 +1,24 @@ -package org.obiba.onyx.webapp.authentication; - -import org.apache.wicket.authorization.strategies.role.IRoleCheckingStrategy; -import org.apache.wicket.authorization.strategies.role.Roles; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; - -public class UserRolesAuthorizer implements IRoleCheckingStrategy { - - public UserRolesAuthorizer() {} - - public final boolean hasAnyRole(final Roles componentRoles) { - final Roles userRoles = OnyxAuthenticatedSession.get().getRoles(); - return userRoles != null && userRoles.hasAnyRole(componentRoles); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.authentication; + +import org.apache.wicket.authorization.strategies.role.IRoleCheckingStrategy; +import org.apache.wicket.authorization.strategies.role.Roles; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; + +public class UserRolesAuthorizer implements IRoleCheckingStrategy { + + public UserRolesAuthorizer() {} + + public final boolean hasAnyRole(final Roles componentRoles) { + final Roles userRoles = OnyxAuthenticatedSession.get().getRoles(); + return userRoles != null && userRoles.hasAnyRole(componentRoles); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/page/BasePage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/page/BasePage.java index b04d5e527..f6c5fa796 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/page/BasePage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/page/BasePage.java @@ -1,68 +1,77 @@ -package org.obiba.onyx.webapp.base.page; - -import java.util.Locale; - -import org.apache.wicket.Application; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.IAjaxIndicatorAware; -import org.apache.wicket.markup.html.IHeaderContributor; -import org.apache.wicket.markup.html.IHeaderResponse; -import org.apache.wicket.markup.html.WebPage; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.resources.JavascriptResourceReference; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.webapp.OnyxApplication; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.webapp.base.panel.HeaderPanel; -import org.obiba.onyx.webapp.base.panel.MenuBar; - -public abstract class BasePage extends WebPage implements IAjaxIndicatorAware, IHeaderContributor { - - private FeedbackPanel feedbackPanel; - - public BasePage() { - super(); - - // Create feedback panel and add to page - feedbackPanel = new FeedbackPanel("feedback"); - feedbackPanel.setOutputMarkupId(true); - add(feedbackPanel); - - if(((OnyxAuthenticatedSession) getSession()).isSignedIn()) { - add(new HeaderPanel("header")); - } else { - add(new EmptyPanel("header")); - } - - add(new MenuBar("menuBar")); - add(new Label("version", ((OnyxApplication)getApplication()).getVersion().toString())); - - add(new Label("baseAjaxIndicator", new StringResourceModel("Processing", this, null))); - } - - public void setMenuBarVisible(boolean visible) { - get("menuBar").setVisible(visible); - } - - protected FeedbackPanel getFeedbackPanel() { - return feedbackPanel; - } - - /** - * @see org.apache.wicket.ajax.IAjaxIndicatorAware#getAjaxIndicatorMarkupId() - */ - public String getAjaxIndicatorMarkupId() { - return "base-ajax-indicator"; - } - - public void onLanguageUpdate(Locale language, AjaxRequestTarget target) { - setResponsePage(getPage()); - } - - public void renderHead(IHeaderResponse response) { - response.renderJavascriptReference(new JavascriptResourceReference(BasePage.class, "onyx.js")); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.base.page; + +import java.util.Locale; + +import org.apache.wicket.Application; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.IAjaxIndicatorAware; +import org.apache.wicket.markup.html.IHeaderContributor; +import org.apache.wicket.markup.html.IHeaderResponse; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.resources.JavascriptResourceReference; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.webapp.OnyxApplication; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.webapp.base.panel.HeaderPanel; +import org.obiba.onyx.webapp.base.panel.MenuBar; + +public abstract class BasePage extends WebPage implements IAjaxIndicatorAware, IHeaderContributor { + + private FeedbackPanel feedbackPanel; + + public BasePage() { + super(); + + // Create feedback panel and add to page + feedbackPanel = new FeedbackPanel("feedback"); + feedbackPanel.setOutputMarkupId(true); + add(feedbackPanel); + + if(((OnyxAuthenticatedSession) getSession()).isSignedIn()) { + add(new HeaderPanel("header")); + } else { + add(new EmptyPanel("header")); + } + + add(new MenuBar("menuBar")); + add(new Label("version", ((OnyxApplication)getApplication()).getVersion().toString())); + + add(new Label("baseAjaxIndicator", new StringResourceModel("Processing", this, null))); + } + + public void setMenuBarVisible(boolean visible) { + get("menuBar").setVisible(visible); + } + + protected FeedbackPanel getFeedbackPanel() { + return feedbackPanel; + } + + /** + * @see org.apache.wicket.ajax.IAjaxIndicatorAware#getAjaxIndicatorMarkupId() + */ + public String getAjaxIndicatorMarkupId() { + return "base-ajax-indicator"; + } + + public void onLanguageUpdate(Locale language, AjaxRequestTarget target) { + setResponsePage(getPage()); + } + + public void renderHead(IHeaderResponse response) { + response.renderJavascriptReference(new JavascriptResourceReference(BasePage.class, "onyx.js")); + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/AjaxLanguageChoicePanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/AjaxLanguageChoicePanel.java index 8a78bce80..0daa84170 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/AjaxLanguageChoicePanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/AjaxLanguageChoicePanel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.base.panel; import java.util.Arrays; diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/HeaderPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/HeaderPanel.java index 6d63ca124..fcebf78e4 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/HeaderPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/HeaderPanel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.base.panel; import java.io.Serializable; diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBar.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBar.java index b60d3c236..7d78d5357 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBar.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBar.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.base.panel; import java.util.Arrays; @@ -57,4 +66,4 @@ protected void onLanguageUpdate(Locale language, AjaxRequestTarget target) { languageSelect.setSelectedLanguage(getSession().getLocale()); add(languageSelect); } -} \ No newline at end of file +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBuilder.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBuilder.java index b33718aee..b0deac0b5 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBuilder.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuBuilder.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.base.panel; import java.util.ArrayList; diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuItem.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuItem.java index 7ad540150..9e1018e38 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuItem.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/base/panel/MenuItem.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.base.panel; import java.util.ArrayList; @@ -66,4 +75,4 @@ public void setRoles(Roles pRoles) { public Roles getRoles() { return roles; } -} \ No newline at end of file +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/config/page/ApplicationConfigurationPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/config/page/ApplicationConfigurationPage.java index 569f0f9ef..a03dad818 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/config/page/ApplicationConfigurationPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/config/page/ApplicationConfigurationPage.java @@ -1,255 +1,264 @@ -package org.obiba.onyx.webapp.config.page; - -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.ServletContext; - -import org.apache.wicket.RequestCycle; -import org.apache.wicket.Session; -import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField; -import org.apache.wicket.markup.html.form.Button; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.PasswordTextField; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.form.upload.FileUpload; -import org.apache.wicket.markup.html.form.upload.FileUploadField; -import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.lang.Bytes; -import org.apache.wicket.validation.IErrorMessageSource; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidationError; -import org.apache.wicket.validation.validator.AbstractValidator; -import org.apache.wicket.validation.validator.EmailAddressValidator; -import org.apache.wicket.validation.validator.PatternValidator; -import org.apache.wicket.validation.validator.StringValidator; -import org.obiba.onyx.core.domain.application.ApplicationConfiguration; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ApplicationConfigurationService; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ApplicationConfigurationPage extends BasePage { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ApplicationConfigurationPage.class); - - @SpringBean - private ApplicationConfigurationService appConfigService; - - @SpringBean - private UserService userService; - - public ApplicationConfigurationPage() { - add(new ConfigurationForm("configurationForm")); - } - - private class ConfigurationForm extends Form { - - private static final long serialVersionUID = -8937533839333908882L; - - ConfigurationFormModel model = new ConfigurationFormModel(); - - FileUploadField studyLogo; - - @SuppressWarnings("serial") - public ConfigurationForm(String name) { - super(name); - - TextField studyName = new TextField("studyName", new PropertyModel(model, "config.studyName")); - studyName.add(new RequiredFormFieldBehavior()); - add(studyName.add(StringValidator.maximumLength(30))); - - TextField siteName = new TextField("siteName", new PropertyModel(model, "config.siteName")); - siteName.add(new RequiredFormFieldBehavior()); - add(siteName.add(StringValidator.maximumLength(30))); - - TextField siteNo = new TextField("siteNo", new PropertyModel(model, "config.siteNo")); - siteNo.add(new RequiredFormFieldBehavior()); - add(siteNo.add(StringValidator.maximumLength(30))); - - TextField administratorName = new TextField("lastName", new PropertyModel(model, "user.lastName")); - administratorName.add(new RequiredFormFieldBehavior()); - add(administratorName.add(StringValidator.maximumLength(30))); - - TextField administratorFirstName = new TextField("firstName", new PropertyModel(model, "user.firstName")); - administratorFirstName.add(new RequiredFormFieldBehavior()); - add(administratorFirstName.add(StringValidator.maximumLength(30))); - - TextField administratorUserLogin = new TextField("login", new PropertyModel(model, "user.login")); - administratorUserLogin.add(new RequiredFormFieldBehavior()); - add(administratorUserLogin.add(StringValidator.maximumLength(30))); - - PasswordTextField administratorUserPassword = new PasswordTextField("password", new PropertyModel(model, "user.password")); - administratorUserPassword.add(new RequiredFormFieldBehavior()); - add(administratorUserPassword.add(StringValidator.maximumLength(30))); - - PasswordTextField administratorUserPasswordConfirm = new PasswordTextField("confirmPassword", new Model("")); - administratorUserPasswordConfirm.add(new RequiredFormFieldBehavior()); - add(administratorUserPasswordConfirm.add(StringValidator.maximumLength(30))); - - // Validate that the password and the confirmed password are the same. - add(new EqualPasswordInputValidator(administratorUserPassword, administratorUserPasswordConfirm)); - - TextField administratorEmail = new TextField("email", new PropertyModel(model, "user.email")); - add(administratorEmail.add(EmailAddressValidator.getInstance())); - add(administratorEmail.add(StringValidator.maximumLength(30))); - - studyLogo = new FileUploadField("studyLogo"); - - // Make sure that the file uploaded is either a "jpg" or a "gif". - add(studyLogo.add(new PatternValidator(".*((\\.jpg)|(\\.gif))")).setRequired(true)); - - // Set max size of upload to two megabytes. A logo should not be bigger than that!! - setMaxSize(Bytes.megabytes(2)); - setMultiPart(true); - - AutoCompleteTextField participantUpdateDirectory = new AutoCompleteTextField("participantUpdateDirectory", new PropertyModel(model, "participantDirectoryPath")) { - - @SuppressWarnings("unchecked") - protected Iterator getChoices(String input) { - File dir = new File(input); - List choices = new ArrayList(); - if(dir.exists() && dir.isDirectory()) { - choices.add(dir.getAbsolutePath()); - for(File subDir : dir.listFiles()) { - if(subDir.isDirectory() && !subDir.getName().startsWith(".")) { - choices.add(subDir.getAbsolutePath()); - } - } - } - return choices.iterator(); - } - - }; - participantUpdateDirectory.add(new AbstractValidator() { - - protected void onValidate(IValidatable validatable) { - File dir = new File((String) validatable.getValue()); - if(!dir.exists()) { - validatable.error(new ParticipantsListDirectoryValidationError("ParticipantsListRepositoryDoesNotExist")); - } else if(!dir.isDirectory()) { - validatable.error(new ParticipantsListDirectoryValidationError("ParticipantsListRepositoryIsNotDirectory")); - } - } - - }); - participantUpdateDirectory.add(new RequiredFormFieldBehavior()); - add(participantUpdateDirectory); - - add(new Button("saveButton")); - } - - public void onSubmit() { - saveConfiguration(); - uploadStudyLogo(); - setResponsePage(getApplication().getHomePage()); - } - - private void uploadStudyLogo() { - - // Retrieve the uploaded logo. - FileUpload upload = studyLogo.getFileUpload(); - - // Attempt to save file only if exist and was successfully transfered. - if(upload != null) { - - // Save the logo in the "images" folder of the web application. - ServletContext context = ((WebApplication) RequestCycle.get().getApplication()).getServletContext(); - File newFile = new File(context.getRealPath("/images"), "studyLogo.jpg"); - - try { - - newFile.createNewFile(); - upload.writeTo(newFile); - - } catch(Exception e) { - throw new IllegalStateException("Unable to write logo file", e); - } finally { - try { - upload.closeStreams(); - } catch(Exception e) { - // Ignore exception. - } - } - } - - } - - private void saveConfiguration() { - - // set up the roles - Role adminRole = userService.createRole(Role.SYSTEM_ADMINISTRATOR); - userService.createRole(Role.PARTICIPANT_MANAGER); - userService.createRole(Role.DATA_COLLECTION_OPERATOR); - - // Setup administrator user. - User user = model.getUser(); - user.setPassword(User.digest(user.getPassword())); - user.addRole(adminRole); - user.setLanguage(Session.get().getLocale()); - user.setDeleted(false); - user.setStatus(Status.ACTIVE); - userService.createUser(user); - - // Save initial application configuration. - appConfigService.createApplicationConfiguration(model.getConfig()); - } - - } - - private class ConfigurationFormModel implements Serializable { - - private static final long serialVersionUID = -3683550452902579885L; - - private User user = new User(); - - private ApplicationConfiguration config = new ApplicationConfiguration(); - - public ApplicationConfiguration getConfig() { - return config; - } - - public User getUser() { - return user; - } - - public void setParticipantDirectoryPath(String path) { - String dirPath = new File(path).getAbsolutePath(); - log.info("participantDirectoryPath={}", dirPath); - config.setParticipantDirectoryPath(dirPath); - } - - public String getParticipantDirectoryPath() { - return config.getParticipantDirectoryPath(); - } - } - - @SuppressWarnings("serial") - private class ParticipantsListDirectoryValidationError implements IValidationError, Serializable { - - private String key; - - public ParticipantsListDirectoryValidationError(String key) { - this.key = key; - } - - public String getErrorMessage(IErrorMessageSource messageSource) { - return ApplicationConfigurationPage.this.getString(key); - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.config.page; + +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.apache.wicket.RequestCycle; +import org.apache.wicket.Session; +import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField; +import org.apache.wicket.markup.html.form.Button; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.PasswordTextField; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.form.upload.FileUpload; +import org.apache.wicket.markup.html.form.upload.FileUploadField; +import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.lang.Bytes; +import org.apache.wicket.validation.IErrorMessageSource; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidationError; +import org.apache.wicket.validation.validator.AbstractValidator; +import org.apache.wicket.validation.validator.EmailAddressValidator; +import org.apache.wicket.validation.validator.PatternValidator; +import org.apache.wicket.validation.validator.StringValidator; +import org.obiba.onyx.core.domain.application.ApplicationConfiguration; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ApplicationConfigurationService; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ApplicationConfigurationPage extends BasePage { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ApplicationConfigurationPage.class); + + @SpringBean + private ApplicationConfigurationService appConfigService; + + @SpringBean + private UserService userService; + + public ApplicationConfigurationPage() { + add(new ConfigurationForm("configurationForm")); + } + + private class ConfigurationForm extends Form { + + private static final long serialVersionUID = -8937533839333908882L; + + ConfigurationFormModel model = new ConfigurationFormModel(); + + FileUploadField studyLogo; + + @SuppressWarnings("serial") + public ConfigurationForm(String name) { + super(name); + + TextField studyName = new TextField("studyName", new PropertyModel(model, "config.studyName")); + studyName.add(new RequiredFormFieldBehavior()); + add(studyName.add(StringValidator.maximumLength(30))); + + TextField siteName = new TextField("siteName", new PropertyModel(model, "config.siteName")); + siteName.add(new RequiredFormFieldBehavior()); + add(siteName.add(StringValidator.maximumLength(30))); + + TextField siteNo = new TextField("siteNo", new PropertyModel(model, "config.siteNo")); + siteNo.add(new RequiredFormFieldBehavior()); + add(siteNo.add(StringValidator.maximumLength(30))); + + TextField administratorName = new TextField("lastName", new PropertyModel(model, "user.lastName")); + administratorName.add(new RequiredFormFieldBehavior()); + add(administratorName.add(StringValidator.maximumLength(30))); + + TextField administratorFirstName = new TextField("firstName", new PropertyModel(model, "user.firstName")); + administratorFirstName.add(new RequiredFormFieldBehavior()); + add(administratorFirstName.add(StringValidator.maximumLength(30))); + + TextField administratorUserLogin = new TextField("login", new PropertyModel(model, "user.login")); + administratorUserLogin.add(new RequiredFormFieldBehavior()); + add(administratorUserLogin.add(StringValidator.maximumLength(30))); + + PasswordTextField administratorUserPassword = new PasswordTextField("password", new PropertyModel(model, "user.password")); + administratorUserPassword.add(new RequiredFormFieldBehavior()); + add(administratorUserPassword.add(StringValidator.maximumLength(30))); + + PasswordTextField administratorUserPasswordConfirm = new PasswordTextField("confirmPassword", new Model("")); + administratorUserPasswordConfirm.add(new RequiredFormFieldBehavior()); + add(administratorUserPasswordConfirm.add(StringValidator.maximumLength(30))); + + // Validate that the password and the confirmed password are the same. + add(new EqualPasswordInputValidator(administratorUserPassword, administratorUserPasswordConfirm)); + + TextField administratorEmail = new TextField("email", new PropertyModel(model, "user.email")); + add(administratorEmail.add(EmailAddressValidator.getInstance())); + add(administratorEmail.add(StringValidator.maximumLength(30))); + + studyLogo = new FileUploadField("studyLogo"); + + // Make sure that the file uploaded is either a "jpg" or a "gif". + add(studyLogo.add(new PatternValidator(".*((\\.jpg)|(\\.gif))")).setRequired(true)); + + // Set max size of upload to two megabytes. A logo should not be bigger than that!! + setMaxSize(Bytes.megabytes(2)); + setMultiPart(true); + + AutoCompleteTextField participantUpdateDirectory = new AutoCompleteTextField("participantUpdateDirectory", new PropertyModel(model, "participantDirectoryPath")) { + + @SuppressWarnings("unchecked") + protected Iterator getChoices(String input) { + File dir = new File(input); + List choices = new ArrayList(); + if(dir.exists() && dir.isDirectory()) { + choices.add(dir.getAbsolutePath()); + for(File subDir : dir.listFiles()) { + if(subDir.isDirectory() && !subDir.getName().startsWith(".")) { + choices.add(subDir.getAbsolutePath()); + } + } + } + return choices.iterator(); + } + + }; + participantUpdateDirectory.add(new AbstractValidator() { + + protected void onValidate(IValidatable validatable) { + File dir = new File((String) validatable.getValue()); + if(!dir.exists()) { + validatable.error(new ParticipantsListDirectoryValidationError("ParticipantsListRepositoryDoesNotExist")); + } else if(!dir.isDirectory()) { + validatable.error(new ParticipantsListDirectoryValidationError("ParticipantsListRepositoryIsNotDirectory")); + } + } + + }); + participantUpdateDirectory.add(new RequiredFormFieldBehavior()); + add(participantUpdateDirectory); + + add(new Button("saveButton")); + } + + public void onSubmit() { + saveConfiguration(); + uploadStudyLogo(); + setResponsePage(getApplication().getHomePage()); + } + + private void uploadStudyLogo() { + + // Retrieve the uploaded logo. + FileUpload upload = studyLogo.getFileUpload(); + + // Attempt to save file only if exist and was successfully transfered. + if(upload != null) { + + // Save the logo in the "images" folder of the web application. + ServletContext context = ((WebApplication) RequestCycle.get().getApplication()).getServletContext(); + File newFile = new File(context.getRealPath("/images"), "studyLogo.jpg"); + + try { + + newFile.createNewFile(); + upload.writeTo(newFile); + + } catch(Exception e) { + throw new IllegalStateException("Unable to write logo file", e); + } finally { + try { + upload.closeStreams(); + } catch(Exception e) { + // Ignore exception. + } + } + } + + } + + private void saveConfiguration() { + + // set up the roles + Role adminRole = userService.createRole(Role.SYSTEM_ADMINISTRATOR); + userService.createRole(Role.PARTICIPANT_MANAGER); + userService.createRole(Role.DATA_COLLECTION_OPERATOR); + + // Setup administrator user. + User user = model.getUser(); + user.setPassword(User.digest(user.getPassword())); + user.addRole(adminRole); + user.setLanguage(Session.get().getLocale()); + user.setDeleted(false); + user.setStatus(Status.ACTIVE); + userService.createUser(user); + + // Save initial application configuration. + appConfigService.createApplicationConfiguration(model.getConfig()); + } + + } + + private class ConfigurationFormModel implements Serializable { + + private static final long serialVersionUID = -3683550452902579885L; + + private User user = new User(); + + private ApplicationConfiguration config = new ApplicationConfiguration(); + + public ApplicationConfiguration getConfig() { + return config; + } + + public User getUser() { + return user; + } + + public void setParticipantDirectoryPath(String path) { + String dirPath = new File(path).getAbsolutePath(); + log.info("participantDirectoryPath={}", dirPath); + config.setParticipantDirectoryPath(dirPath); + } + + public String getParticipantDirectoryPath() { + return config.getParticipantDirectoryPath(); + } + } + + @SuppressWarnings("serial") + private class ParticipantsListDirectoryValidationError implements IValidationError, Serializable { + + private String key; + + public ParticipantsListDirectoryValidationError(String key) { + this.key = key; + } + + public String getErrorMessage(IErrorMessageSource messageSource) { + return ApplicationConfigurationPage.this.getString(key); + } + + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/home/page/HomePage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/home/page/HomePage.java index 9e14408e4..f68392a9e 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/home/page/HomePage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/home/page/HomePage.java @@ -1,73 +1,82 @@ -package org.obiba.onyx.webapp.home.page; - -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.markup.html.form.Button; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.link.BookmarkablePageLink; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.participant.page.InterviewPage; -import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; - -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) -public class HomePage extends BasePage { - - @SpringBean - private EntityQueryService queryService; - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SuppressWarnings("serial") - public HomePage() { - super(); - - add(new ParticipantSearchForm("configurationForm")); - - add(new BookmarkablePageLink("search", ParticipantSearchPage.class)); - - } - - private class ParticipantSearchForm extends Form { - - private static final long serialVersionUID = 1L; - - public ParticipantSearchForm(String id) { - super(id); - - setModel(new Model(new Participant())); - - TextField barCode = new TextField("barCode", new PropertyModel(getModelObject(), "barcode")); - barCode.add(new RequiredFormFieldBehavior()); - barCode.setLabel(new StringResourceModel("ParticipantCode", HomePage.this, null)); - add(barCode); - - add(new Button("submit")); - } - - @Override - protected void onSubmit() { - Participant template = (Participant) ParticipantSearchForm.this.getModelObject(); - Participant participant = queryService.matchOne(template); - - // Participant found, display interview page. - if(participant != null) { - activeInterviewService.setParticipant(participant); - setResponsePage(InterviewPage.class); - - // Not found, display error message in feedback panel. - } else { - error((new StringResourceModel("ParticipantNotFound", this, ParticipantSearchForm.this.getModel())).getString()); - } - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.home.page; + +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.form.Button; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.link.BookmarkablePageLink; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.participant.page.InterviewPage; +import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; + +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) +public class HomePage extends BasePage { + + @SpringBean + private EntityQueryService queryService; + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SuppressWarnings("serial") + public HomePage() { + super(); + + add(new ParticipantSearchForm("configurationForm")); + + add(new BookmarkablePageLink("search", ParticipantSearchPage.class)); + + } + + private class ParticipantSearchForm extends Form { + + private static final long serialVersionUID = 1L; + + public ParticipantSearchForm(String id) { + super(id); + + setModel(new Model(new Participant())); + + TextField barCode = new TextField("barCode", new PropertyModel(getModelObject(), "barcode")); + barCode.add(new RequiredFormFieldBehavior()); + barCode.setLabel(new StringResourceModel("ParticipantCode", HomePage.this, null)); + add(barCode); + + add(new Button("submit")); + } + + @Override + protected void onSubmit() { + Participant template = (Participant) ParticipantSearchForm.this.getModelObject(); + Participant participant = queryService.matchOne(template); + + // Participant found, display interview page. + if(participant != null) { + activeInterviewService.setParticipant(participant); + setResponsePage(InterviewPage.class); + + // Not found, display error message in feedback panel. + } else { + error((new StringResourceModel("ParticipantNotFound", this, ParticipantSearchForm.this.getModel())).getString()); + } + } + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/page/LoginPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/page/LoginPage.java index f0d7376e8..25d6c2f46 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/page/LoginPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/page/LoginPage.java @@ -1,17 +1,26 @@ -package org.obiba.onyx.webapp.login.page; - - -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.login.panel.LoginPanel; - - -public class LoginPage extends BasePage { - - private static final long serialVersionUID = -3536960410263657341L; - - public LoginPage() { - add(new LoginPanel("loginPanel")); - } - - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.login.page; + + +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.login.panel.LoginPanel; + + +public class LoginPage extends BasePage { + + private static final long serialVersionUID = -3536960410263657341L; + + public LoginPage() { + add(new LoginPanel("loginPanel")); + } + + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/panel/LoginPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/panel/LoginPanel.java index 3f9ac365e..542b8bb63 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/panel/LoginPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/login/panel/LoginPanel.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ package org.obiba.onyx.webapp.login.panel; import org.apache.wicket.authentication.panel.SignInPanel; @@ -44,4 +53,4 @@ public void onSignInSucceeded() { setResponsePage(getApplication().getHomePage()); } -} \ No newline at end of file +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/panel/OnyxEntityList.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/panel/OnyxEntityList.java index b6aefa272..ae1275e42 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/panel/OnyxEntityList.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/panel/OnyxEntityList.java @@ -1,27 +1,36 @@ -package org.obiba.onyx.webapp.panel; - -import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; -import org.apache.wicket.model.IModel; -import org.obiba.wicket.markup.html.table.EntityListTablePanel; -import org.obiba.wicket.markup.html.table.IColumnProvider; - -public class OnyxEntityList extends EntityListTablePanel { - - private static final long serialVersionUID = 7891474467194294293L; - - public OnyxEntityList(String id, Class type, IColumnProvider columns, IModel title) { - super(id, type, columns, title); - setAllowColumnSelection(false); - } - - public OnyxEntityList(String id, T template, IColumnProvider columns, IModel title) { - super(id, template, columns, title); - setAllowColumnSelection(false); - } - - public OnyxEntityList(String id, SortableDataProvider dataProvider, IColumnProvider columns, IModel title) { - super(id, dataProvider, columns, title, 50); - setAllowColumnSelection(false); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.panel; + +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.model.IModel; +import org.obiba.wicket.markup.html.table.EntityListTablePanel; +import org.obiba.wicket.markup.html.table.IColumnProvider; + +public class OnyxEntityList extends EntityListTablePanel { + + private static final long serialVersionUID = 7891474467194294293L; + + public OnyxEntityList(String id, Class type, IColumnProvider columns, IModel title) { + super(id, type, columns, title); + setAllowColumnSelection(false); + } + + public OnyxEntityList(String id, T template, IColumnProvider columns, IModel title) { + super(id, template, columns, title); + setAllowColumnSelection(false); + } + + public OnyxEntityList(String id, SortableDataProvider dataProvider, IColumnProvider columns, IModel title) { + super(id, dataProvider, columns, title, 50); + setAllowColumnSelection(false); + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/InterviewPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/InterviewPage.java index d54cc4432..351cc11da 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/InterviewPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/InterviewPage.java @@ -1,222 +1,231 @@ -package org.obiba.onyx.webapp.participant.page; - -import java.io.Serializable; -import java.util.Date; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionDefinition; -import org.obiba.onyx.engine.ActionDefinitionBuilder; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.participant.panel.CommentsModalPanel; -import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; -import org.obiba.onyx.webapp.stage.panel.StageSelectionPanel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; - -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) -public class InterviewPage extends BasePage { - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private EntityQueryService queryService; - - private Label commentsCount; - - AjaxLink viewComments; - - public InterviewPage() { - super(); - - if(activeInterviewService.getParticipant() == null || activeInterviewService.getInterview() == null) { - setResponsePage(WebApplication.get().getHomePage()); - } else { - final Interview interview = activeInterviewService.setInterviewOperator(OnyxAuthenticatedSession.get().getUser()); - Participant participant = activeInterviewService.getParticipant(); - - add(new ParticipantPanel("participant", new DetachableEntityModel(queryService, participant), true)); - - // Create modal comments window - final ModalWindow commentsWindow; - add(commentsWindow = new ModalWindow("addCommentsModal")); - commentsWindow.setTitle(new StringResourceModel("CommentsWindow", this, null)); - commentsWindow.setInitialHeight(400); - commentsWindow.setInitialWidth(600); - - commentsWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - - private static final long serialVersionUID = 1L; - - public void onClose(AjaxRequestTarget target) { - - } - }); - - // Add view interview comments action - add(viewComments = new AjaxLink("viewComments") { - - private static final long serialVersionUID = 1L; - - public void onClick(AjaxRequestTarget target) { - commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { - private static final long serialVersionUID = 1L; - - @Override - public void onAddComments(AjaxRequestTarget target) { - InterviewPage.this.updateCommentsCount(); - target.addComponent(InterviewPage.this.commentsCount); - } - - }); - commentsWindow.show(target); - } - }); - - // Initialize comments counter - updateCommentsCount(); - - // Add create interview comments action - add(new AjaxLink("addComments") { - - private static final long serialVersionUID = 1L; - - public void onClick(AjaxRequestTarget target) { - commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { - private static final long serialVersionUID = 1L; - - @Override - public void onAddComments(AjaxRequestTarget target) { - InterviewPage.this.updateCommentsCount(); - target.addComponent(InterviewPage.this.commentsCount); - } - - }); - commentsWindow.show(target); - } - }); - - ActiveInterviewModel interviewModel = new ActiveInterviewModel(); - - KeyValueDataPanel kvPanel = new KeyValueDataPanel("interview"); - kvPanel.addRow(new StringResourceModel("StartDate", this, null), new PropertyModel(interviewModel, "startDate")); - kvPanel.addRow(new StringResourceModel("EndDate", this, null), new PropertyModel(interviewModel, "endDate")); - kvPanel.addRow(new StringResourceModel("Status", this, null), new PropertyModel(interviewModel, "status")); - add(kvPanel); - - // Interview cancellation - - final ActionDefinition cancelInterviewDef = ActionDefinitionBuilder.create(ActionType.STOP, new StringResourceModel("CancelInterview", this, null).getString()).setDescription(new StringResourceModel("ExplainCancelInterview", this, null).getString()).setAskPassword(true).getActionDefinition(); - cancelInterviewDef.addReasons(new String[] { "Reason1", "Reason2", "Reason3", "Other" }); - cancelInterviewDef.setDefaultReason("Reason1"); - - final ActionWindow interviewActionWindow = new ActionWindow("modal") { - - private static final long serialVersionUID = 1L; - - @Override - public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { - activeInterviewService.setStatus(InterviewStatus.CANCELLED); - setResponsePage(InterviewPage.class); - } - - }; - add(interviewActionWindow); - - AjaxLink link = new AjaxLink("cancelInterview") { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - interviewActionWindow.show(target, null, cancelInterviewDef); - } - }; - - if(interview.getStatus().equals(InterviewStatus.CANCELLED)) link.setVisible(false); - else - link.setVisible(true); - - add(link); - - add(new StageSelectionPanel("stage-list", getFeedbackPanel()) { - - private static final long serialVersionUID = 1L; - - @Override - public void onViewComments(AjaxRequestTarget target) { - commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { - - private static final long serialVersionUID = 1L; - - @Override - public void onAddComments(AjaxRequestTarget target) { - InterviewPage.this.updateCommentsCount(); - target.addComponent(InterviewPage.this.commentsCount); - } - - }); - commentsWindow.show(target); - } - - @Override - public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { - InterviewPage.this.updateCommentsCount(); - target.addComponent(InterviewPage.this.commentsCount); - } - - }); - } - } - - public void updateCommentsCount() { - viewComments.addOrReplace(commentsCount = new Label("commentsCount", String.valueOf(activeInterviewService.getInterviewComments().size()))); - commentsCount.setOutputMarkupId(true); - } - - @SuppressWarnings("serial") - private class ActiveInterviewModel implements Serializable { - - public String getStartDate() { - Date date = activeInterviewService.getInterview().getStartDate(); - return date == null ? "" : DateModelUtils.getShortDateTimeModel(new Model(date)).getObject().toString(); - } - - public String getEndDate() { - Date date = activeInterviewService.getInterview().getEndDate(); - return date == null ? "" : DateModelUtils.getShortDateTimeModel(new Model(date)).getObject().toString(); - } - - public String getStatus() { - Action act = activeInterviewService.getStatusAction(); - ValueMap map = null; - if(act != null && act.getEventReason() != null) { - // TODO localize the reason - map = new ValueMap("reason=" + act.getEventReason()); - } - return (new StringResourceModel("InterviewStatus." + activeInterviewService.getInterview().getStatus(), InterviewPage.this, new Model(map))).getString(); - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.page; + +import java.io.Serializable; +import java.util.Date; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionDefinition; +import org.obiba.onyx.engine.ActionDefinitionBuilder; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.participant.panel.CommentsModalPanel; +import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; +import org.obiba.onyx.webapp.stage.panel.StageSelectionPanel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; + +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) +public class InterviewPage extends BasePage { + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private EntityQueryService queryService; + + private Label commentsCount; + + AjaxLink viewComments; + + public InterviewPage() { + super(); + + if(activeInterviewService.getParticipant() == null || activeInterviewService.getInterview() == null) { + setResponsePage(WebApplication.get().getHomePage()); + } else { + final Interview interview = activeInterviewService.setInterviewOperator(OnyxAuthenticatedSession.get().getUser()); + Participant participant = activeInterviewService.getParticipant(); + + add(new ParticipantPanel("participant", new DetachableEntityModel(queryService, participant), true)); + + // Create modal comments window + final ModalWindow commentsWindow; + add(commentsWindow = new ModalWindow("addCommentsModal")); + commentsWindow.setTitle(new StringResourceModel("CommentsWindow", this, null)); + commentsWindow.setInitialHeight(400); + commentsWindow.setInitialWidth(600); + + commentsWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { + + private static final long serialVersionUID = 1L; + + public void onClose(AjaxRequestTarget target) { + + } + }); + + // Add view interview comments action + add(viewComments = new AjaxLink("viewComments") { + + private static final long serialVersionUID = 1L; + + public void onClick(AjaxRequestTarget target) { + commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { + private static final long serialVersionUID = 1L; + + @Override + public void onAddComments(AjaxRequestTarget target) { + InterviewPage.this.updateCommentsCount(); + target.addComponent(InterviewPage.this.commentsCount); + } + + }); + commentsWindow.show(target); + } + }); + + // Initialize comments counter + updateCommentsCount(); + + // Add create interview comments action + add(new AjaxLink("addComments") { + + private static final long serialVersionUID = 1L; + + public void onClick(AjaxRequestTarget target) { + commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { + private static final long serialVersionUID = 1L; + + @Override + public void onAddComments(AjaxRequestTarget target) { + InterviewPage.this.updateCommentsCount(); + target.addComponent(InterviewPage.this.commentsCount); + } + + }); + commentsWindow.show(target); + } + }); + + ActiveInterviewModel interviewModel = new ActiveInterviewModel(); + + KeyValueDataPanel kvPanel = new KeyValueDataPanel("interview"); + kvPanel.addRow(new StringResourceModel("StartDate", this, null), new PropertyModel(interviewModel, "startDate")); + kvPanel.addRow(new StringResourceModel("EndDate", this, null), new PropertyModel(interviewModel, "endDate")); + kvPanel.addRow(new StringResourceModel("Status", this, null), new PropertyModel(interviewModel, "status")); + add(kvPanel); + + // Interview cancellation + + final ActionDefinition cancelInterviewDef = ActionDefinitionBuilder.create(ActionType.STOP, new StringResourceModel("CancelInterview", this, null).getString()).setDescription(new StringResourceModel("ExplainCancelInterview", this, null).getString()).setAskPassword(true).getActionDefinition(); + cancelInterviewDef.addReasons(new String[] { "Reason1", "Reason2", "Reason3", "Other" }); + cancelInterviewDef.setDefaultReason("Reason1"); + + final ActionWindow interviewActionWindow = new ActionWindow("modal") { + + private static final long serialVersionUID = 1L; + + @Override + public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { + activeInterviewService.setStatus(InterviewStatus.CANCELLED); + setResponsePage(InterviewPage.class); + } + + }; + add(interviewActionWindow); + + AjaxLink link = new AjaxLink("cancelInterview") { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + interviewActionWindow.show(target, null, cancelInterviewDef); + } + }; + + if(interview.getStatus().equals(InterviewStatus.CANCELLED)) link.setVisible(false); + else + link.setVisible(true); + + add(link); + + add(new StageSelectionPanel("stage-list", getFeedbackPanel()) { + + private static final long serialVersionUID = 1L; + + @Override + public void onViewComments(AjaxRequestTarget target) { + commentsWindow.setContent(new CommentsModalPanel("content", commentsWindow) { + + private static final long serialVersionUID = 1L; + + @Override + public void onAddComments(AjaxRequestTarget target) { + InterviewPage.this.updateCommentsCount(); + target.addComponent(InterviewPage.this.commentsCount); + } + + }); + commentsWindow.show(target); + } + + @Override + public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { + InterviewPage.this.updateCommentsCount(); + target.addComponent(InterviewPage.this.commentsCount); + } + + }); + } + } + + public void updateCommentsCount() { + viewComments.addOrReplace(commentsCount = new Label("commentsCount", String.valueOf(activeInterviewService.getInterviewComments().size()))); + commentsCount.setOutputMarkupId(true); + } + + @SuppressWarnings("serial") + private class ActiveInterviewModel implements Serializable { + + public String getStartDate() { + Date date = activeInterviewService.getInterview().getStartDate(); + return date == null ? "" : DateModelUtils.getShortDateTimeModel(new Model(date)).getObject().toString(); + } + + public String getEndDate() { + Date date = activeInterviewService.getInterview().getEndDate(); + return date == null ? "" : DateModelUtils.getShortDateTimeModel(new Model(date)).getObject().toString(); + } + + public String getStatus() { + Action act = activeInterviewService.getStatusAction(); + ValueMap map = null; + if(act != null && act.getEventReason() != null) { + // TODO localize the reason + map = new ValueMap("reason=" + act.getEventReason()); + } + return (new StringResourceModel("InterviewStatus." + activeInterviewService.getInterview().getStatus(), InterviewPage.this, new Model(map))).getString(); + } + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantReceptionPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantReceptionPage.java index 206f47aaf..88ebab5e5 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantReceptionPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantReceptionPage.java @@ -1,53 +1,62 @@ -package org.obiba.onyx.webapp.participant.page; - -import org.apache.wicket.Page; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.participant.panel.AssignCodeToParticipantPanel; -import org.obiba.onyx.webapp.participant.panel.EditParticipantPanel; -import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; - -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) -public class ParticipantReceptionPage extends BasePage { - - @SuppressWarnings("serial") - public ParticipantReceptionPage(IModel participantModel, Page sourcePage) { - super(); - - final ParticipantPanel participantPanel = new ParticipantPanel("participantPanel", participantModel); - add(participantPanel); - add(new AssignCodeToParticipantPanel("assignCodeToParticipantPanel", participantModel, sourcePage)); - - // - // Add the Edit Participant pop-up. - // - final ModalWindow editParticipantModalWindow = new ModalWindow("editParticipantModalWindow"); - editParticipantModalWindow.setTitle(new StringResourceModel("Participant", this, null)); - editParticipantModalWindow.setInitialHeight(435); - editParticipantModalWindow.setInitialWidth(400); - editParticipantModalWindow.setContent(new EditParticipantPanel("content", participantModel, editParticipantModalWindow)); - editParticipantModalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - - public void onClose(AjaxRequestTarget target) { - target.addComponent(participantPanel); - } - - }); - add(editParticipantModalWindow); - - @SuppressWarnings("serial") - AjaxLink link = new AjaxLink("editParticipantAction") { - @Override - public void onClick(AjaxRequestTarget target) { - editParticipantModalWindow.show(target); - } - }; - - add(link); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.page; + +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.participant.panel.AssignCodeToParticipantPanel; +import org.obiba.onyx.webapp.participant.panel.EditParticipantPanel; +import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; + +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) +public class ParticipantReceptionPage extends BasePage { + + @SuppressWarnings("serial") + public ParticipantReceptionPage(IModel participantModel, Page sourcePage) { + super(); + + final ParticipantPanel participantPanel = new ParticipantPanel("participantPanel", participantModel); + add(participantPanel); + add(new AssignCodeToParticipantPanel("assignCodeToParticipantPanel", participantModel, sourcePage)); + + // + // Add the Edit Participant pop-up. + // + final ModalWindow editParticipantModalWindow = new ModalWindow("editParticipantModalWindow"); + editParticipantModalWindow.setTitle(new StringResourceModel("Participant", this, null)); + editParticipantModalWindow.setInitialHeight(435); + editParticipantModalWindow.setInitialWidth(400); + editParticipantModalWindow.setContent(new EditParticipantPanel("content", participantModel, editParticipantModalWindow)); + editParticipantModalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { + + public void onClose(AjaxRequestTarget target) { + target.addComponent(participantPanel); + } + + }); + add(editParticipantModalWindow); + + @SuppressWarnings("serial") + AjaxLink link = new AjaxLink("editParticipantAction") { + @Override + public void onClick(AjaxRequestTarget target) { + editParticipantModalWindow.show(target); + } + }; + + add(link); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantSearchPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantSearchPage.java index d5bb51c66..6caad9f98 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantSearchPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/page/ParticipantSearchPage.java @@ -1,469 +1,478 @@ -package org.obiba.onyx.webapp.participant.page; - -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxButton; -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.link.Link; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.target.resource.ResourceStreamRequestTarget; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.obiba.core.service.EntityQueryService; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.core.validation.exception.ValidationRuntimeException; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.ParticipantService; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.panel.OnyxEntityList; -import org.obiba.onyx.webapp.participant.panel.ParticipantModalPanel; -import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.obiba.wicket.JavascriptEventConfirmation; -import org.obiba.wicket.markup.html.link.AjaxLinkList; -import org.obiba.wicket.markup.html.table.IColumnProvider; -import org.obiba.wicket.markup.html.table.SortableDataProviderEntityServiceImpl; -import org.obiba.wicket.util.resource.CsvResourceStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.validation.ObjectError; - -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) -public class ParticipantSearchPage extends BasePage { - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(ParticipantSearchPage.class); - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ParticipantService participantService; - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - private OnyxEntityList participantList; - - private Participant template = new Participant(); - - private ModalWindow participantDetailsModalWindow; - - @SuppressWarnings("serial") - public ParticipantSearchPage() { - super(); - - participantDetailsModalWindow = new ModalWindow("participantDetailsModalWindow"); - participantDetailsModalWindow.setTitle(new StringResourceModel("Participant", this, null)); - participantDetailsModalWindow.setInitialHeight(300); - participantDetailsModalWindow.setInitialWidth(400); - add(participantDetailsModalWindow); - - Form form = new Form("searchForm"); - add(form); - - form.add(new TextField("barcode", new PropertyModel(template, "barcode"))); - - form.add(new AjaxButton("searchByCode", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - OnyxEntityList replacement; - if(template.getBarcode() == null) { - replacement = getAllParticipantsList(); - } else { - replacement = new OnyxEntityList("participant-list", new ParticipantByCodeProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("ParticipantsByCode", ParticipantSearchPage.this, new Model(new ValueMap("code=" + template.getBarcode())))); - } - replaceParticipantList(target, replacement); - target.addComponent(getFeedbackPanel()); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(getFeedbackPanel()); - } - - }); - - form.add(new TextField("lastName", new PropertyModel(template, "lastName"))); - - form.add(new AjaxButton("searchByLastName", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - OnyxEntityList replacement; - if(template.getLastName() == null) { - replacement = getAllParticipantsList(); - } else { - replacement = new OnyxEntityList("participant-list", new ParticipantByNameProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("ParticipantsByName", ParticipantSearchPage.this, new Model(new ValueMap("name=" + template.getLastName())))); - } - replaceParticipantList(target, replacement); - target.addComponent(getFeedbackPanel()); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(getFeedbackPanel()); - } - - }); - - form.add(new AjaxButton("submit", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - OnyxEntityList replacement = getAllParticipantsList(); - replaceParticipantList(target, replacement); - target.addComponent(getFeedbackPanel()); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(getFeedbackPanel()); - } - - }); - - form.add(new AjaxButton("appointments", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - OnyxEntityList replacement = new OnyxEntityList("participant-list", new AppointedParticipantProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("AppointmentsOfTheDay", ParticipantSearchPage.this, null)); - replaceParticipantList(target, replacement); - target.addComponent(getFeedbackPanel()); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(getFeedbackPanel()); - } - - }); - - form.add(new AjaxButton("interviews", form) { - - @Override - protected void onSubmit(AjaxRequestTarget target, Form form) { - OnyxEntityList replacement = new OnyxEntityList("participant-list", new InterviewedParticipantProvider(), new ParticipantListColumnProvider(), new StringResourceModel("CurrentInterviews", ParticipantSearchPage.this, null)); - replaceParticipantList(target, replacement); - target.addComponent(getFeedbackPanel()); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(getFeedbackPanel()); - } - - }); - - add(new AjaxLink("volunteer") { - - @Override - public void onClick(AjaxRequestTarget target) { - // TODO enroll volunteer - target.addComponent(getFeedbackPanel()); - } - - }); - - Link link = new Link("update") { - - @Override - public void onClick() { - try { - participantService.updateParticipantList(); - info(ParticipantSearchPage.this.getString("ParticipantsListSuccessfullyUpdated")); - } catch(ValidationRuntimeException e) { - for(ObjectError oe : e.getAllObjectErrors()) { - Object[] args = oe.getArguments(); - IModel model = null; - if(oe.getCode().equals("ParticipantInterviewCompletedWithAppointmentInTheFuture") && args != null && args.length == 4) { - ValueMap map = new ValueMap("line=" + args[0] + ",id=" + args[1]); - model = new Model(map); - } else if(oe.getCode().equals("WrongParticipantSiteName") && args != null && args.length >= 3) { - ValueMap map = new ValueMap("line=" + args[0] + ",id=" + args[1] + ",site=" + args[2]); - model = new Model(map); - } - error(ParticipantSearchPage.this.getString(oe.getCode(), model, oe.getDefaultMessage())); - } - log.error("Failed updating participants: {}", e.toString()); - } - } - - }; - link.add(new JavascriptEventConfirmation("onclick", new StringResourceModel("ConfirmParticipantsListUpdate", this, null))); - add(link); - - add(new Link("excel") { - - @Override - public void onClick() { - getRequestCycle().setRequestTarget(new ResourceStreamRequestTarget(participantList.getReportStream()) { - @Override - public String getFileName() { - SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd_HHmm"); - String name = formater.format(new Date()) + "_participants"; - - return name + "." + CsvResourceStream.FILE_SUFFIX; - } - }); - } - - }); - - participantList = new OnyxEntityList("participant-list", new AppointedParticipantProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("AppointmentsOfTheDay", ParticipantSearchPage.this, null)); - add(participantList); - } - - private OnyxEntityList getAllParticipantsList() { - return new OnyxEntityList("participant-list", new ParticipantProvider(), new ParticipantListColumnProvider(), new StringResourceModel("Participants", ParticipantSearchPage.this, null)); - } - - private void replaceParticipantList(AjaxRequestTarget target, OnyxEntityList replacement) { - participantList.replaceWith(replacement); - participantList = replacement; - - target.addComponent(participantList); - } - - @SuppressWarnings("serial") - private class ParticipantProvider extends SortableDataProviderEntityServiceImpl { - - public ParticipantProvider() { - super(queryService, Participant.class); - setSort(new SortParam("lastName", true)); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return queryService.list(Participant.class, paging, clauses); - } - - @Override - public int size() { - return queryService.count(Participant.class); - } - - } - - @SuppressWarnings("serial") - private class ParticipantByCodeProvider extends SortableDataProviderEntityServiceImpl { - - private Participant template; - - public ParticipantByCodeProvider(Participant template) { - super(queryService, Participant.class); - this.template = template; - setSort(new SortParam("barcode", true)); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return participantService.getParticipantsByCode(template.getBarcode(), paging, clauses); - } - - @Override - public int size() { - return participantService.countParticipantsByCode(template.getBarcode()); - } - - } - - @SuppressWarnings("serial") - private class ParticipantByNameProvider extends SortableDataProviderEntityServiceImpl { - - private Participant template; - - public ParticipantByNameProvider(Participant template) { - super(queryService, Participant.class); - this.template = template; - setSort(new SortParam("lastName", true)); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return participantService.getParticipantsByName(template.getLastName(), paging, clauses); - } - - @Override - public int size() { - return participantService.countParticipantsByName(template.getLastName()); - } - - } - - @SuppressWarnings("serial") - private class AppointedParticipantProvider extends SortableDataProviderEntityServiceImpl { - - private Date from; - - private Date to; - - public AppointedParticipantProvider(Participant template) { - super(queryService, Participant.class); - setSort(new SortParam("appointment.date", true)); - - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date()); - cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); - this.from = cal.getTime(); - cal.add(Calendar.DAY_OF_MONTH, 1); - this.to = cal.getTime(); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return participantService.getParticipants(from, to, paging, clauses); - } - - @Override - public int size() { - return participantService.countParticipants(from, to); - } - - } - - @SuppressWarnings("serial") - private class InterviewedParticipantProvider extends SortableDataProviderEntityServiceImpl { - - public InterviewedParticipantProvider() { - super(queryService, Participant.class); - setSort(new SortParam("lastName", true)); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return participantService.getParticipants(InterviewStatus.IN_PROGRESS, paging, clauses); - } - - @Override - public int size() { - return participantService.countParticipants(InterviewStatus.IN_PROGRESS); - } - - } - - private class ParticipantListColumnProvider implements IColumnProvider, Serializable { - - private static final long serialVersionUID = -9121583835357007L; - - private List columns = new ArrayList(); - - private List additional = new ArrayList(); - - @SuppressWarnings("serial") - public ParticipantListColumnProvider() { - columns.add(new PropertyColumn(new StringResourceModel("ParticipantCode", ParticipantSearchPage.this, null), "barcode", "barcode")); - columns.add(new PropertyColumn(new StringResourceModel("LastName", ParticipantSearchPage.this, null), "lastName", "lastName")); - columns.add(new PropertyColumn(new StringResourceModel("FirstName", ParticipantSearchPage.this, null), "firstName", "firstName")); - columns.add(new AbstractColumn(new StringResourceModel("Gender", ParticipantSearchPage.this, null), "gender") { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Participant p = (Participant) rowModel.getObject(); - cellItem.add(new Label(componentId, new StringResourceModel("Gender." + p.getGender(), ParticipantSearchPage.this, null))); - } - - }); - columns.add(new AbstractColumn(new StringResourceModel("BirthDate", ParticipantSearchPage.this, null), "birthDate") { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Participant p = (Participant) rowModel.getObject(); - cellItem.add(new Label(componentId, DateModelUtils.getShortDateModel(new Model(p.getBirthDate())))); - } - - }); - - columns.add(new AbstractColumn(new StringResourceModel("Appointment", ParticipantSearchPage.this, null), "appointment.date") { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Participant p = (Participant) rowModel.getObject(); - if(p.getAppointment() != null) cellItem.add(new Label(componentId, DateModelUtils.getShortDateTimeModel(new Model(p.getAppointment().getDate())))); - else - cellItem.add(new Label(componentId, "")); - } - - }); - - columns.add(new AbstractColumn(new StringResourceModel("Status", ParticipantSearchPage.this, null)) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Participant p = (Participant) rowModel.getObject(); - if(p.getInterview() != null) cellItem.add(new Label(componentId, new StringResourceModel("InterviewStatus." + p.getInterview().getStatus(), ParticipantSearchPage.this, null))); - else - cellItem.add(new Label(componentId)); - } - - }); - columns.add(new AbstractColumn(new StringResourceModel("Actions", ParticipantSearchPage.this, null)) { - - public void populateItem(final Item cellItem, String componentId, final IModel rowModel) { - final List actions = new ArrayList(); - final Participant p = (Participant) rowModel.getObject(); - actions.add(new StringResourceModel("View", ParticipantSearchPage.this, null)); - if(p.getBarcode() != null) actions.add(new StringResourceModel("Interview", ParticipantSearchPage.this, null)); - else - actions.add(new StringResourceModel("Receive", ParticipantSearchPage.this, null)); - - cellItem.add(new AjaxLinkList(componentId, actions, "") { - - @Override - public void onClick(IModel model, AjaxRequestTarget target) { - if(actions.indexOf(model) == 0) { - participantDetailsModalWindow.setContent(new ParticipantModalPanel("content", new ParticipantPanel("content", rowModel), participantDetailsModalWindow)); - participantDetailsModalWindow.show(target); - } else if(actions.indexOf(model) == 1) { - if(p.getBarcode() != null) { - activeInterviewService.setParticipant(p); - setResponsePage(InterviewPage.class); - } else { - setResponsePage(new ParticipantReceptionPage(rowModel, ParticipantSearchPage.this)); - } - } - } - - }); - } - - }); - } - - public List getAdditionalColumns() { - return additional; - } - - public List getColumnHeaderNames() { - return null; - } - - public List getDefaultColumns() { - return columns; - } - - public List getRequiredColumns() { - return columns; - } - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.page; + +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.link.Link; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.target.resource.ResourceStreamRequestTarget; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.obiba.core.service.EntityQueryService; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.core.validation.exception.ValidationRuntimeException; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.ParticipantService; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.panel.OnyxEntityList; +import org.obiba.onyx.webapp.participant.panel.ParticipantModalPanel; +import org.obiba.onyx.webapp.participant.panel.ParticipantPanel; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.obiba.wicket.JavascriptEventConfirmation; +import org.obiba.wicket.markup.html.link.AjaxLinkList; +import org.obiba.wicket.markup.html.table.IColumnProvider; +import org.obiba.wicket.markup.html.table.SortableDataProviderEntityServiceImpl; +import org.obiba.wicket.util.resource.CsvResourceStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.validation.ObjectError; + +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) +public class ParticipantSearchPage extends BasePage { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ParticipantSearchPage.class); + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ParticipantService participantService; + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + private OnyxEntityList participantList; + + private Participant template = new Participant(); + + private ModalWindow participantDetailsModalWindow; + + @SuppressWarnings("serial") + public ParticipantSearchPage() { + super(); + + participantDetailsModalWindow = new ModalWindow("participantDetailsModalWindow"); + participantDetailsModalWindow.setTitle(new StringResourceModel("Participant", this, null)); + participantDetailsModalWindow.setInitialHeight(300); + participantDetailsModalWindow.setInitialWidth(400); + add(participantDetailsModalWindow); + + Form form = new Form("searchForm"); + add(form); + + form.add(new TextField("barcode", new PropertyModel(template, "barcode"))); + + form.add(new AjaxButton("searchByCode", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + OnyxEntityList replacement; + if(template.getBarcode() == null) { + replacement = getAllParticipantsList(); + } else { + replacement = new OnyxEntityList("participant-list", new ParticipantByCodeProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("ParticipantsByCode", ParticipantSearchPage.this, new Model(new ValueMap("code=" + template.getBarcode())))); + } + replaceParticipantList(target, replacement); + target.addComponent(getFeedbackPanel()); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(getFeedbackPanel()); + } + + }); + + form.add(new TextField("lastName", new PropertyModel(template, "lastName"))); + + form.add(new AjaxButton("searchByLastName", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + OnyxEntityList replacement; + if(template.getLastName() == null) { + replacement = getAllParticipantsList(); + } else { + replacement = new OnyxEntityList("participant-list", new ParticipantByNameProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("ParticipantsByName", ParticipantSearchPage.this, new Model(new ValueMap("name=" + template.getLastName())))); + } + replaceParticipantList(target, replacement); + target.addComponent(getFeedbackPanel()); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(getFeedbackPanel()); + } + + }); + + form.add(new AjaxButton("submit", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + OnyxEntityList replacement = getAllParticipantsList(); + replaceParticipantList(target, replacement); + target.addComponent(getFeedbackPanel()); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(getFeedbackPanel()); + } + + }); + + form.add(new AjaxButton("appointments", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + OnyxEntityList replacement = new OnyxEntityList("participant-list", new AppointedParticipantProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("AppointmentsOfTheDay", ParticipantSearchPage.this, null)); + replaceParticipantList(target, replacement); + target.addComponent(getFeedbackPanel()); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(getFeedbackPanel()); + } + + }); + + form.add(new AjaxButton("interviews", form) { + + @Override + protected void onSubmit(AjaxRequestTarget target, Form form) { + OnyxEntityList replacement = new OnyxEntityList("participant-list", new InterviewedParticipantProvider(), new ParticipantListColumnProvider(), new StringResourceModel("CurrentInterviews", ParticipantSearchPage.this, null)); + replaceParticipantList(target, replacement); + target.addComponent(getFeedbackPanel()); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(getFeedbackPanel()); + } + + }); + + add(new AjaxLink("volunteer") { + + @Override + public void onClick(AjaxRequestTarget target) { + // TODO enroll volunteer + target.addComponent(getFeedbackPanel()); + } + + }); + + Link link = new Link("update") { + + @Override + public void onClick() { + try { + participantService.updateParticipantList(); + info(ParticipantSearchPage.this.getString("ParticipantsListSuccessfullyUpdated")); + } catch(ValidationRuntimeException e) { + for(ObjectError oe : e.getAllObjectErrors()) { + Object[] args = oe.getArguments(); + IModel model = null; + if(oe.getCode().equals("ParticipantInterviewCompletedWithAppointmentInTheFuture") && args != null && args.length == 4) { + ValueMap map = new ValueMap("line=" + args[0] + ",id=" + args[1]); + model = new Model(map); + } else if(oe.getCode().equals("WrongParticipantSiteName") && args != null && args.length >= 3) { + ValueMap map = new ValueMap("line=" + args[0] + ",id=" + args[1] + ",site=" + args[2]); + model = new Model(map); + } + error(ParticipantSearchPage.this.getString(oe.getCode(), model, oe.getDefaultMessage())); + } + log.error("Failed updating participants: {}", e.toString()); + } + } + + }; + link.add(new JavascriptEventConfirmation("onclick", new StringResourceModel("ConfirmParticipantsListUpdate", this, null))); + add(link); + + add(new Link("excel") { + + @Override + public void onClick() { + getRequestCycle().setRequestTarget(new ResourceStreamRequestTarget(participantList.getReportStream()) { + @Override + public String getFileName() { + SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd_HHmm"); + String name = formater.format(new Date()) + "_participants"; + + return name + "." + CsvResourceStream.FILE_SUFFIX; + } + }); + } + + }); + + participantList = new OnyxEntityList("participant-list", new AppointedParticipantProvider(template), new ParticipantListColumnProvider(), new StringResourceModel("AppointmentsOfTheDay", ParticipantSearchPage.this, null)); + add(participantList); + } + + private OnyxEntityList getAllParticipantsList() { + return new OnyxEntityList("participant-list", new ParticipantProvider(), new ParticipantListColumnProvider(), new StringResourceModel("Participants", ParticipantSearchPage.this, null)); + } + + private void replaceParticipantList(AjaxRequestTarget target, OnyxEntityList replacement) { + participantList.replaceWith(replacement); + participantList = replacement; + + target.addComponent(participantList); + } + + @SuppressWarnings("serial") + private class ParticipantProvider extends SortableDataProviderEntityServiceImpl { + + public ParticipantProvider() { + super(queryService, Participant.class); + setSort(new SortParam("lastName", true)); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return queryService.list(Participant.class, paging, clauses); + } + + @Override + public int size() { + return queryService.count(Participant.class); + } + + } + + @SuppressWarnings("serial") + private class ParticipantByCodeProvider extends SortableDataProviderEntityServiceImpl { + + private Participant template; + + public ParticipantByCodeProvider(Participant template) { + super(queryService, Participant.class); + this.template = template; + setSort(new SortParam("barcode", true)); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return participantService.getParticipantsByCode(template.getBarcode(), paging, clauses); + } + + @Override + public int size() { + return participantService.countParticipantsByCode(template.getBarcode()); + } + + } + + @SuppressWarnings("serial") + private class ParticipantByNameProvider extends SortableDataProviderEntityServiceImpl { + + private Participant template; + + public ParticipantByNameProvider(Participant template) { + super(queryService, Participant.class); + this.template = template; + setSort(new SortParam("lastName", true)); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return participantService.getParticipantsByName(template.getLastName(), paging, clauses); + } + + @Override + public int size() { + return participantService.countParticipantsByName(template.getLastName()); + } + + } + + @SuppressWarnings("serial") + private class AppointedParticipantProvider extends SortableDataProviderEntityServiceImpl { + + private Date from; + + private Date to; + + public AppointedParticipantProvider(Participant template) { + super(queryService, Participant.class); + setSort(new SortParam("appointment.date", true)); + + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); + this.from = cal.getTime(); + cal.add(Calendar.DAY_OF_MONTH, 1); + this.to = cal.getTime(); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return participantService.getParticipants(from, to, paging, clauses); + } + + @Override + public int size() { + return participantService.countParticipants(from, to); + } + + } + + @SuppressWarnings("serial") + private class InterviewedParticipantProvider extends SortableDataProviderEntityServiceImpl { + + public InterviewedParticipantProvider() { + super(queryService, Participant.class); + setSort(new SortParam("lastName", true)); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return participantService.getParticipants(InterviewStatus.IN_PROGRESS, paging, clauses); + } + + @Override + public int size() { + return participantService.countParticipants(InterviewStatus.IN_PROGRESS); + } + + } + + private class ParticipantListColumnProvider implements IColumnProvider, Serializable { + + private static final long serialVersionUID = -9121583835357007L; + + private List columns = new ArrayList(); + + private List additional = new ArrayList(); + + @SuppressWarnings("serial") + public ParticipantListColumnProvider() { + columns.add(new PropertyColumn(new StringResourceModel("ParticipantCode", ParticipantSearchPage.this, null), "barcode", "barcode")); + columns.add(new PropertyColumn(new StringResourceModel("LastName", ParticipantSearchPage.this, null), "lastName", "lastName")); + columns.add(new PropertyColumn(new StringResourceModel("FirstName", ParticipantSearchPage.this, null), "firstName", "firstName")); + columns.add(new AbstractColumn(new StringResourceModel("Gender", ParticipantSearchPage.this, null), "gender") { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Participant p = (Participant) rowModel.getObject(); + cellItem.add(new Label(componentId, new StringResourceModel("Gender." + p.getGender(), ParticipantSearchPage.this, null))); + } + + }); + columns.add(new AbstractColumn(new StringResourceModel("BirthDate", ParticipantSearchPage.this, null), "birthDate") { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Participant p = (Participant) rowModel.getObject(); + cellItem.add(new Label(componentId, DateModelUtils.getShortDateModel(new Model(p.getBirthDate())))); + } + + }); + + columns.add(new AbstractColumn(new StringResourceModel("Appointment", ParticipantSearchPage.this, null), "appointment.date") { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Participant p = (Participant) rowModel.getObject(); + if(p.getAppointment() != null) cellItem.add(new Label(componentId, DateModelUtils.getShortDateTimeModel(new Model(p.getAppointment().getDate())))); + else + cellItem.add(new Label(componentId, "")); + } + + }); + + columns.add(new AbstractColumn(new StringResourceModel("Status", ParticipantSearchPage.this, null)) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Participant p = (Participant) rowModel.getObject(); + if(p.getInterview() != null) cellItem.add(new Label(componentId, new StringResourceModel("InterviewStatus." + p.getInterview().getStatus(), ParticipantSearchPage.this, null))); + else + cellItem.add(new Label(componentId)); + } + + }); + columns.add(new AbstractColumn(new StringResourceModel("Actions", ParticipantSearchPage.this, null)) { + + public void populateItem(final Item cellItem, String componentId, final IModel rowModel) { + final List actions = new ArrayList(); + final Participant p = (Participant) rowModel.getObject(); + actions.add(new StringResourceModel("View", ParticipantSearchPage.this, null)); + if(p.getBarcode() != null) actions.add(new StringResourceModel("Interview", ParticipantSearchPage.this, null)); + else + actions.add(new StringResourceModel("Receive", ParticipantSearchPage.this, null)); + + cellItem.add(new AjaxLinkList(componentId, actions, "") { + + @Override + public void onClick(IModel model, AjaxRequestTarget target) { + if(actions.indexOf(model) == 0) { + participantDetailsModalWindow.setContent(new ParticipantModalPanel("content", new ParticipantPanel("content", rowModel), participantDetailsModalWindow)); + participantDetailsModalWindow.show(target); + } else if(actions.indexOf(model) == 1) { + if(p.getBarcode() != null) { + activeInterviewService.setParticipant(p); + setResponsePage(InterviewPage.class); + } else { + setResponsePage(new ParticipantReceptionPage(rowModel, ParticipantSearchPage.this)); + } + } + } + + }); + } + + }); + } + + public List getAdditionalColumns() { + return additional; + } + + public List getColumnHeaderNames() { + return null; + } + + public List getDefaultColumns() { + return columns; + } + + public List getRequiredColumns() { + return columns; + } + + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/AssignCodeToParticipantPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/AssignCodeToParticipantPanel.java index 4a7b8073b..b10298759 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/AssignCodeToParticipantPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/AssignCodeToParticipantPanel.java @@ -1,117 +1,126 @@ -package org.obiba.onyx.webapp.participant.panel; - -import java.io.Serializable; - -import org.apache.wicket.Page; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.markup.html.form.Button; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.TextArea; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.apache.wicket.validation.IErrorMessageSource; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidationError; -import org.apache.wicket.validation.IValidator; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ParticipantService; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; - -public class AssignCodeToParticipantPanel extends Panel { - - @SpringBean - private ParticipantService participantService; - - @SpringBean - private EntityQueryService queryService; - - private Page sourcePage; - - private static final long serialVersionUID = 1L; - - public AssignCodeToParticipantPanel(String id, IModel participantModel, Page sourcePage) { - - super(id); - - this.sourcePage = sourcePage; - - add(new AssignCodeToParticipantForm("assignCodeToParticipantForm", participantModel)); - - } - - private class AssignCodeToParticipantForm extends Form { - - private static final long serialVersionUID = 1L; - - @SuppressWarnings("serial") - public AssignCodeToParticipantForm(String id, final IModel participantModel) { - super(id); - final Participant participantTemplate = new Participant(); - - TextField participantCode = new TextField("participantCode", new PropertyModel(participantTemplate, "barcode")); - participantCode.add(new RequiredFormFieldBehavior()); - participantCode.add(new IValidator() { - - public void validate(final IValidatable validatable) { - Participant template = new Participant(); - template.setBarcode((String) validatable.getValue()); - if(queryService.count(template) > 0) { - validatable.error(new ParticipantIDValidationError((String) validatable.getValue())); - } - } - - }); - add(participantCode); - - // TODO comment at reception time - final Model receptionCommentModel = new Model(); - add(new TextArea("comment", receptionCommentModel)); - - add(new Button("submit", participantModel) { - - @Override - public void onSubmit() { - participantService.assignCodeToParticipant((Participant) participantModel.getObject(), participantTemplate.getBarcode(), (String) receptionCommentModel.getObject(), OnyxAuthenticatedSession.get().getUser()); - setResponsePage(sourcePage); - } - }); - - add(new AjaxLink("cancel") { - - @Override - public void onClick(AjaxRequestTarget target) { - setResponsePage(sourcePage); - } - - }); - - } - } - - @SuppressWarnings("serial") - private class ParticipantIDValidationError implements IValidationError, Serializable { - - private String id; - - public ParticipantIDValidationError(String id) { - this.id = id; - } - - public String getErrorMessage(IErrorMessageSource messageSource) { - StringResourceModel strModel = new StringResourceModel("ParticipantIDAlreadyAssigned", AssignCodeToParticipantPanel.this, new Model(new ValueMap("id=" + id))); - return strModel.getString(); - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import java.io.Serializable; + +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.markup.html.form.Button; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.TextArea; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.apache.wicket.validation.IErrorMessageSource; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidationError; +import org.apache.wicket.validation.IValidator; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ParticipantService; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.webapp.participant.page.ParticipantSearchPage; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; + +public class AssignCodeToParticipantPanel extends Panel { + + @SpringBean + private ParticipantService participantService; + + @SpringBean + private EntityQueryService queryService; + + private Page sourcePage; + + private static final long serialVersionUID = 1L; + + public AssignCodeToParticipantPanel(String id, IModel participantModel, Page sourcePage) { + + super(id); + + this.sourcePage = sourcePage; + + add(new AssignCodeToParticipantForm("assignCodeToParticipantForm", participantModel)); + + } + + private class AssignCodeToParticipantForm extends Form { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("serial") + public AssignCodeToParticipantForm(String id, final IModel participantModel) { + super(id); + final Participant participantTemplate = new Participant(); + + TextField participantCode = new TextField("participantCode", new PropertyModel(participantTemplate, "barcode")); + participantCode.add(new RequiredFormFieldBehavior()); + participantCode.add(new IValidator() { + + public void validate(final IValidatable validatable) { + Participant template = new Participant(); + template.setBarcode((String) validatable.getValue()); + if(queryService.count(template) > 0) { + validatable.error(new ParticipantIDValidationError((String) validatable.getValue())); + } + } + + }); + add(participantCode); + + // TODO comment at reception time + final Model receptionCommentModel = new Model(); + add(new TextArea("comment", receptionCommentModel)); + + add(new Button("submit", participantModel) { + + @Override + public void onSubmit() { + participantService.assignCodeToParticipant((Participant) participantModel.getObject(), participantTemplate.getBarcode(), (String) receptionCommentModel.getObject(), OnyxAuthenticatedSession.get().getUser()); + setResponsePage(sourcePage); + } + }); + + add(new AjaxLink("cancel") { + + @Override + public void onClick(AjaxRequestTarget target) { + setResponsePage(sourcePage); + } + + }); + + } + } + + @SuppressWarnings("serial") + private class ParticipantIDValidationError implements IValidationError, Serializable { + + private String id; + + public ParticipantIDValidationError(String id) { + this.id = id; + } + + public String getErrorMessage(IErrorMessageSource messageSource) { + StringResourceModel strModel = new StringResourceModel("ParticipantIDAlreadyAssigned", AssignCodeToParticipantPanel.this, new Model(new ValueMap("id=" + id))); + return strModel.getString(); + } + + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanel.java index 2f1bf825a..c5f5f0cc7 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanel.java @@ -1,216 +1,225 @@ -package org.obiba.onyx.webapp.participant.panel; - -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxButton; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.basic.MultiLineLabel; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.TextArea; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.markup.repeater.data.DataView; -import org.apache.wicket.markup.repeater.data.IDataProvider; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; -import org.obiba.wicket.markup.html.table.DetachableEntityModel; - -public abstract class CommentsModalPanel extends Panel { - - private static final long serialVersionUID = 1L; - - @SpringBean(name="activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private ModalWindow commentsWindow; - - private FeedbackPanel feedback; - - private List commentList; - - WebMarkupContainer previousComments; - - public CommentsModalPanel(String id, final ModalWindow commentsWindow) { - super(id); - this.commentsWindow = commentsWindow; - commentList = activeInterviewService.getInterviewComments(); - setOutputMarkupId(true); - - add(new ParticipantPanel("participant", new DetachableEntityModel(queryService, activeInterviewService.getParticipant()), true)); - add(new CommentForm("commentForm")); - - add(feedback = new FeedbackPanel("feedback")); - feedback.setOutputMarkupId(true); - - // The WebMarkupContainer is needed to allow the DataView update through Ajax. The DataView cannot be update directly. - add(previousComments = new WebMarkupContainer("previousComments")); - previousComments.add(new CommentsDataView("comment-list", new CommentsDataProvider())); - previousComments.setOutputMarkupId(true); - - // No comment message is only visible when there is no comment for the current interview. - previousComments.add(new Label("noComments", new StringResourceModel("NoComments", this, null)) { - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - if(commentList.size() == 0) { - return true; - } - return false; - } - }); - - commentsWindow.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { - - private static final long serialVersionUID = 1L; - - public boolean onCloseButtonClicked(AjaxRequestTarget target) { - return true; - } - }); - - } - - public abstract void onAddComments(AjaxRequestTarget target); - - private class CommentForm extends Form { - - private static final long serialVersionUID = 1L; - - public CommentForm(String id) { - super(id); - - setModel(new Model(new Action())); - - final TextArea newComment = new TextArea("newComment", new PropertyModel(getModel(), "comment")); - newComment.add(new RequiredFormFieldBehavior()); - newComment.setOutputMarkupId(true); - add(newComment); - - // Save a new comment. - add(new AjaxButton("saveComment", this) { - - private static final long serialVersionUID = 1L; - - protected void onSubmit(AjaxRequestTarget target, Form form) { - - // Add new comment to interview. - Action comment = (Action) CommentForm.this.getModelObject(); - comment.setActionType(ActionType.COMMENT); - activeInterviewService.doAction(null, comment, activeInterviewService.getInterview().getUser()); - CommentsModalPanel.this.onAddComments(target); - - // Refresh previous comments list. - commentList = activeInterviewService.getInterviewComments(); - target.addComponent(previousComments); - - // Reset new comment form. - CommentForm.this.getModel().setObject(new Action()); - target.addComponent(newComment); - - // Display a message confirming that the comment was saved. - info(new StringResourceModel("NewCommentAddedConfirmation", this, null, new Object[] { DateModelUtils.getDateTimeModel(new Model(new Date(System.currentTimeMillis()))) }).getString()); - target.addComponent(feedback); - } - - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedback); - } - - }); - - add(new AjaxLink("cancelComment") { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - commentsWindow.close(target); - } - - }); - - } - - } - - private class CommentsDataView extends DataView { - - private static final long serialVersionUID = 1L; - - public CommentsDataView(String id, IDataProvider dataProvider) { - super(id, dataProvider); - } - - @Override - protected void populateItem(Item item) { - Action comment = (Action) item.getModelObject(); - - KeyValueDataPanel kvPanel = new KeyValueDataPanel("comment-panel"); - kvPanel.addRow(new StringResourceModel("CommentTime", this, null), DateModelUtils.getDateTimeModel(new PropertyModel(comment, "dateTime"))); - IModel stageModel; - if(comment.getStage() != null) { - stageModel = new PropertyModel(new StageModel(moduleRegistry, comment.getStage()), "description"); - } else { - stageModel = new StringResourceModel("GeneralComment", this, null); - } - kvPanel.addRow(new StringResourceModel("Stage", this, null), stageModel); - User currentUser = comment.getUser(); - kvPanel.addRow(new StringResourceModel("MadeBy", this, null), new Label(KeyValueDataPanel.getRowValueId(), currentUser.getFirstName() + " " + currentUser.getLastName())); - kvPanel.addRow(new StringResourceModel("Comment", this, null), new MultiLineLabel(KeyValueDataPanel.getRowValueId(), new PropertyModel(comment, "comment"))); - item.add(kvPanel); - - } - - } - - private class CommentsDataProvider implements IDataProvider { - - private static final long serialVersionUID = 1L; - - Action template; - - public Iterator iterator(int first, int count) { - return commentList.iterator(); - } - - public IModel model(Object object) { - return new Model((Action) object); - } - - public int size() { - return commentList.size(); - } - - public void detach() { - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.basic.MultiLineLabel; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.TextArea; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.markup.repeater.data.DataView; +import org.apache.wicket.markup.repeater.data.IDataProvider; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; +import org.obiba.wicket.markup.html.table.DetachableEntityModel; + +public abstract class CommentsModalPanel extends Panel { + + private static final long serialVersionUID = 1L; + + @SpringBean(name="activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private ModalWindow commentsWindow; + + private FeedbackPanel feedback; + + private List commentList; + + WebMarkupContainer previousComments; + + public CommentsModalPanel(String id, final ModalWindow commentsWindow) { + super(id); + this.commentsWindow = commentsWindow; + commentList = activeInterviewService.getInterviewComments(); + setOutputMarkupId(true); + + add(new ParticipantPanel("participant", new DetachableEntityModel(queryService, activeInterviewService.getParticipant()), true)); + add(new CommentForm("commentForm")); + + add(feedback = new FeedbackPanel("feedback")); + feedback.setOutputMarkupId(true); + + // The WebMarkupContainer is needed to allow the DataView update through Ajax. The DataView cannot be update directly. + add(previousComments = new WebMarkupContainer("previousComments")); + previousComments.add(new CommentsDataView("comment-list", new CommentsDataProvider())); + previousComments.setOutputMarkupId(true); + + // No comment message is only visible when there is no comment for the current interview. + previousComments.add(new Label("noComments", new StringResourceModel("NoComments", this, null)) { + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + if(commentList.size() == 0) { + return true; + } + return false; + } + }); + + commentsWindow.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { + + private static final long serialVersionUID = 1L; + + public boolean onCloseButtonClicked(AjaxRequestTarget target) { + return true; + } + }); + + } + + public abstract void onAddComments(AjaxRequestTarget target); + + private class CommentForm extends Form { + + private static final long serialVersionUID = 1L; + + public CommentForm(String id) { + super(id); + + setModel(new Model(new Action())); + + final TextArea newComment = new TextArea("newComment", new PropertyModel(getModel(), "comment")); + newComment.add(new RequiredFormFieldBehavior()); + newComment.setOutputMarkupId(true); + add(newComment); + + // Save a new comment. + add(new AjaxButton("saveComment", this) { + + private static final long serialVersionUID = 1L; + + protected void onSubmit(AjaxRequestTarget target, Form form) { + + // Add new comment to interview. + Action comment = (Action) CommentForm.this.getModelObject(); + comment.setActionType(ActionType.COMMENT); + activeInterviewService.doAction(null, comment, activeInterviewService.getInterview().getUser()); + CommentsModalPanel.this.onAddComments(target); + + // Refresh previous comments list. + commentList = activeInterviewService.getInterviewComments(); + target.addComponent(previousComments); + + // Reset new comment form. + CommentForm.this.getModel().setObject(new Action()); + target.addComponent(newComment); + + // Display a message confirming that the comment was saved. + info(new StringResourceModel("NewCommentAddedConfirmation", this, null, new Object[] { DateModelUtils.getDateTimeModel(new Model(new Date(System.currentTimeMillis()))) }).getString()); + target.addComponent(feedback); + } + + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedback); + } + + }); + + add(new AjaxLink("cancelComment") { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + commentsWindow.close(target); + } + + }); + + } + + } + + private class CommentsDataView extends DataView { + + private static final long serialVersionUID = 1L; + + public CommentsDataView(String id, IDataProvider dataProvider) { + super(id, dataProvider); + } + + @Override + protected void populateItem(Item item) { + Action comment = (Action) item.getModelObject(); + + KeyValueDataPanel kvPanel = new KeyValueDataPanel("comment-panel"); + kvPanel.addRow(new StringResourceModel("CommentTime", this, null), DateModelUtils.getDateTimeModel(new PropertyModel(comment, "dateTime"))); + IModel stageModel; + if(comment.getStage() != null) { + stageModel = new PropertyModel(new StageModel(moduleRegistry, comment.getStage()), "description"); + } else { + stageModel = new StringResourceModel("GeneralComment", this, null); + } + kvPanel.addRow(new StringResourceModel("Stage", this, null), stageModel); + User currentUser = comment.getUser(); + kvPanel.addRow(new StringResourceModel("MadeBy", this, null), new Label(KeyValueDataPanel.getRowValueId(), currentUser.getFirstName() + " " + currentUser.getLastName())); + kvPanel.addRow(new StringResourceModel("Comment", this, null), new MultiLineLabel(KeyValueDataPanel.getRowValueId(), new PropertyModel(comment, "comment"))); + item.add(kvPanel); + + } + + } + + private class CommentsDataProvider implements IDataProvider { + + private static final long serialVersionUID = 1L; + + Action template; + + public Iterator iterator(int first, int count) { + return commentList.iterator(); + } + + public IModel model(Object object) { + return new Model((Action) object); + } + + public int size() { + return commentList.size(); + } + + public void detach() { + } + + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanel.java index 7b2e78a8b..b522be7f1 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanel.java @@ -1,185 +1,194 @@ -package org.obiba.onyx.webapp.participant.panel; - -import java.util.Arrays; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; -import org.apache.wicket.datetime.markup.html.form.DateTextField; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.extensions.yui.calendar.DateField; -import org.apache.wicket.markup.html.form.DropDownChoice; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.ResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.validation.validator.PatternValidator; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.participant.Province; -import org.obiba.onyx.core.service.ParticipantService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class EditParticipantPanel extends Panel { - - private static final long serialVersionUID = 1L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(EditParticipantPanel.class); - - /** - * Regular expression used to validate postal codes. - * - * Note: - No postal code includes the letters D, F, I, O, Q, or U. - The letters W and Z are used, but are not - * currently used as the first letter. - */ - private static final String POSTAL_CODE_REGEX = "[A-Z&&[^DFIOQUWZ]]\\d[A-Z&&[^DFIOQU]] \\d[A-Z&&[^DFIOQU]]\\d"; - - /** - * Regular expression used to validate phone numbers. - * - * Note: - Dashes are required between different parts of the phone number. - This is obviously very basic validation. - * More could be done here to rule out numbers that confirm to this format but are invalid for other reasons (e.g., - * 000-000-0000 is not a valid phone number). - */ - private static final String PHONE_REGEX = "\\d{3}-\\d{3}-\\d{4}"; - - @SpringBean - private ParticipantService participantService; - - private ModalWindow parentWindow; - - private FeedbackPanel feedbackPanel; - - public EditParticipantPanel(String id, IModel participantModel, ModalWindow parentWindow) { - super(id); - - this.parentWindow = parentWindow; - - Form editParticipantForm = new EditParticipantForm("editParticipantForm", participantModel); - add(editParticipantForm); - - feedbackPanel = new FeedbackPanel("feedback"); - feedbackPanel.setOutputMarkupId(true); - add(feedbackPanel); - } - - private class EditParticipantForm extends Form { - - private static final long serialVersionUID = 1L; - - @SuppressWarnings("serial") - public EditParticipantForm(String id, final IModel participantModel) { - super(id); - setModel(participantModel); - - add(new TextField("firstName", new PropertyModel(getModel(), "firstName")).setRequired(true).setLabel(new ResourceModel("FirstName"))); - add(new TextField("lastName", new PropertyModel(getModel(), "lastName")).setRequired(true).setLabel(new ResourceModel("LastName"))); - add(createGenderDropDown()); - add(createBirthDateField()); - add(new TextField("street", new PropertyModel(getModel(), "street"))); - add(new TextField("apartment", new PropertyModel(getModel(), "apartment"))); - add(new TextField("city", new PropertyModel(getModel(), "city"))); - add(createProvinceDropDown()); - add(new TextField("country", new PropertyModel(getModel(), "country"))); - add(new TextField("postalCode", new PropertyModel(getModel(), "postalCode")).add(new PatternValidator(POSTAL_CODE_REGEX))); - add(new TextField("phone", new PropertyModel(getModel(), "phone")).add(new PatternValidator(PHONE_REGEX))); - - @SuppressWarnings("serial") - AjaxSubmitLink submitLink = new AjaxSubmitLink("saveAction") { - protected void onSubmit(AjaxRequestTarget target, Form form) { - Participant participant = (Participant) EditParticipantForm.this.getModelObject(); - participantService.updateParticipant(participant); - EditParticipantPanel.this.parentWindow.close(target); - } - - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(EditParticipantPanel.this.feedbackPanel); - } - }; - add(submitLink); - - @SuppressWarnings("serial") - AjaxLink cancelLink = new AjaxLink("cancelAction") { - @Override - public void onClick(AjaxRequestTarget target) { - EditParticipantPanel.this.parentWindow.close(target); - } - }; - add(cancelLink); - } - - @SuppressWarnings("serial") - private DateField createBirthDateField() { - DateField birthDateField = new DateField("birthDate", new PropertyModel(getModel(), "birthDate")) { - protected DateTextField newDateTextField(String id, PropertyModel dateFieldModel) { - return DateTextField.forDatePattern(id, dateFieldModel, "yyyy-MM-dd"); - } - }; - - birthDateField.setRequired(true); - birthDateField.setLabel(new ResourceModel("BirthDate")); - - return birthDateField; - } - - @SuppressWarnings("serial") - private DropDownChoice createGenderDropDown() { - DropDownChoice genderDropDown = new DropDownChoice("gender", new PropertyModel(getModel(), "gender"), Arrays.asList(Gender.values()), new GenderRenderer()) { - - @Override - protected boolean localizeDisplayValues() { - // Returning true will make the parent class lookup the value returned by the call - // to GenderRenderer.getDisplayValue() as a key in the localizer - // (ie: localizer.getString(renderer.getDisplayValue()) - return true; - } - }; - genderDropDown.setRequired(true); - genderDropDown.setLabel(new ResourceModel("Gender")); - genderDropDown.setOutputMarkupId(true); - - return genderDropDown; - } - - @SuppressWarnings("serial") - private DropDownChoice createProvinceDropDown() { - DropDownChoice provinceDropDown = new DropDownChoice("province", new PropertyModel(getModel(), "province"), Arrays.asList(Province.values()), new ProvinceRenderer()); - provinceDropDown.setRequired(true); - provinceDropDown.setOutputMarkupId(true); - - return provinceDropDown; - } - } - - @SuppressWarnings("serial") - private class GenderRenderer implements IChoiceRenderer { - - public Object getDisplayValue(Object object) { - // Prepend "Gender." to generate the proper resource bundle key - return "Gender." + object.toString(); - } - - public String getIdValue(Object object, int index) { - return object.toString(); - } - } - - @SuppressWarnings("serial") - private class ProvinceRenderer implements IChoiceRenderer { - - public Object getDisplayValue(Object object) { - return object.toString(); - } - - public String getIdValue(Object object, int index) { - return object.toString(); - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import java.util.Arrays; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; +import org.apache.wicket.datetime.markup.html.form.DateTextField; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.extensions.yui.calendar.DateField; +import org.apache.wicket.markup.html.form.DropDownChoice; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.ResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.validator.PatternValidator; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.participant.Province; +import org.obiba.onyx.core.service.ParticipantService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EditParticipantPanel extends Panel { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(EditParticipantPanel.class); + + /** + * Regular expression used to validate postal codes. + * + * Note: - No postal code includes the letters D, F, I, O, Q, or U. - The letters W and Z are used, but are not + * currently used as the first letter. + */ + private static final String POSTAL_CODE_REGEX = "[A-Z&&[^DFIOQUWZ]]\\d[A-Z&&[^DFIOQU]] \\d[A-Z&&[^DFIOQU]]\\d"; + + /** + * Regular expression used to validate phone numbers. + * + * Note: - Dashes are required between different parts of the phone number. - This is obviously very basic validation. + * More could be done here to rule out numbers that confirm to this format but are invalid for other reasons (e.g., + * 000-000-0000 is not a valid phone number). + */ + private static final String PHONE_REGEX = "\\d{3}-\\d{3}-\\d{4}"; + + @SpringBean + private ParticipantService participantService; + + private ModalWindow parentWindow; + + private FeedbackPanel feedbackPanel; + + public EditParticipantPanel(String id, IModel participantModel, ModalWindow parentWindow) { + super(id); + + this.parentWindow = parentWindow; + + Form editParticipantForm = new EditParticipantForm("editParticipantForm", participantModel); + add(editParticipantForm); + + feedbackPanel = new FeedbackPanel("feedback"); + feedbackPanel.setOutputMarkupId(true); + add(feedbackPanel); + } + + private class EditParticipantForm extends Form { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("serial") + public EditParticipantForm(String id, final IModel participantModel) { + super(id); + setModel(participantModel); + + add(new TextField("firstName", new PropertyModel(getModel(), "firstName")).setRequired(true).setLabel(new ResourceModel("FirstName"))); + add(new TextField("lastName", new PropertyModel(getModel(), "lastName")).setRequired(true).setLabel(new ResourceModel("LastName"))); + add(createGenderDropDown()); + add(createBirthDateField()); + add(new TextField("street", new PropertyModel(getModel(), "street"))); + add(new TextField("apartment", new PropertyModel(getModel(), "apartment"))); + add(new TextField("city", new PropertyModel(getModel(), "city"))); + add(createProvinceDropDown()); + add(new TextField("country", new PropertyModel(getModel(), "country"))); + add(new TextField("postalCode", new PropertyModel(getModel(), "postalCode")).add(new PatternValidator(POSTAL_CODE_REGEX))); + add(new TextField("phone", new PropertyModel(getModel(), "phone")).add(new PatternValidator(PHONE_REGEX))); + + @SuppressWarnings("serial") + AjaxSubmitLink submitLink = new AjaxSubmitLink("saveAction") { + protected void onSubmit(AjaxRequestTarget target, Form form) { + Participant participant = (Participant) EditParticipantForm.this.getModelObject(); + participantService.updateParticipant(participant); + EditParticipantPanel.this.parentWindow.close(target); + } + + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(EditParticipantPanel.this.feedbackPanel); + } + }; + add(submitLink); + + @SuppressWarnings("serial") + AjaxLink cancelLink = new AjaxLink("cancelAction") { + @Override + public void onClick(AjaxRequestTarget target) { + EditParticipantPanel.this.parentWindow.close(target); + } + }; + add(cancelLink); + } + + @SuppressWarnings("serial") + private DateField createBirthDateField() { + DateField birthDateField = new DateField("birthDate", new PropertyModel(getModel(), "birthDate")) { + protected DateTextField newDateTextField(String id, PropertyModel dateFieldModel) { + return DateTextField.forDatePattern(id, dateFieldModel, "yyyy-MM-dd"); + } + }; + + birthDateField.setRequired(true); + birthDateField.setLabel(new ResourceModel("BirthDate")); + + return birthDateField; + } + + @SuppressWarnings("serial") + private DropDownChoice createGenderDropDown() { + DropDownChoice genderDropDown = new DropDownChoice("gender", new PropertyModel(getModel(), "gender"), Arrays.asList(Gender.values()), new GenderRenderer()) { + + @Override + protected boolean localizeDisplayValues() { + // Returning true will make the parent class lookup the value returned by the call + // to GenderRenderer.getDisplayValue() as a key in the localizer + // (ie: localizer.getString(renderer.getDisplayValue()) + return true; + } + }; + genderDropDown.setRequired(true); + genderDropDown.setLabel(new ResourceModel("Gender")); + genderDropDown.setOutputMarkupId(true); + + return genderDropDown; + } + + @SuppressWarnings("serial") + private DropDownChoice createProvinceDropDown() { + DropDownChoice provinceDropDown = new DropDownChoice("province", new PropertyModel(getModel(), "province"), Arrays.asList(Province.values()), new ProvinceRenderer()); + provinceDropDown.setRequired(true); + provinceDropDown.setOutputMarkupId(true); + + return provinceDropDown; + } + } + + @SuppressWarnings("serial") + private class GenderRenderer implements IChoiceRenderer { + + public Object getDisplayValue(Object object) { + // Prepend "Gender." to generate the proper resource bundle key + return "Gender." + object.toString(); + } + + public String getIdValue(Object object, int index) { + return object.toString(); + } + } + + @SuppressWarnings("serial") + private class ProvinceRenderer implements IChoiceRenderer { + + public Object getDisplayValue(Object object) { + return object.toString(); + } + + public String getIdValue(Object object, int index) { + return object.toString(); + } + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantModalPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantModalPanel.java index 3f5e7918c..8616878aa 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantModalPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantModalPanel.java @@ -1,24 +1,33 @@ -package org.obiba.onyx.webapp.participant.panel; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; - -public class ParticipantModalPanel extends Panel { - - public ParticipantModalPanel(String id, Panel contentPanel, final ModalWindow modalWindow) { - super(id); - - add(contentPanel); - - AjaxLink link = new AjaxLink("closeAction") { - @Override - public void onClick(AjaxRequestTarget target) { - modalWindow.close(target); - } - }; - - add(link); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; + +public class ParticipantModalPanel extends Panel { + + public ParticipantModalPanel(String id, Panel contentPanel, final ModalWindow modalWindow) { + super(id); + + add(contentPanel); + + AjaxLink link = new AjaxLink("closeAction") { + @Override + public void onClick(AjaxRequestTarget target) { + modalWindow.close(target); + } + }; + + add(link); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantPanel.java index 2b66f30b1..4fa9da26c 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/ParticipantPanel.java @@ -1,51 +1,60 @@ -package org.obiba.onyx.webapp.participant.panel; - -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.wicket.util.DateModelUtils; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; - -public class ParticipantPanel extends Panel { - - private static final long serialVersionUID = -5722864134344016349L; - - public ParticipantPanel(String id, IModel participantModel) { - this(id, participantModel, false); - } - - public ParticipantPanel(String id, IModel participantModel, boolean shortList) { - super(id); - setModel(participantModel); - setOutputMarkupId(true); - - KeyValueDataPanel kvPanel = new KeyValueDataPanel("participant"); - - Participant participant = (Participant) participantModel.getObject(); - if(participant.getBarcode() != null) { - kvPanel.addRow(new StringResourceModel("ParticipantCode", this, null), new PropertyModel(getModel(), "barcode")); - } - kvPanel.addRow(new StringResourceModel("AppointmentCode", this, null), new PropertyModel(getModel(), "enrollmentId")); - kvPanel.addRow(new StringResourceModel("Name", this, null), new PropertyModel(getModel(), "fullName")); - kvPanel.addRow(new StringResourceModel("Gender", this, null), new PropertyModel(this, "localizedGender")); - kvPanel.addRow(new StringResourceModel("BirthDate", this, null), DateModelUtils.getShortDateModel(new PropertyModel(getModel(), "birthDate"))); - - if(!shortList) { - kvPanel.addRow(new StringResourceModel("Street", this, null), new PropertyModel(getModel(), "street")); - kvPanel.addRow(new StringResourceModel("Apartment", this, null), new PropertyModel(getModel(), "apartment")); - kvPanel.addRow(new StringResourceModel("City", this, null), new PropertyModel(getModel(), "city")); - kvPanel.addRow(new StringResourceModel("Province", this, null), new PropertyModel(getModel(), "province")); - kvPanel.addRow(new StringResourceModel("Country", this, null), new PropertyModel(getModel(), "country")); - kvPanel.addRow(new StringResourceModel("PostalCode", this, null), new PropertyModel(getModel(), "postalCode")); - kvPanel.addRow(new StringResourceModel("Phone", this, null), new PropertyModel(getModel(), "phone")); - } - - add(kvPanel); - } - - public String getLocalizedGender() { - return getString("Gender." + ((Participant) getModelObject()).getGender()); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.wicket.util.DateModelUtils; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; + +public class ParticipantPanel extends Panel { + + private static final long serialVersionUID = -5722864134344016349L; + + public ParticipantPanel(String id, IModel participantModel) { + this(id, participantModel, false); + } + + public ParticipantPanel(String id, IModel participantModel, boolean shortList) { + super(id); + setModel(participantModel); + setOutputMarkupId(true); + + KeyValueDataPanel kvPanel = new KeyValueDataPanel("participant"); + + Participant participant = (Participant) participantModel.getObject(); + if(participant.getBarcode() != null) { + kvPanel.addRow(new StringResourceModel("ParticipantCode", this, null), new PropertyModel(getModel(), "barcode")); + } + kvPanel.addRow(new StringResourceModel("AppointmentCode", this, null), new PropertyModel(getModel(), "enrollmentId")); + kvPanel.addRow(new StringResourceModel("Name", this, null), new PropertyModel(getModel(), "fullName")); + kvPanel.addRow(new StringResourceModel("Gender", this, null), new PropertyModel(this, "localizedGender")); + kvPanel.addRow(new StringResourceModel("BirthDate", this, null), DateModelUtils.getShortDateModel(new PropertyModel(getModel(), "birthDate"))); + + if(!shortList) { + kvPanel.addRow(new StringResourceModel("Street", this, null), new PropertyModel(getModel(), "street")); + kvPanel.addRow(new StringResourceModel("Apartment", this, null), new PropertyModel(getModel(), "apartment")); + kvPanel.addRow(new StringResourceModel("City", this, null), new PropertyModel(getModel(), "city")); + kvPanel.addRow(new StringResourceModel("Province", this, null), new PropertyModel(getModel(), "province")); + kvPanel.addRow(new StringResourceModel("Country", this, null), new PropertyModel(getModel(), "country")); + kvPanel.addRow(new StringResourceModel("PostalCode", this, null), new PropertyModel(getModel(), "postalCode")); + kvPanel.addRow(new StringResourceModel("Phone", this, null), new PropertyModel(getModel(), "phone")); + } + + add(kvPanel); + } + + public String getLocalizedGender() { + return getString("Gender." + ((Participant) getModelObject()).getGender()); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/OnyxDatabaseSeed.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/OnyxDatabaseSeed.java index f4e35a388..44c691d1b 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/OnyxDatabaseSeed.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/OnyxDatabaseSeed.java @@ -1,47 +1,56 @@ -package org.obiba.onyx.webapp.seed; - -import java.util.List; - -import org.apache.wicket.protocol.http.WebApplication; -import org.obiba.core.service.PersistenceManager; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.StageDependencyCondition; -import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.thoughtworks.xstream.XStream; - -public class OnyxDatabaseSeed extends XstreamResourceDatabaseSeed { - private final Logger log = LoggerFactory.getLogger(getClass()); - - private PersistenceManager persistenceManager; - - public void setPersistenceManager(PersistenceManager persistenceManager) { - this.persistenceManager = persistenceManager; - } - - @SuppressWarnings("unchecked") - @Override - protected void handleXstreamResult(Object result) { - if(result != null && result instanceof List) { - List objects = (List) result; - for(Object entity : objects) { - log.info("Seeding database with entity {} of type {}", entity, entity.getClass().getSimpleName()); - persistenceManager.save(entity); - } - } - } - - @Override - protected boolean shouldSeed(WebApplication application) { - return (persistenceManager.count(Stage.class) == 0); - } - - @Override - protected void initializeXstream(XStream xstream) { - super.initializeXstream(xstream); - xstream.alias("stage", Stage.class); - xstream.alias("stageDependencyCondition", StageDependencyCondition.class); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.seed; + +import java.util.List; + +import org.apache.wicket.protocol.http.WebApplication; +import org.obiba.core.service.PersistenceManager; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.StageDependencyCondition; +import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.thoughtworks.xstream.XStream; + +public class OnyxDatabaseSeed extends XstreamResourceDatabaseSeed { + private final Logger log = LoggerFactory.getLogger(getClass()); + + private PersistenceManager persistenceManager; + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + @SuppressWarnings("unchecked") + @Override + protected void handleXstreamResult(Object result) { + if(result != null && result instanceof List) { + List objects = (List) result; + for(Object entity : objects) { + log.info("Seeding database with entity {} of type {}", entity, entity.getClass().getSimpleName()); + persistenceManager.save(entity); + } + } + } + + @Override + protected boolean shouldSeed(WebApplication application) { + return (persistenceManager.count(Stage.class) == 0); + } + + @Override + protected void initializeXstream(XStream xstream) { + super.initializeXstream(xstream); + xstream.alias("stage", Stage.class); + xstream.alias("stageDependencyCondition", StageDependencyCondition.class); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/TestDatabaseSeed.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/TestDatabaseSeed.java index b0a702ffb..18478e068 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/TestDatabaseSeed.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/seed/TestDatabaseSeed.java @@ -1,99 +1,108 @@ -package org.obiba.onyx.webapp.seed; - -import java.io.File; -import java.util.List; - -import javax.servlet.ServletContext; - -import org.apache.wicket.protocol.http.WebApplication; -import org.obiba.core.service.PersistenceManager; -import org.obiba.onyx.core.domain.application.ApplicationConfiguration; -import org.obiba.onyx.core.domain.participant.Appointment; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -import com.thoughtworks.xstream.XStream; - -public class TestDatabaseSeed extends XstreamResourceDatabaseSeed { - private final Logger log = LoggerFactory.getLogger(getClass()); - - private PersistenceManager persistenceManager; - - public void setPersistenceManager(PersistenceManager persistenceManager) { - this.persistenceManager = persistenceManager; - } - - @SuppressWarnings("unchecked") - @Override - protected void handleXstreamResult(Resource resource, Object result) { - if(result != null && result instanceof List) { - List objects = (List) result; - for(Object entity : objects) { - - // Encrypt password - if(entity instanceof User) { - User user = (User) entity; - String encryptedPassword = User.digest(user.getPassword()); - user.setPassword(encryptedPassword); - log.info("Password: " + user.getPassword()); - log.info("Encypted Password: " + encryptedPassword); - - User template = new User(); - template.setLogin(user.getLogin()); - for(User u : persistenceManager.match(template)) { - persistenceManager.delete(u); - } - if(persistenceManager.count(template) > 0) entity = null; - } else if(entity instanceof ApplicationConfiguration) { - ApplicationConfiguration template = new ApplicationConfiguration(); - for(ApplicationConfiguration conf : persistenceManager.match(template)) { - persistenceManager.delete(conf); - } - ApplicationConfiguration appConfig = (ApplicationConfiguration) entity; - File participantDirectory = new File(appConfig.getParticipantDirectoryPath()); - log.debug("participantDirectoryPath={}", appConfig.getParticipantDirectoryPath()); - if(!participantDirectory.exists()) { - // get the webapp root from servlet context - ServletContext context = ((WebApplication) WebApplication.get()).getServletContext(); - appConfig.setParticipantDirectoryPath(context.getRealPath(appConfig.getParticipantDirectoryPath())); - participantDirectory = new File(appConfig.getParticipantDirectoryPath()); - log.debug("new participantDirectoryPath={}", appConfig.getParticipantDirectoryPath()); - if(!participantDirectory.exists()) { - throw new IllegalArgumentException("Wrong participant repository: " + appConfig.getParticipantDirectoryPath()); - } - } - } - - if(entity != null) { - log.info("Seeding database with entity {} of type {}", entity, entity.getClass().getSimpleName()); - persistenceManager.save(entity); - } - } - } - } - - @Override - protected boolean shouldSeed(WebApplication application) { - boolean seed = super.shouldSeed(application); - return seed && (persistenceManager.count(User.class) == 0); - } - - @Override - protected void initializeXstream(XStream xstream) { - super.initializeXstream(xstream); - - xstream.alias("config", ApplicationConfiguration.class); - xstream.alias("role", Role.class); - xstream.alias("user", User.class); - xstream.alias("participant", Participant.class); - xstream.alias("interview", Interview.class); - xstream.alias("appointment", Appointment.class); - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.seed; + +import java.io.File; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.apache.wicket.protocol.http.WebApplication; +import org.obiba.core.service.PersistenceManager; +import org.obiba.onyx.core.domain.application.ApplicationConfiguration; +import org.obiba.onyx.core.domain.participant.Appointment; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.wicket.util.seed.XstreamResourceDatabaseSeed; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.Resource; + +import com.thoughtworks.xstream.XStream; + +public class TestDatabaseSeed extends XstreamResourceDatabaseSeed { + private final Logger log = LoggerFactory.getLogger(getClass()); + + private PersistenceManager persistenceManager; + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + @SuppressWarnings("unchecked") + @Override + protected void handleXstreamResult(Resource resource, Object result) { + if(result != null && result instanceof List) { + List objects = (List) result; + for(Object entity : objects) { + + // Encrypt password + if(entity instanceof User) { + User user = (User) entity; + String encryptedPassword = User.digest(user.getPassword()); + user.setPassword(encryptedPassword); + log.info("Password: " + user.getPassword()); + log.info("Encypted Password: " + encryptedPassword); + + User template = new User(); + template.setLogin(user.getLogin()); + for(User u : persistenceManager.match(template)) { + persistenceManager.delete(u); + } + if(persistenceManager.count(template) > 0) entity = null; + } else if(entity instanceof ApplicationConfiguration) { + ApplicationConfiguration template = new ApplicationConfiguration(); + for(ApplicationConfiguration conf : persistenceManager.match(template)) { + persistenceManager.delete(conf); + } + ApplicationConfiguration appConfig = (ApplicationConfiguration) entity; + File participantDirectory = new File(appConfig.getParticipantDirectoryPath()); + log.debug("participantDirectoryPath={}", appConfig.getParticipantDirectoryPath()); + if(!participantDirectory.exists()) { + // get the webapp root from servlet context + ServletContext context = ((WebApplication) WebApplication.get()).getServletContext(); + appConfig.setParticipantDirectoryPath(context.getRealPath(appConfig.getParticipantDirectoryPath())); + participantDirectory = new File(appConfig.getParticipantDirectoryPath()); + log.debug("new participantDirectoryPath={}", appConfig.getParticipantDirectoryPath()); + if(!participantDirectory.exists()) { + throw new IllegalArgumentException("Wrong participant repository: " + appConfig.getParticipantDirectoryPath()); + } + } + } + + if(entity != null) { + log.info("Seeding database with entity {} of type {}", entity, entity.getClass().getSimpleName()); + persistenceManager.save(entity); + } + } + } + } + + @Override + protected boolean shouldSeed(WebApplication application) { + boolean seed = super.shouldSeed(application); + return seed && (persistenceManager.count(User.class) == 0); + } + + @Override + protected void initializeXstream(XStream xstream) { + super.initializeXstream(xstream); + + xstream.alias("config", ApplicationConfiguration.class); + xstream.alias("role", Role.class); + xstream.alias("user", User.class); + xstream.alias("participant", Participant.class); + xstream.alias("interview", Interview.class); + xstream.alias("appointment", Appointment.class); + + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/service/impl/UserSessionServiceImpl.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/service/impl/UserSessionServiceImpl.java index 14df898e3..2ae911620 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/service/impl/UserSessionServiceImpl.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/service/impl/UserSessionServiceImpl.java @@ -1,23 +1,32 @@ -package org.obiba.onyx.webapp.service.impl; - -import java.util.Locale; - -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; - -public class UserSessionServiceImpl implements UserSessionService { - - public Locale getLocale() { - return OnyxAuthenticatedSession.get().getLocale(); - } - - public void setLocale(Locale locale) { - OnyxAuthenticatedSession.get().setLocale(locale); - } - - public User getUser() { - return OnyxAuthenticatedSession.get().getUser(); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.service.impl; + +import java.util.Locale; + +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; + +public class UserSessionServiceImpl implements UserSessionService { + + public Locale getLocale() { + return OnyxAuthenticatedSession.get().getLocale(); + } + + public void setLocale(Locale locale) { + OnyxAuthenticatedSession.get().setLocale(locale); + } + + public User getUser() { + return OnyxAuthenticatedSession.get().getUser(); + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/page/StagePage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/page/StagePage.java index 38d40d3cc..32e142ac7 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/page/StagePage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/page/StagePage.java @@ -1,85 +1,94 @@ -package org.obiba.onyx.webapp.stage.page; - -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.markup.html.panel.EmptyPanel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.protocol.http.WebApplication; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.participant.page.InterviewPage; -import org.obiba.onyx.webapp.stage.panel.StageHeaderPanel; -import org.obiba.onyx.webapp.stage.panel.StageMenuBar; -import org.obiba.onyx.wicket.IEngineComponentAware; -import org.obiba.onyx.wicket.action.ActionWindow; - -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) -public class StagePage extends BasePage { - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - private StageMenuBar menuBar; - - @SuppressWarnings("serial") - public StagePage(IModel stageModel) { - super(); - setMenuBarVisible(true); - setModel(stageModel); - - Participant participant = activeInterviewService.getParticipant(); - - if(participant == null) { - setResponsePage(WebApplication.get().getHomePage()); - } else { - // - // Modify header. - // - remove("header"); - add(new StageHeaderPanel("header")); - - // - // Modify menu bar. - // - remove("menuBar"); - menuBar = new StageMenuBar("menuBar", stageModel); - add(menuBar); - - IStageExecution exec = activeInterviewService.getStageExecution((Stage) getModelObject()); - - final ActionWindow modal; - add(modal = new ActionWindow("modal") { - - @Override - public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { - IStageExecution exec = activeInterviewService.getStageExecution(stage); - if(!exec.isInteractive()) { - setResponsePage(InterviewPage.class); - } else { - setResponsePage(new StagePage(StagePage.this.getModel())); - } - } - - }); - - if(!exec.isInteractive()) { - add(new EmptyPanel("stage-component")); - } else { - Component stageComponent = exec.getWidget("stage-component"); - if(stageComponent instanceof IEngineComponentAware) { - IEngineComponentAware comp = (IEngineComponentAware) stageComponent; - comp.setActionWindwon(modal); - comp.setFeedbackPanel(getFeedbackPanel()); - } - add(stageComponent); - } - } - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.page; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.markup.html.panel.EmptyPanel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.participant.page.InterviewPage; +import org.obiba.onyx.webapp.stage.panel.StageHeaderPanel; +import org.obiba.onyx.webapp.stage.panel.StageMenuBar; +import org.obiba.onyx.wicket.IEngineComponentAware; +import org.obiba.onyx.wicket.action.ActionWindow; + +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR", "PARTICIPANT_MANAGER", "DATA_COLLECTION_OPERATOR" }) +public class StagePage extends BasePage { + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + private StageMenuBar menuBar; + + @SuppressWarnings("serial") + public StagePage(IModel stageModel) { + super(); + setMenuBarVisible(true); + setModel(stageModel); + + Participant participant = activeInterviewService.getParticipant(); + + if(participant == null) { + setResponsePage(WebApplication.get().getHomePage()); + } else { + // + // Modify header. + // + remove("header"); + add(new StageHeaderPanel("header")); + + // + // Modify menu bar. + // + remove("menuBar"); + menuBar = new StageMenuBar("menuBar", stageModel); + add(menuBar); + + IStageExecution exec = activeInterviewService.getStageExecution((Stage) getModelObject()); + + final ActionWindow modal; + add(modal = new ActionWindow("modal") { + + @Override + public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { + IStageExecution exec = activeInterviewService.getStageExecution(stage); + if(!exec.isInteractive()) { + setResponsePage(InterviewPage.class); + } else { + setResponsePage(new StagePage(StagePage.this.getModel())); + } + } + + }); + + if(!exec.isInteractive()) { + add(new EmptyPanel("stage-component")); + } else { + Component stageComponent = exec.getWidget("stage-component"); + if(stageComponent instanceof IEngineComponentAware) { + IEngineComponentAware comp = (IEngineComponentAware) stageComponent; + comp.setActionWindwon(modal); + comp.setFeedbackPanel(getFeedbackPanel()); + } + add(stageComponent); + } + } + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageHeaderPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageHeaderPanel.java index 8e493adc6..5ddfd8154 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageHeaderPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageHeaderPanel.java @@ -1,15 +1,24 @@ -package org.obiba.onyx.webapp.stage.panel; - -import org.obiba.onyx.webapp.base.panel.HeaderPanel; - -public class StageHeaderPanel extends HeaderPanel { - - private static final long serialVersionUID = 7480791934966023398L; - - public StageHeaderPanel(String id) { - super(id); - - remove("profile"); - remove("quit"); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.panel; + +import org.obiba.onyx.webapp.base.panel.HeaderPanel; + +public class StageHeaderPanel extends HeaderPanel { + + private static final long serialVersionUID = 7480791934966023398L; + + public StageHeaderPanel(String id) { + super(id); + + remove("profile"); + remove("quit"); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageMenuBar.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageMenuBar.java index cc4ddbf0a..4923da11e 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageMenuBar.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageMenuBar.java @@ -1,32 +1,41 @@ -package org.obiba.onyx.webapp.stage.panel; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.webapp.base.panel.MenuBar; -import org.obiba.onyx.wicket.util.DateModelUtils; - -public class StageMenuBar extends MenuBar { - - private static final long serialVersionUID = 8805458043658346936L; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - public StageMenuBar(String id, IModel stageModel) { - super(id); - setOutputMarkupId(true); - - Participant participant = activeInterviewService.getParticipant(); - - add(new Label("stageLabel", new PropertyModel(stageModel, "description"))); - add(new Label("participantLabel", participant.getFullName() + " | " + participant.getBarcode())); - add(new Label("birthDateLabel", DateModelUtils.getDateModel(new PropertyModel(participant, "birthDate")))); - } - - protected void buildMenus() { - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.panel; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.webapp.base.panel.MenuBar; +import org.obiba.onyx.wicket.util.DateModelUtils; + +public class StageMenuBar extends MenuBar { + + private static final long serialVersionUID = 8805458043658346936L; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + public StageMenuBar(String id, IModel stageModel) { + super(id); + setOutputMarkupId(true); + + Participant participant = activeInterviewService.getParticipant(); + + add(new Label("stageLabel", new PropertyModel(stageModel, "description"))); + add(new Label("participantLabel", participant.getFullName() + " | " + participant.getBarcode())); + add(new Label("birthDateLabel", DateModelUtils.getDateModel(new PropertyModel(participant, "birthDate")))); + } + + protected void buildMenus() { + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageSelectionPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageSelectionPanel.java index 374f0a8f4..c32686380 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageSelectionPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageSelectionPanel.java @@ -1,230 +1,239 @@ -package org.obiba.onyx.webapp.stage.panel; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.util.value.ValueMap; -import org.obiba.onyx.core.domain.participant.InterviewStatus; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.webapp.action.panel.ActionsPanel; -import org.obiba.onyx.webapp.panel.OnyxEntityList; -import org.obiba.onyx.webapp.stage.page.StagePage; -import org.obiba.onyx.wicket.StageModel; -import org.obiba.onyx.wicket.action.ActionWindow; -import org.obiba.wicket.markup.html.table.IColumnProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class StageSelectionPanel extends Panel { - - private static final long serialVersionUID = 6282742572162384139L; - - @SuppressWarnings("unused") - private static final Logger log = LoggerFactory.getLogger(StageSelectionPanel.class); - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - @SpringBean - private ModuleRegistry moduleRegistry; - - private ActionWindow modal; - - private OnyxEntityList list; - - private FeedbackPanel feedbackPanel; - - @SuppressWarnings("serial") - public StageSelectionPanel(String id, FeedbackPanel feedbackPanel) { - super(id); - setOutputMarkupId(true); - - this.feedbackPanel = feedbackPanel; - - checkStageStatus(); - - add(modal = new ActionWindow("modal") { - - @Override - public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { - IStageExecution exec = activeInterviewService.getStageExecution(stage); - if(!exec.isInteractive()) { - checkStageStatus(); - target.addComponent(StageSelectionPanel.this.feedbackPanel); - target.addComponent(list); - StageSelectionPanel.this.onActionPerformed(target, stage, action); - } else { - setResponsePage(new StagePage(new StageModel(moduleRegistry, stage))); - } - } - - }); - - add(list = new OnyxEntityList("list", new StageProvider(), new StageListColumnProvider(), new StringResourceModel("StageList", StageSelectionPanel.this, null))); - } - - private void checkStageStatus() { - for(Stage stage : moduleRegistry.listStages()) { - IStageExecution exec = activeInterviewService.getStageExecution(stage); - if(exec.isInteractive()) { - log.warn("Wrong status for " + stage.getName()); - feedbackPanel.warn(getString("WrongStatusForStage", new Model(new ValueMap("name=" + stage.getDescription())))); - } - } - } - - abstract public void onViewComments(AjaxRequestTarget target); - - abstract public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action); - - private class StageProvider extends SortableDataProvider { - - private static final long serialVersionUID = 6022606267778864539L; - - public StageProvider() { - } - - public Iterator iterator(int first, int count) { - List stages = moduleRegistry.listStages(); - return stages.iterator(); - } - - public IModel model(Object object) { - return new StageModel(moduleRegistry, (Stage) object); - } - - public int size() { - return moduleRegistry.listStages().size(); - } - - } - - private class StageListColumnProvider implements IColumnProvider, Serializable { - - private static final long serialVersionUID = -9121583835345457007L; - - private List columns = new ArrayList(); - - private List additional = new ArrayList(); - - @SuppressWarnings("serial") - public StageListColumnProvider() { - columns.add(new PropertyColumn(new Model("#"), "displayOrder")); - - columns.add(new AbstractColumn(new StringResourceModel("Name", StageSelectionPanel.this, null)) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - cellItem.add(new Label(componentId, new PropertyModel(rowModel, "description"))); - } - - }); - - columns.add(new AbstractColumn(new StringResourceModel("Status", StageSelectionPanel.this, null)) { - - public void populateItem(Item cellItem, String componentId, final IModel rowModel) { - cellItem.add(new Label(componentId, new Model() { - public Object getObject() { - Stage stage = (Stage) rowModel.getObject(); - IStageExecution exec = activeInterviewService.getStageExecution(stage); - return exec.getMessage(); - } - })); - } - - }); - - columns.add(new AbstractColumn(new StringResourceModel("StartEndTime", StageSelectionPanel.this, null)) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Stage stage = (Stage) rowModel.getObject(); - cellItem.add(new StageStartEndTimePanel(componentId, stage)); - } - - }); - - if(activeInterviewService.getInterview().getStatus().equals(InterviewStatus.IN_PROGRESS)) { - columns.add(new AbstractColumn(new Model("Actions")) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - Stage stage = (Stage) rowModel.getObject(); - IStageExecution exec = activeInterviewService.getStageExecution(stage); - cellItem.add(new ActionsPanel(componentId, rowModel, exec, modal)); - } - - }); - } - - columns.add(new AbstractColumn(new StringResourceModel("Comments", StageSelectionPanel.this, null)) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - List interviewComments = activeInterviewService.getInterviewComments(); - Stage stage = (Stage) rowModel.getObject(); - - boolean foundActionComments = false; - for(Action action : interviewComments) { - if(action.getStage() != null && action.getStage().equals(stage.getName())) { - foundActionComments = true; - break; - } - } - - // Show link only if there are existing comments for the selected Stage - if(foundActionComments) { - cellItem.add(new ViewCommentsActionPanel(componentId) { - - private static final long serialVersionUID = 1L; - - @Override - public void onViewComments(AjaxRequestTarget target) { - StageSelectionPanel.this.onViewComments(target); - } - - }); - - } else { - cellItem.add(new Label(componentId, "")); - } - } - - }); - - } - - public List getAdditionalColumns() { - return additional; - } - - public List getColumnHeaderNames() { - return null; - } - - public List getDefaultColumns() { - return columns; - } - - public List getRequiredColumns() { - return columns; - } - - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.panel; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.value.ValueMap; +import org.obiba.onyx.core.domain.participant.InterviewStatus; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.webapp.action.panel.ActionsPanel; +import org.obiba.onyx.webapp.panel.OnyxEntityList; +import org.obiba.onyx.webapp.stage.page.StagePage; +import org.obiba.onyx.wicket.StageModel; +import org.obiba.onyx.wicket.action.ActionWindow; +import org.obiba.wicket.markup.html.table.IColumnProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class StageSelectionPanel extends Panel { + + private static final long serialVersionUID = 6282742572162384139L; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(StageSelectionPanel.class); + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + @SpringBean + private ModuleRegistry moduleRegistry; + + private ActionWindow modal; + + private OnyxEntityList list; + + private FeedbackPanel feedbackPanel; + + @SuppressWarnings("serial") + public StageSelectionPanel(String id, FeedbackPanel feedbackPanel) { + super(id); + setOutputMarkupId(true); + + this.feedbackPanel = feedbackPanel; + + checkStageStatus(); + + add(modal = new ActionWindow("modal") { + + @Override + public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action) { + IStageExecution exec = activeInterviewService.getStageExecution(stage); + if(!exec.isInteractive()) { + checkStageStatus(); + target.addComponent(StageSelectionPanel.this.feedbackPanel); + target.addComponent(list); + StageSelectionPanel.this.onActionPerformed(target, stage, action); + } else { + setResponsePage(new StagePage(new StageModel(moduleRegistry, stage))); + } + } + + }); + + add(list = new OnyxEntityList("list", new StageProvider(), new StageListColumnProvider(), new StringResourceModel("StageList", StageSelectionPanel.this, null))); + } + + private void checkStageStatus() { + for(Stage stage : moduleRegistry.listStages()) { + IStageExecution exec = activeInterviewService.getStageExecution(stage); + if(exec.isInteractive()) { + log.warn("Wrong status for " + stage.getName()); + feedbackPanel.warn(getString("WrongStatusForStage", new Model(new ValueMap("name=" + stage.getDescription())))); + } + } + } + + abstract public void onViewComments(AjaxRequestTarget target); + + abstract public void onActionPerformed(AjaxRequestTarget target, Stage stage, Action action); + + private class StageProvider extends SortableDataProvider { + + private static final long serialVersionUID = 6022606267778864539L; + + public StageProvider() { + } + + public Iterator iterator(int first, int count) { + List stages = moduleRegistry.listStages(); + return stages.iterator(); + } + + public IModel model(Object object) { + return new StageModel(moduleRegistry, (Stage) object); + } + + public int size() { + return moduleRegistry.listStages().size(); + } + + } + + private class StageListColumnProvider implements IColumnProvider, Serializable { + + private static final long serialVersionUID = -9121583835345457007L; + + private List columns = new ArrayList(); + + private List additional = new ArrayList(); + + @SuppressWarnings("serial") + public StageListColumnProvider() { + columns.add(new PropertyColumn(new Model("#"), "displayOrder")); + + columns.add(new AbstractColumn(new StringResourceModel("Name", StageSelectionPanel.this, null)) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + cellItem.add(new Label(componentId, new PropertyModel(rowModel, "description"))); + } + + }); + + columns.add(new AbstractColumn(new StringResourceModel("Status", StageSelectionPanel.this, null)) { + + public void populateItem(Item cellItem, String componentId, final IModel rowModel) { + cellItem.add(new Label(componentId, new Model() { + public Object getObject() { + Stage stage = (Stage) rowModel.getObject(); + IStageExecution exec = activeInterviewService.getStageExecution(stage); + return exec.getMessage(); + } + })); + } + + }); + + columns.add(new AbstractColumn(new StringResourceModel("StartEndTime", StageSelectionPanel.this, null)) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Stage stage = (Stage) rowModel.getObject(); + cellItem.add(new StageStartEndTimePanel(componentId, stage)); + } + + }); + + if(activeInterviewService.getInterview().getStatus().equals(InterviewStatus.IN_PROGRESS)) { + columns.add(new AbstractColumn(new Model("Actions")) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + Stage stage = (Stage) rowModel.getObject(); + IStageExecution exec = activeInterviewService.getStageExecution(stage); + cellItem.add(new ActionsPanel(componentId, rowModel, exec, modal)); + } + + }); + } + + columns.add(new AbstractColumn(new StringResourceModel("Comments", StageSelectionPanel.this, null)) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + List interviewComments = activeInterviewService.getInterviewComments(); + Stage stage = (Stage) rowModel.getObject(); + + boolean foundActionComments = false; + for(Action action : interviewComments) { + if(action.getStage() != null && action.getStage().equals(stage.getName())) { + foundActionComments = true; + break; + } + } + + // Show link only if there are existing comments for the selected Stage + if(foundActionComments) { + cellItem.add(new ViewCommentsActionPanel(componentId) { + + private static final long serialVersionUID = 1L; + + @Override + public void onViewComments(AjaxRequestTarget target) { + StageSelectionPanel.this.onViewComments(target); + } + + }); + + } else { + cellItem.add(new Label(componentId, "")); + } + } + + }); + + } + + public List getAdditionalColumns() { + return additional; + } + + public List getColumnHeaderNames() { + return null; + } + + public List getDefaultColumns() { + return columns; + } + + public List getRequiredColumns() { + return columns; + } + + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageStartEndTimePanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageStartEndTimePanel.java index d08802320..a2291491f 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageStartEndTimePanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/StageStartEndTimePanel.java @@ -1,59 +1,68 @@ -package org.obiba.onyx.webapp.stage.panel; - -import java.util.List; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.Stage; -import org.obiba.onyx.engine.state.IStageExecution; -import org.obiba.onyx.wicket.util.DateModelUtils; - -public class StageStartEndTimePanel extends Panel { - - @SpringBean - private EntityQueryService queryService; - - @SpringBean(name = "activeInterviewService") - private ActiveInterviewService activeInterviewService; - - private static final long serialVersionUID = 1L; - - public StageStartEndTimePanel(String id, Stage stage) { - super(id); - - Action template = new Action(); - template.setInterview(activeInterviewService.getInterview()); - template.setStage(stage.getName()); - - List actionList = queryService.match(template); - - // Find the last action of type EXECUTE for this stage - // Also save the last action in the list (most recent action) - Action lastExecuteAction = null; - Action lastAction = null; - for(Action action : actionList) { - if(action.getActionType() == ActionType.EXECUTE) lastExecuteAction = action; - lastAction = action; - } - - IStageExecution exec = activeInterviewService.getStageExecution(stage); - - if(exec.isCompleted() && (exec.getStartingActionType() == ActionType.EXECUTE)) { - add(new Label("endTime", DateModelUtils.getShortDateTimeModel(new PropertyModel(lastAction, "dateTime")))); - add(new Label("separator", "-")); - add(new Label("startTime", DateModelUtils.getShortDateTimeModel(new PropertyModel(lastExecuteAction, "dateTime")))); - } else { - add(new Label("endTime", "")); - add(new Label("separator", "")); - add(new Label("startTime", "")); - } - - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.panel; + +import java.util.List; + +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.Stage; +import org.obiba.onyx.engine.state.IStageExecution; +import org.obiba.onyx.wicket.util.DateModelUtils; + +public class StageStartEndTimePanel extends Panel { + + @SpringBean + private EntityQueryService queryService; + + @SpringBean(name = "activeInterviewService") + private ActiveInterviewService activeInterviewService; + + private static final long serialVersionUID = 1L; + + public StageStartEndTimePanel(String id, Stage stage) { + super(id); + + Action template = new Action(); + template.setInterview(activeInterviewService.getInterview()); + template.setStage(stage.getName()); + + List actionList = queryService.match(template); + + // Find the last action of type EXECUTE for this stage + // Also save the last action in the list (most recent action) + Action lastExecuteAction = null; + Action lastAction = null; + for(Action action : actionList) { + if(action.getActionType() == ActionType.EXECUTE) lastExecuteAction = action; + lastAction = action; + } + + IStageExecution exec = activeInterviewService.getStageExecution(stage); + + if(exec.isCompleted() && (exec.getStartingActionType() == ActionType.EXECUTE)) { + add(new Label("endTime", DateModelUtils.getShortDateTimeModel(new PropertyModel(lastAction, "dateTime")))); + add(new Label("separator", "-")); + add(new Label("startTime", DateModelUtils.getShortDateTimeModel(new PropertyModel(lastExecuteAction, "dateTime")))); + } else { + add(new Label("endTime", "")); + add(new Label("separator", "")); + add(new Label("startTime", "")); + } + + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/ViewCommentsActionPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/ViewCommentsActionPanel.java index 1ff817a6c..75c7f0bbc 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/ViewCommentsActionPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/stage/panel/ViewCommentsActionPanel.java @@ -1,25 +1,34 @@ -package org.obiba.onyx.webapp.stage.panel; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.markup.html.panel.Panel; - -abstract public class ViewCommentsActionPanel extends Panel { - - private static final long serialVersionUID = 1L; - - public ViewCommentsActionPanel(String id) { - super(id); - add(new AjaxLink("viewComments") { - - private static final long serialVersionUID = 1L; - - public void onClick(AjaxRequestTarget target) { - ViewCommentsActionPanel.this.onViewComments(target); - } - }); - } - - public abstract void onViewComments(AjaxRequestTarget target); - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.stage.panel; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.markup.html.panel.Panel; + +abstract public class ViewCommentsActionPanel extends Panel { + + private static final long serialVersionUID = 1L; + + public ViewCommentsActionPanel(String id) { + super(id); + add(new AjaxLink("viewComments") { + + private static final long serialVersionUID = 1L; + + public void onClick(AjaxRequestTarget target) { + ViewCommentsActionPanel.this.onViewComments(target); + } + }); + } + + public abstract void onViewComments(AjaxRequestTarget target); + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/ProfilePage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/ProfilePage.java index e23fb31ba..9505c83a1 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/ProfilePage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/ProfilePage.java @@ -1,69 +1,78 @@ -package org.obiba.onyx.webapp.user.page; - -import java.util.Arrays; -import java.util.Locale; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.base.panel.AjaxLanguageChoicePanel; -import org.obiba.onyx.webapp.user.panel.ChangePasswordPanel; - -/** - * Allows the signed user to change his password and preferred language - * @author acarey - * - */ -public class ProfilePage extends BasePage { - - @SpringBean - private UserService userService; - - public ProfilePage() { - super(); - - AjaxLanguageChoicePanel languageSelect = new AjaxLanguageChoicePanel("languageSelect", new StringResourceModel("Language", this, null), Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH })) { - - private static final long serialVersionUID = 1L; - - @Override - protected void onLanguageUpdate(Locale language, AjaxRequestTarget target) { - if(language == null) return; - getSession().setLocale(language); - userService.updateUserLanguage(OnyxAuthenticatedSession.get().getUser().getId(), language); - setResponsePage(getPage()); - } - - }; - - User user = OnyxAuthenticatedSession.get().getUser(); - if(user.getLanguage() != null) getSession().setLocale(user.getLanguage()); - else { - if(getSession().getLocale() != null && getSession().getLocale().getLanguage().equals("fr")) getSession().setLocale(Locale.FRENCH); - else - getSession().setLocale(Locale.ENGLISH); - } - - languageSelect.setSelectedLanguage(getSession().getLocale()); - - add(languageSelect); - - ChangePasswordPanel changePassword = new ChangePasswordPanel("changePassword") { - private static final long serialVersionUID = 1L; - - public void onSuccess() { - setResponsePage(getApplication().getHomePage()); - } - - public void onFailure() { - setResponsePage(getPage()); - } - }; - - add(changePassword); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.page; + +import java.util.Arrays; +import java.util.Locale; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.base.panel.AjaxLanguageChoicePanel; +import org.obiba.onyx.webapp.user.panel.ChangePasswordPanel; + +/** + * Allows the signed user to change his password and preferred language + * @author acarey + * + */ +public class ProfilePage extends BasePage { + + @SpringBean + private UserService userService; + + public ProfilePage() { + super(); + + AjaxLanguageChoicePanel languageSelect = new AjaxLanguageChoicePanel("languageSelect", new StringResourceModel("Language", this, null), Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH })) { + + private static final long serialVersionUID = 1L; + + @Override + protected void onLanguageUpdate(Locale language, AjaxRequestTarget target) { + if(language == null) return; + getSession().setLocale(language); + userService.updateUserLanguage(OnyxAuthenticatedSession.get().getUser().getId(), language); + setResponsePage(getPage()); + } + + }; + + User user = OnyxAuthenticatedSession.get().getUser(); + if(user.getLanguage() != null) getSession().setLocale(user.getLanguage()); + else { + if(getSession().getLocale() != null && getSession().getLocale().getLanguage().equals("fr")) getSession().setLocale(Locale.FRENCH); + else + getSession().setLocale(Locale.ENGLISH); + } + + languageSelect.setSelectedLanguage(getSession().getLocale()); + + add(languageSelect); + + ChangePasswordPanel changePassword = new ChangePasswordPanel("changePassword") { + private static final long serialVersionUID = 1L; + + public void onSuccess() { + setResponsePage(getApplication().getHomePage()); + } + + public void onFailure() { + setResponsePage(getPage()); + } + }; + + add(changePassword); + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/UserSearchPage.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/UserSearchPage.java index 5cc69ceb6..af8405cda 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/UserSearchPage.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/page/UserSearchPage.java @@ -1,243 +1,252 @@ -package org.obiba.onyx.webapp.user.page; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.HeaderlessColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.link.ILinkListener; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.core.service.EntityQueryService; -import org.obiba.core.service.PagingClause; -import org.obiba.core.service.SortingClause; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.webapp.base.page.BasePage; -import org.obiba.onyx.webapp.panel.OnyxEntityList; -import org.obiba.onyx.webapp.user.panel.UserPanel; -import org.obiba.wicket.markup.html.panel.ConfirmLinkPanel; -import org.obiba.wicket.markup.html.panel.LinkPanel; -import org.obiba.wicket.markup.html.table.IColumnProvider; -import org.obiba.wicket.markup.html.table.SortableDataProviderEntityServiceImpl; - -/** - * Displays the list of users Contains a link to edit user info, to add a new user and to delete an existing user - * Contains a toggle to change user status - * @author acarey - * - */ -@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR" }) -public class UserSearchPage extends BasePage { - - @SpringBean - private EntityQueryService queryService; - - @SpringBean - private UserService userService; - - private OnyxEntityList userList; - - private User template = new User(); - - private ModalWindow userDetailsModalWindow; - - @SuppressWarnings("serial") - public UserSearchPage() { - super(); - - userDetailsModalWindow = new ModalWindow("userDetailsModalWindow"); - userDetailsModalWindow.setTitle(new StringResourceModel("UserManagement", this, null)); - - userDetailsModalWindow.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { - public boolean onCloseButtonClicked(AjaxRequestTarget target) { - // same as cancel - return true; - } - }); - - userDetailsModalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - public void onClose(AjaxRequestTarget target) { - target.addComponent(userList); - } - }); - userDetailsModalWindow.setInitialWidth(400); - userDetailsModalWindow.setInitialHeight(450); - add(userDetailsModalWindow); - - add(new AjaxLink("addUser") { - - @Override - public void onClick(AjaxRequestTarget target) { - userDetailsModalWindow.setContent(new UserPanel("content", new Model(new User()), userDetailsModalWindow)); - userDetailsModalWindow.show(target); - } - - }); - - template.setDeleted(false); - - userList = new OnyxEntityList("user-list", new UserProvider(template), new UserListColumnProvider(), new StringResourceModel("UserList", UserSearchPage.this, null)); - add(userList); - - } - - @SuppressWarnings("serial") - private class UserProvider extends SortableDataProviderEntityServiceImpl { - - private User template; - - public UserProvider(User template) { - super(queryService, User.class); - this.template = template; - setSort(new SortParam("lastName", true)); - } - - @Override - protected List getList(PagingClause paging, SortingClause... clauses) { - return userService.getUsers(template, paging, clauses); - } - - @Override - public int size() { - return userService.getUserCount(template); - } - - } - - private class UserListColumnProvider implements IColumnProvider, Serializable { - - private static final long serialVersionUID = 1141339694945247910L; - - private List columns = new ArrayList(); - - private List additional = new ArrayList(); - - @SuppressWarnings("serial") - public UserListColumnProvider() { - columns.add(new PropertyColumn(new StringResourceModel("LastName", UserSearchPage.this, null), "lastName", "lastName")); - columns.add(new PropertyColumn(new StringResourceModel("FirstName", UserSearchPage.this, null), "firstName", "firstName")); - columns.add(new PropertyColumn(new StringResourceModel("login", UserSearchPage.this, null), "login", "login")); - columns.add(new PropertyColumn(new StringResourceModel("Email", UserSearchPage.this, null), "email", "email")); - - columns.add(new AbstractColumn(new StringResourceModel("Role(s)", UserSearchPage.this, null)) { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - StringBuilder roleList = new StringBuilder(); - - for(Role r : getUser(rowModel).getRoles()) { - if(roleList.length() != 0) roleList.append(", "); - roleList.append(new StringResourceModel("Role." + ((Role) r).getName(), UserSearchPage.this, null).getString()); - } - - cellItem.add(new Label(componentId, roleList.toString())); - } - - }); - - columns.add(new AbstractColumn(new StringResourceModel("Status", UserSearchPage.this, null)) { - - public void populateItem(Item cellItem, String componentId, final IModel rowModel) { - LinkPanel statusLink = new LinkPanel(componentId, new ILinkListener() { - - public void onLinkClicked() { - Status newStatus; - if(getUser(rowModel).getStatus().equals(Status.ACTIVE)) newStatus = Status.INACTIVE; - else - newStatus = Status.ACTIVE; - userService.updateStatus(getUser(rowModel).getId(), newStatus); - } - - }, new StringResourceModel("Status." + getUser(rowModel).getStatus(), UserSearchPage.this, null)); - - if(OnyxAuthenticatedSession.get().getUser().getLogin().equals(getUser(rowModel).getLogin())) cellItem.add(new Label(componentId, new StringResourceModel("Status." + getUser(rowModel).getStatus(), UserSearchPage.this, null))); - else - cellItem.add(statusLink); - } - }); - - columns.add(new HeaderlessColumn() { - - public void populateItem(Item cellItem, String componentId, IModel rowModel) { - cellItem.add(new LinkFragment(componentId, rowModel)); - } - }); - - columns.add(new HeaderlessColumn() { - - public void populateItem(Item cellItem, String componentId, final IModel rowModel) { - ConfirmLinkPanel deleteLink = new ConfirmLinkPanel(componentId, new StringResourceModel("Delete", UserSearchPage.this, null), new StringResourceModel("ConfirmDeleteUser", UserSearchPage.this, null, new Object[] { getUser(rowModel).getFullName() })) { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick() { - userService.deleteUser(getUser(rowModel).getId()); - } - }; - if(OnyxAuthenticatedSession.get().getUser().getLogin().equals(getUser(rowModel).getLogin())) deleteLink.setVisible(false); - cellItem.add(deleteLink); - } - }); - } - - public List getAdditionalColumns() { - return additional; - } - - public List getColumnHeaderNames() { - return null; - } - - public List getDefaultColumns() { - return columns; - } - - public List getRequiredColumns() { - return columns; - } - - protected User getUser(IModel rowModel) { - return (User) rowModel.getObject(); - } - - } - - public class LinkFragment extends Fragment { - - private static final long serialVersionUID = 1L; - - public LinkFragment(String id, final IModel rowModel) { - super(id, "linkFragment", UserSearchPage.this); - add(new AjaxLink("editLink") { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - // TODO Auto-generated method stub - userDetailsModalWindow.setContent(new UserPanel("content", rowModel, userDetailsModalWindow)); - userDetailsModalWindow.show(target); - } - - }); - - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.page; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.HeaderlessColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.link.ILinkListener; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.core.service.EntityQueryService; +import org.obiba.core.service.PagingClause; +import org.obiba.core.service.SortingClause; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.webapp.base.page.BasePage; +import org.obiba.onyx.webapp.panel.OnyxEntityList; +import org.obiba.onyx.webapp.user.panel.UserPanel; +import org.obiba.wicket.markup.html.panel.ConfirmLinkPanel; +import org.obiba.wicket.markup.html.panel.LinkPanel; +import org.obiba.wicket.markup.html.table.IColumnProvider; +import org.obiba.wicket.markup.html.table.SortableDataProviderEntityServiceImpl; + +/** + * Displays the list of users Contains a link to edit user info, to add a new user and to delete an existing user + * Contains a toggle to change user status + * @author acarey + * + */ +@AuthorizeInstantiation( { "SYSTEM_ADMINISTRATOR" }) +public class UserSearchPage extends BasePage { + + @SpringBean + private EntityQueryService queryService; + + @SpringBean + private UserService userService; + + private OnyxEntityList userList; + + private User template = new User(); + + private ModalWindow userDetailsModalWindow; + + @SuppressWarnings("serial") + public UserSearchPage() { + super(); + + userDetailsModalWindow = new ModalWindow("userDetailsModalWindow"); + userDetailsModalWindow.setTitle(new StringResourceModel("UserManagement", this, null)); + + userDetailsModalWindow.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { + public boolean onCloseButtonClicked(AjaxRequestTarget target) { + // same as cancel + return true; + } + }); + + userDetailsModalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { + public void onClose(AjaxRequestTarget target) { + target.addComponent(userList); + } + }); + userDetailsModalWindow.setInitialWidth(400); + userDetailsModalWindow.setInitialHeight(450); + add(userDetailsModalWindow); + + add(new AjaxLink("addUser") { + + @Override + public void onClick(AjaxRequestTarget target) { + userDetailsModalWindow.setContent(new UserPanel("content", new Model(new User()), userDetailsModalWindow)); + userDetailsModalWindow.show(target); + } + + }); + + template.setDeleted(false); + + userList = new OnyxEntityList("user-list", new UserProvider(template), new UserListColumnProvider(), new StringResourceModel("UserList", UserSearchPage.this, null)); + add(userList); + + } + + @SuppressWarnings("serial") + private class UserProvider extends SortableDataProviderEntityServiceImpl { + + private User template; + + public UserProvider(User template) { + super(queryService, User.class); + this.template = template; + setSort(new SortParam("lastName", true)); + } + + @Override + protected List getList(PagingClause paging, SortingClause... clauses) { + return userService.getUsers(template, paging, clauses); + } + + @Override + public int size() { + return userService.getUserCount(template); + } + + } + + private class UserListColumnProvider implements IColumnProvider, Serializable { + + private static final long serialVersionUID = 1141339694945247910L; + + private List columns = new ArrayList(); + + private List additional = new ArrayList(); + + @SuppressWarnings("serial") + public UserListColumnProvider() { + columns.add(new PropertyColumn(new StringResourceModel("LastName", UserSearchPage.this, null), "lastName", "lastName")); + columns.add(new PropertyColumn(new StringResourceModel("FirstName", UserSearchPage.this, null), "firstName", "firstName")); + columns.add(new PropertyColumn(new StringResourceModel("login", UserSearchPage.this, null), "login", "login")); + columns.add(new PropertyColumn(new StringResourceModel("Email", UserSearchPage.this, null), "email", "email")); + + columns.add(new AbstractColumn(new StringResourceModel("Role(s)", UserSearchPage.this, null)) { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + StringBuilder roleList = new StringBuilder(); + + for(Role r : getUser(rowModel).getRoles()) { + if(roleList.length() != 0) roleList.append(", "); + roleList.append(new StringResourceModel("Role." + ((Role) r).getName(), UserSearchPage.this, null).getString()); + } + + cellItem.add(new Label(componentId, roleList.toString())); + } + + }); + + columns.add(new AbstractColumn(new StringResourceModel("Status", UserSearchPage.this, null)) { + + public void populateItem(Item cellItem, String componentId, final IModel rowModel) { + LinkPanel statusLink = new LinkPanel(componentId, new ILinkListener() { + + public void onLinkClicked() { + Status newStatus; + if(getUser(rowModel).getStatus().equals(Status.ACTIVE)) newStatus = Status.INACTIVE; + else + newStatus = Status.ACTIVE; + userService.updateStatus(getUser(rowModel).getId(), newStatus); + } + + }, new StringResourceModel("Status." + getUser(rowModel).getStatus(), UserSearchPage.this, null)); + + if(OnyxAuthenticatedSession.get().getUser().getLogin().equals(getUser(rowModel).getLogin())) cellItem.add(new Label(componentId, new StringResourceModel("Status." + getUser(rowModel).getStatus(), UserSearchPage.this, null))); + else + cellItem.add(statusLink); + } + }); + + columns.add(new HeaderlessColumn() { + + public void populateItem(Item cellItem, String componentId, IModel rowModel) { + cellItem.add(new LinkFragment(componentId, rowModel)); + } + }); + + columns.add(new HeaderlessColumn() { + + public void populateItem(Item cellItem, String componentId, final IModel rowModel) { + ConfirmLinkPanel deleteLink = new ConfirmLinkPanel(componentId, new StringResourceModel("Delete", UserSearchPage.this, null), new StringResourceModel("ConfirmDeleteUser", UserSearchPage.this, null, new Object[] { getUser(rowModel).getFullName() })) { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick() { + userService.deleteUser(getUser(rowModel).getId()); + } + }; + if(OnyxAuthenticatedSession.get().getUser().getLogin().equals(getUser(rowModel).getLogin())) deleteLink.setVisible(false); + cellItem.add(deleteLink); + } + }); + } + + public List getAdditionalColumns() { + return additional; + } + + public List getColumnHeaderNames() { + return null; + } + + public List getDefaultColumns() { + return columns; + } + + public List getRequiredColumns() { + return columns; + } + + protected User getUser(IModel rowModel) { + return (User) rowModel.getObject(); + } + + } + + public class LinkFragment extends Fragment { + + private static final long serialVersionUID = 1L; + + public LinkFragment(String id, final IModel rowModel) { + super(id, "linkFragment", UserSearchPage.this); + add(new AjaxLink("editLink") { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + // TODO Auto-generated method stub + userDetailsModalWindow.setContent(new UserPanel("content", rowModel, userDetailsModalWindow)); + userDetailsModalWindow.show(target); + } + + }); + + } + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/ChangePasswordPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/ChangePasswordPanel.java index 3ae260228..474407836 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/ChangePasswordPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/ChangePasswordPanel.java @@ -1,133 +1,142 @@ -package org.obiba.onyx.webapp.user.panel; - -import java.io.Serializable; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.markup.html.form.Button; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.PasswordTextField; -import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.OnyxAuthenticatedSession; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; - -/** - * Defines form for password changing - * @author acarey - * - */ -public abstract class ChangePasswordPanel extends Panel { - - private static final long serialVersionUID = 1L; - - @SpringBean - private UserService userService; - - public ChangePasswordPanel(String id) { - super(id); - add(new ChangePasswordForm("changePasswordForm")); - } - - private class ChangePasswordForm extends Form { - - private static final long serialVersionUID = 1L; - - ChangePasswordPanelModel model = new ChangePasswordPanelModel(); - - public ChangePasswordForm(String id) { - super(id); - - PasswordTextField password = new PasswordTextField("password", new PropertyModel(model, "password")); - password.add(new RequiredFormFieldBehavior()); - add(password); - - PasswordTextField confirmPassword = new PasswordTextField("confirmPassword", new PropertyModel(model, "confirmPassword")); - confirmPassword.add(new RequiredFormFieldBehavior()); - add(confirmPassword); - - // Validate that the password and the confirmed password are the same. - add(new EqualPasswordInputValidator(password, confirmPassword)); - - add(new Button("submit") { - - private static final long serialVersionUID = 1L; - - @Override - public void onSubmit() { - super.onSubmit(); - - String password = model.getPassword(); - - User user = OnyxAuthenticatedSession.get().getUser(); - if(userService.isNewPassword(user, User.digest(password))) { - try { - userService.updatePassword(user.getId(), User.digest(password)); - onSuccess(); - } catch(Exception e) { - e.printStackTrace(); - onFailure(); - } - } else { - error(new StringResourceModel("PasswordPreviouslyUsed", this, null).getString()); - onFailure(); - } - } - - }); - - add(new AjaxLink("cancel") { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - int currentPageId = getPage().getPageMapEntry().getNumericId(); - setResponsePage(getPage().getPageMap().get((currentPageId - 1), -1)); - } - }); - } - } - - /** - * Called when password is successfully changed - * - */ - public abstract void onSuccess(); - - /** - * Called when password check or update failed. - * - */ - public abstract void onFailure(); - - private class ChangePasswordPanelModel implements Serializable { - - private static final long serialVersionUID = 1L; - - private String password; - - private String confirmPassword; - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getConfirmPassword() { - return confirmPassword; - } - - public void setConfirmPassword(String confirmPassword) { - this.confirmPassword = confirmPassword; - } - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.panel; + +import java.io.Serializable; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.markup.html.form.Button; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.PasswordTextField; +import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.OnyxAuthenticatedSession; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; + +/** + * Defines form for password changing + * @author acarey + * + */ +public abstract class ChangePasswordPanel extends Panel { + + private static final long serialVersionUID = 1L; + + @SpringBean + private UserService userService; + + public ChangePasswordPanel(String id) { + super(id); + add(new ChangePasswordForm("changePasswordForm")); + } + + private class ChangePasswordForm extends Form { + + private static final long serialVersionUID = 1L; + + ChangePasswordPanelModel model = new ChangePasswordPanelModel(); + + public ChangePasswordForm(String id) { + super(id); + + PasswordTextField password = new PasswordTextField("password", new PropertyModel(model, "password")); + password.add(new RequiredFormFieldBehavior()); + add(password); + + PasswordTextField confirmPassword = new PasswordTextField("confirmPassword", new PropertyModel(model, "confirmPassword")); + confirmPassword.add(new RequiredFormFieldBehavior()); + add(confirmPassword); + + // Validate that the password and the confirmed password are the same. + add(new EqualPasswordInputValidator(password, confirmPassword)); + + add(new Button("submit") { + + private static final long serialVersionUID = 1L; + + @Override + public void onSubmit() { + super.onSubmit(); + + String password = model.getPassword(); + + User user = OnyxAuthenticatedSession.get().getUser(); + if(userService.isNewPassword(user, User.digest(password))) { + try { + userService.updatePassword(user.getId(), User.digest(password)); + onSuccess(); + } catch(Exception e) { + e.printStackTrace(); + onFailure(); + } + } else { + error(new StringResourceModel("PasswordPreviouslyUsed", this, null).getString()); + onFailure(); + } + } + + }); + + add(new AjaxLink("cancel") { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + int currentPageId = getPage().getPageMapEntry().getNumericId(); + setResponsePage(getPage().getPageMap().get((currentPageId - 1), -1)); + } + }); + } + } + + /** + * Called when password is successfully changed + * + */ + public abstract void onSuccess(); + + /** + * Called when password check or update failed. + * + */ + public abstract void onFailure(); + + private class ChangePasswordPanelModel implements Serializable { + + private static final long serialVersionUID = 1L; + + private String password; + + private String confirmPassword; + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConfirmPassword() { + return confirmPassword; + } + + public void setConfirmPassword(String confirmPassword) { + this.confirmPassword = confirmPassword; + } + } +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserModalPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserModalPanel.java index b00829726..852a68360 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserModalPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserModalPanel.java @@ -1,15 +1,24 @@ -package org.obiba.onyx.webapp.user.panel; - -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; - -public class UserModalPanel extends Panel { - - private static final long serialVersionUID = 1L; - - public UserModalPanel(String id, Panel contentPanel, final ModalWindow modalWindow) { - super(id); - add(contentPanel); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.panel; + +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; + +public class UserModalPanel extends Panel { + + private static final long serialVersionUID = 1L; + + public UserModalPanel(String id, Panel contentPanel, final ModalWindow modalWindow) { + super(id); + add(contentPanel); + } + +} diff --git a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserPanel.java b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserPanel.java index 1d7e945f1..7562e5117 100644 --- a/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserPanel.java +++ b/onyx-webapp/src/main/java/org/obiba/onyx/webapp/user/panel/UserPanel.java @@ -1,206 +1,215 @@ -package org.obiba.onyx.webapp.user.panel; - -import java.util.Arrays; -import java.util.Locale; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.markup.html.AjaxLink; -import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.html.form.ListMultipleChoice; -import org.apache.wicket.markup.html.form.PasswordTextField; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.injection.annot.SpringBean; -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.validator.AbstractValidator; -import org.apache.wicket.validation.validator.EmailAddressValidator; -import org.obiba.core.service.SortingClause; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.Status; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.onyx.webapp.base.panel.AjaxLanguageChoicePanel; -import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; - -/** - * Defines User Form for adding/editing user - * @author acarey - * - */ -public class UserPanel extends Panel { - - private static final long serialVersionUID = 1L; - - @SpringBean - private UserService userService; - - private ModalWindow userModalWindow; - - private FeedbackPanel feedbackPanel; - - private PasswordTextField password; - - private AjaxLanguageChoicePanel language; - - public UserPanel(String id, IModel model, final ModalWindow modalWindow) { - super(id, model); - userModalWindow = modalWindow; - add(new UserPanelForm("userPanelForm", model)); - } - - /** - * Expect User entity in IModel {@link User} - */ - private class UserPanelForm extends Form { - - private static final long serialVersionUID = 1L; - - public UserPanelForm(String id, final IModel model) { - super(id); - setModel(model); - - feedbackPanel = new FeedbackPanel("feedback"); - feedbackPanel.setOutputMarkupId(true); - add(feedbackPanel); - - TextField lastName = new TextField("lastName", new PropertyModel(getModel(), "lastName")); - lastName.add(new RequiredFormFieldBehavior()); - add(lastName); - - TextField firstName = new TextField("firstName", new PropertyModel(getModel(), "firstName")); - firstName.add(new RequiredFormFieldBehavior()); - add(firstName); - - TextField login = new TextField("login", new PropertyModel(getModel(), "login")); - login.add(new RequiredFormFieldBehavior()); - login.setEnabled(false); - add(login); - - password = new PasswordTextField("password", new Model(new String())); - password.setRequired(getUser().getLogin() == null); - if(getUser().getLogin() != null) password.add(new PasswordValidator()); - add(password); - - TextField email = new TextField("email", new PropertyModel(getModel(), "email")); - email.add(new RequiredFormFieldBehavior()); - email.add(EmailAddressValidator.getInstance()); - add(email); - - ListMultipleChoice roles = new ListMultipleChoice("roles", new PropertyModel(getModel(), "roles"), userService.getRoles(SortingClause.create("name"))); - roles.setRequired(true); - roles.setChoiceRenderer(new IChoiceRenderer() { - - private static final long serialVersionUID = 1L; - - public Object getDisplayValue(Object object) { - return (new StringResourceModel("Role." + ((Role) object).getName(), UserPanel.this, null).getString()); - } - - public String getIdValue(Object object, int index) { - return (((Role) object).getId().toString()); - } - }); - add(roles); - - language = new AjaxLanguageChoicePanel("languageSelect", null, Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH })) { - - private static final long serialVersionUID = 1L; - - @Override - protected void onLanguageUpdate(Locale language, AjaxRequestTarget target) { - if(language == null) language = Locale.ENGLISH; - //getUser().setLanguage(language); - } - - }; - - if(getUser().getLanguage() != null) language.setSelectedLanguage(getUser().getLanguage()); - add(language); - - add(new AjaxSubmitLink("submit") { - - private static final long serialVersionUID = 1L; - - @Override - public void onSubmit(AjaxRequestTarget target, Form form) { - super.onSubmit(); - User user = (User) UserPanelForm.this.getModelObject(); - String newPassword = UserPanel.this.password.getModelObjectAsString(); - Locale newLanguage = UserPanel.this.language.getSelectedLanguage(); - - if(newPassword != "") user.setPassword(User.digest(newPassword)); - if(user.getLogin() == null) generateLogin(user); - user.setLanguage((newLanguage == null) ? Locale.ENGLISH : newLanguage); - if(user.getStatus() == null) user.setStatus(Status.ACTIVE); - user.setDeleted(false); - - userService.createOrUpdateUser(user); - userModalWindow.close(target); - } - - @Override - protected void onError(AjaxRequestTarget target, Form form) { - target.addComponent(feedbackPanel); - } - }); - - add(new AjaxLink("cancel") { - - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - userModalWindow.close(target); - } - }); - } - - private class PasswordValidator extends AbstractValidator { - - private static final long serialVersionUID = 1L; - - @Override - protected void onValidate(IValidatable validatable) { - String newPassword = validatable.getValue().toString(); - - if(getUser().getPassword().equals(User.digest(newPassword))) { - feedbackPanel.error(new StringResourceModel("PasswordPreviouslyUsed", UserPanel.this, null).getString()); - } - } - } - - protected User getUser() { - return (User) getModelObject(); - } - } - - /** - * Generate a unique user name, only for non existing user. - * @param user - */ - private void generateLogin(User user) { - if(user.getId() != null) return; - - String baseLogin = ""; - - if(user.getFirstName() != null && user.getFirstName().length() > 0) baseLogin = user.getFirstName().substring(0, 1).toLowerCase(); - if(user.getLastName() != null && user.getLastName().length() > 0) baseLogin += user.getLastName().toLowerCase(); - - String login = baseLogin; - int i = 1; - while(userService.getUserWithLogin(login) != null) { - login = baseLogin + i; - i++; - } - - user.setLogin(login); - } -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.panel; + +import java.util.Arrays; +import java.util.Locale; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; +import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.html.form.ListMultipleChoice; +import org.apache.wicket.markup.html.form.PasswordTextField; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.validator.AbstractValidator; +import org.apache.wicket.validation.validator.EmailAddressValidator; +import org.obiba.core.service.SortingClause; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.Status; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.onyx.webapp.base.panel.AjaxLanguageChoicePanel; +import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior; + +/** + * Defines User Form for adding/editing user + * @author acarey + * + */ +public class UserPanel extends Panel { + + private static final long serialVersionUID = 1L; + + @SpringBean + private UserService userService; + + private ModalWindow userModalWindow; + + private FeedbackPanel feedbackPanel; + + private PasswordTextField password; + + private AjaxLanguageChoicePanel language; + + public UserPanel(String id, IModel model, final ModalWindow modalWindow) { + super(id, model); + userModalWindow = modalWindow; + add(new UserPanelForm("userPanelForm", model)); + } + + /** + * Expect User entity in IModel {@link User} + */ + private class UserPanelForm extends Form { + + private static final long serialVersionUID = 1L; + + public UserPanelForm(String id, final IModel model) { + super(id); + setModel(model); + + feedbackPanel = new FeedbackPanel("feedback"); + feedbackPanel.setOutputMarkupId(true); + add(feedbackPanel); + + TextField lastName = new TextField("lastName", new PropertyModel(getModel(), "lastName")); + lastName.add(new RequiredFormFieldBehavior()); + add(lastName); + + TextField firstName = new TextField("firstName", new PropertyModel(getModel(), "firstName")); + firstName.add(new RequiredFormFieldBehavior()); + add(firstName); + + TextField login = new TextField("login", new PropertyModel(getModel(), "login")); + login.add(new RequiredFormFieldBehavior()); + login.setEnabled(false); + add(login); + + password = new PasswordTextField("password", new Model(new String())); + password.setRequired(getUser().getLogin() == null); + if(getUser().getLogin() != null) password.add(new PasswordValidator()); + add(password); + + TextField email = new TextField("email", new PropertyModel(getModel(), "email")); + email.add(new RequiredFormFieldBehavior()); + email.add(EmailAddressValidator.getInstance()); + add(email); + + ListMultipleChoice roles = new ListMultipleChoice("roles", new PropertyModel(getModel(), "roles"), userService.getRoles(SortingClause.create("name"))); + roles.setRequired(true); + roles.setChoiceRenderer(new IChoiceRenderer() { + + private static final long serialVersionUID = 1L; + + public Object getDisplayValue(Object object) { + return (new StringResourceModel("Role." + ((Role) object).getName(), UserPanel.this, null).getString()); + } + + public String getIdValue(Object object, int index) { + return (((Role) object).getId().toString()); + } + }); + add(roles); + + language = new AjaxLanguageChoicePanel("languageSelect", null, Arrays.asList(new Locale[] { Locale.FRENCH, Locale.ENGLISH })) { + + private static final long serialVersionUID = 1L; + + @Override + protected void onLanguageUpdate(Locale language, AjaxRequestTarget target) { + if(language == null) language = Locale.ENGLISH; + //getUser().setLanguage(language); + } + + }; + + if(getUser().getLanguage() != null) language.setSelectedLanguage(getUser().getLanguage()); + add(language); + + add(new AjaxSubmitLink("submit") { + + private static final long serialVersionUID = 1L; + + @Override + public void onSubmit(AjaxRequestTarget target, Form form) { + super.onSubmit(); + User user = (User) UserPanelForm.this.getModelObject(); + String newPassword = UserPanel.this.password.getModelObjectAsString(); + Locale newLanguage = UserPanel.this.language.getSelectedLanguage(); + + if(newPassword != "") user.setPassword(User.digest(newPassword)); + if(user.getLogin() == null) generateLogin(user); + user.setLanguage((newLanguage == null) ? Locale.ENGLISH : newLanguage); + if(user.getStatus() == null) user.setStatus(Status.ACTIVE); + user.setDeleted(false); + + userService.createOrUpdateUser(user); + userModalWindow.close(target); + } + + @Override + protected void onError(AjaxRequestTarget target, Form form) { + target.addComponent(feedbackPanel); + } + }); + + add(new AjaxLink("cancel") { + + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + userModalWindow.close(target); + } + }); + } + + private class PasswordValidator extends AbstractValidator { + + private static final long serialVersionUID = 1L; + + @Override + protected void onValidate(IValidatable validatable) { + String newPassword = validatable.getValue().toString(); + + if(getUser().getPassword().equals(User.digest(newPassword))) { + feedbackPanel.error(new StringResourceModel("PasswordPreviouslyUsed", UserPanel.this, null).getString()); + } + } + } + + protected User getUser() { + return (User) getModelObject(); + } + } + + /** + * Generate a unique user name, only for non existing user. + * @param user + */ + private void generateLogin(User user) { + if(user.getId() != null) return; + + String baseLogin = ""; + + if(user.getFirstName() != null && user.getFirstName().length() > 0) baseLogin = user.getFirstName().substring(0, 1).toLowerCase(); + if(user.getLastName() != null && user.getLastName().length() > 0) baseLogin += user.getLastName().toLowerCase(); + + String login = baseLogin; + int i = 1; + while(userService.getUserWithLogin(login) != null) { + login = baseLogin + i; + i++; + } + + user.setLogin(login); + } +} diff --git a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanelTest.java b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanelTest.java index def1c4f03..391953d8e 100644 --- a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanelTest.java +++ b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/CommentsModalPanelTest.java @@ -1,239 +1,248 @@ -package org.obiba.onyx.webapp.participant.panel; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.basic.MultiLineLabel; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.apache.wicket.util.tester.TestPanelSource; -import org.apache.wicket.util.tester.WicketTester; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.EntityQueryService; -import org.obiba.onyx.core.domain.participant.Interview; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.ActiveInterviewService; -import org.obiba.onyx.core.service.UserSessionService; -import org.obiba.onyx.engine.Action; -import org.obiba.onyx.engine.ActionType; -import org.obiba.onyx.engine.Module; -import org.obiba.onyx.engine.ModuleRegistry; -import org.obiba.onyx.engine.Stage; -import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; -import org.obiba.wicket.test.MockSpringApplication; - -public class CommentsModalPanelTest implements Serializable { - - private static final long serialVersionUID = 1L; - - private transient WicketTester tester; - - private ApplicationContextMock applicationContextMock; - - private ActiveInterviewService activeInterviewServiceMock; - - private EntityQueryService queryServiceMock; - - private transient ModuleRegistry moduleRegistry; - - private UserSessionService userSessionServiceMock; - - private CommentsModalPanel commentsModalPanel; - - @Before - public void setup() { - applicationContextMock = new ApplicationContextMock() { - private static final long serialVersionUID = 1L; - - // Need to override this method since the default implementation - // throws an UnsupportedOperationException! - public String getMessage(String code, Object[] args, Locale locale) { - return ""; - } - }; - - activeInterviewServiceMock = createMock(ActiveInterviewService.class); - applicationContextMock.putBean("activeInterviewService", activeInterviewServiceMock); - - queryServiceMock = createMock(EntityQueryService.class); - applicationContextMock.putBean("queryService", queryServiceMock); - - applicationContextMock.putBean("moduleRegistry", moduleRegistry = new ModuleRegistry()); - - userSessionServiceMock = createMock(UserSessionService.class); - applicationContextMock.putBean("userSessionService", userSessionServiceMock); - - MockSpringApplication application = new MockSpringApplication(); - application.setApplicationContext(applicationContextMock); - - tester = new WicketTester(application); - } - - /** - * Tests that all types of comments -- general and stage -- are displayed in the Previous Comments section, ordered by - * date (most recent first). - */ - @SuppressWarnings("serial") - @Test - public void testCommentsDisplayedMostRecentFirst() { - User user = createUser(); - Interview interview = createInterview(1l); - - Stage stage = createStage("marble", "CON", "Participant_Consent", 1); - stage.setApplicationContext(applicationContextMock); - stage.setUserSessionService(userSessionServiceMock); - - Participant participant = createParticipant(1l, "Suzan", "Tremblay"); - String generalComment = "general comment"; - String stageComment = "stage execute comment"; - Date now = new Date(); - Date oneHourAgo = new Date(now.getTime() - 1000 * 60 * 60); - - // - // Create a list of two comments for this test, ordered by date (most recent first). - // - // NOTE: The order corresponds to the expected order of comments returned by - // ActiveInterviewService.getInterviewComments(). - // - List commentActions = new ArrayList(); - commentActions.add(createStageComment(user, interview, stage, ActionType.EXECUTE, now, stageComment)); - commentActions.add(createGeneralComment(user, interview, oneHourAgo, generalComment)); - - // Expect that UserSessionService.getLocale() is called, and return locale "en". - expect(userSessionServiceMock.getLocale()).andReturn(new Locale("en")); - expectLastCall().anyTimes(); - - // We can't mock ModuleRegistry, so we'll create a mock Module instance and register that in the ModuleRegistry... - // This allows us to expect that ModuleRegistry.getStage() is called, and return the proper Stage instance - Module mockModule = createMock(Module.class); - expect(mockModule.getStages()).andReturn(Collections.singletonList(stage)); - expectLastCall().anyTimes(); - expect(mockModule.getName()).andReturn("MockModule"); - expectLastCall().anyTimes(); - - // Expect that CommentsModalPanel calls ActiveInterviewService.getInterviewComments() - // to retrieve all comments related to the current interview, and return the test comments. - expect(activeInterviewServiceMock.getInterviewComments()).andReturn(commentActions); - - // Expect that CommentsModalPanel calls ActiveInterviewService.getParticipant() to - // retrieve the participant currently being interviewed, and return the test participant. - expect(activeInterviewServiceMock.getParticipant()).andReturn(participant); - - replay(userSessionServiceMock); - replay(mockModule); - replay(activeInterviewServiceMock); - - moduleRegistry.registerModule(mockModule); - - tester.startPanel(new TestPanelSource() { - public Panel getTestPanel(String panelId) { - return commentsModalPanel = new CommentsModalPanel(panelId, new ModalWindow("bogus")) { - @Override - public void onAddComments(AjaxRequestTarget target) { - // do nothing - } - }; - } - }); - - verify(userSessionServiceMock); - verify(mockModule); - verify(activeInterviewServiceMock); - - // - // Get a reference to the FIRST comment panel and verify that it contains the most - // recent comment -- i.e., the stage comment. - // - // NOTE: In the current user interface, the comment string is contained in the FOURTH row - // of the comment panel. - // - KeyValueDataPanel commentPanel = (KeyValueDataPanel) commentsModalPanel.get("previousComments:comment-list:1:comment-panel"); - Assert.assertNotNull(commentPanel); - - MultiLineLabel commentLabel = (MultiLineLabel) commentPanel.get("repeating:4:" + KeyValueDataPanel.getRowValueId()); - Assert.assertNotNull(commentLabel); - Assert.assertEquals(stageComment, commentLabel.getModelObjectAsString()); - - // - // Now get a reference to the SECOND comment panel and verify that it contains the - // earlier comment -- i.e., the general comment. - // - commentPanel = (KeyValueDataPanel) commentsModalPanel.get("previousComments:comment-list:2:comment-panel"); - Assert.assertNotNull(commentPanel); - - commentLabel = (MultiLineLabel) commentPanel.get("repeating:4:" + KeyValueDataPanel.getRowValueId()); - Assert.assertNotNull(commentLabel); - Assert.assertEquals(generalComment, commentLabel.getModelObjectAsString()); - } - - private User createUser() { - User user = new User(); - user.setId(1l); - - return user; - } - - private Interview createInterview(long id) { - Interview interview = new Interview(); - interview.setId(id); - - return interview; - } - - private Stage createStage(String module, String name, String description, int displayOrder) { - Stage stage = new Stage(); - stage.setModule(module); - stage.setDisplayOrder(displayOrder); - - return stage; - } - - private Participant createParticipant(long id, String firstName, String lastName) { - Participant participant = new Participant(); - participant.setId(id); - participant.setFirstName(firstName); - participant.setLastName(lastName); - - return participant; - } - - private Action createGeneralComment(User user, Interview interview, Date date, String comment) { - Action commentAction = new Action(); - - commentAction.setActionType(ActionType.COMMENT); - commentAction.setUser(user); - commentAction.setInterview(interview); - commentAction.setDateTime(date); - commentAction.setComment(comment); - - return commentAction; - } - - private Action createStageComment(User user, Interview interview, Stage stage, ActionType type, Date date, String comment) { - Action commentAction = new Action(); - - commentAction.setActionType(type); - commentAction.setUser(user); - commentAction.setInterview(interview); - commentAction.setStage(stage.getName()); - commentAction.setDateTime(date); - commentAction.setComment(comment); - - return commentAction; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.basic.MultiLineLabel; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.apache.wicket.util.tester.TestPanelSource; +import org.apache.wicket.util.tester.WicketTester; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.EntityQueryService; +import org.obiba.onyx.core.domain.participant.Interview; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.ActiveInterviewService; +import org.obiba.onyx.core.service.UserSessionService; +import org.obiba.onyx.engine.Action; +import org.obiba.onyx.engine.ActionType; +import org.obiba.onyx.engine.Module; +import org.obiba.onyx.engine.ModuleRegistry; +import org.obiba.onyx.engine.Stage; +import org.obiba.wicket.markup.html.panel.KeyValueDataPanel; +import org.obiba.wicket.test.MockSpringApplication; + +public class CommentsModalPanelTest implements Serializable { + + private static final long serialVersionUID = 1L; + + private transient WicketTester tester; + + private ApplicationContextMock applicationContextMock; + + private ActiveInterviewService activeInterviewServiceMock; + + private EntityQueryService queryServiceMock; + + private transient ModuleRegistry moduleRegistry; + + private UserSessionService userSessionServiceMock; + + private CommentsModalPanel commentsModalPanel; + + @Before + public void setup() { + applicationContextMock = new ApplicationContextMock() { + private static final long serialVersionUID = 1L; + + // Need to override this method since the default implementation + // throws an UnsupportedOperationException! + public String getMessage(String code, Object[] args, Locale locale) { + return ""; + } + }; + + activeInterviewServiceMock = createMock(ActiveInterviewService.class); + applicationContextMock.putBean("activeInterviewService", activeInterviewServiceMock); + + queryServiceMock = createMock(EntityQueryService.class); + applicationContextMock.putBean("queryService", queryServiceMock); + + applicationContextMock.putBean("moduleRegistry", moduleRegistry = new ModuleRegistry()); + + userSessionServiceMock = createMock(UserSessionService.class); + applicationContextMock.putBean("userSessionService", userSessionServiceMock); + + MockSpringApplication application = new MockSpringApplication(); + application.setApplicationContext(applicationContextMock); + + tester = new WicketTester(application); + } + + /** + * Tests that all types of comments -- general and stage -- are displayed in the Previous Comments section, ordered by + * date (most recent first). + */ + @SuppressWarnings("serial") + @Test + public void testCommentsDisplayedMostRecentFirst() { + User user = createUser(); + Interview interview = createInterview(1l); + + Stage stage = createStage("marble", "CON", "Participant_Consent", 1); + stage.setApplicationContext(applicationContextMock); + stage.setUserSessionService(userSessionServiceMock); + + Participant participant = createParticipant(1l, "Suzan", "Tremblay"); + String generalComment = "general comment"; + String stageComment = "stage execute comment"; + Date now = new Date(); + Date oneHourAgo = new Date(now.getTime() - 1000 * 60 * 60); + + // + // Create a list of two comments for this test, ordered by date (most recent first). + // + // NOTE: The order corresponds to the expected order of comments returned by + // ActiveInterviewService.getInterviewComments(). + // + List commentActions = new ArrayList(); + commentActions.add(createStageComment(user, interview, stage, ActionType.EXECUTE, now, stageComment)); + commentActions.add(createGeneralComment(user, interview, oneHourAgo, generalComment)); + + // Expect that UserSessionService.getLocale() is called, and return locale "en". + expect(userSessionServiceMock.getLocale()).andReturn(new Locale("en")); + expectLastCall().anyTimes(); + + // We can't mock ModuleRegistry, so we'll create a mock Module instance and register that in the ModuleRegistry... + // This allows us to expect that ModuleRegistry.getStage() is called, and return the proper Stage instance + Module mockModule = createMock(Module.class); + expect(mockModule.getStages()).andReturn(Collections.singletonList(stage)); + expectLastCall().anyTimes(); + expect(mockModule.getName()).andReturn("MockModule"); + expectLastCall().anyTimes(); + + // Expect that CommentsModalPanel calls ActiveInterviewService.getInterviewComments() + // to retrieve all comments related to the current interview, and return the test comments. + expect(activeInterviewServiceMock.getInterviewComments()).andReturn(commentActions); + + // Expect that CommentsModalPanel calls ActiveInterviewService.getParticipant() to + // retrieve the participant currently being interviewed, and return the test participant. + expect(activeInterviewServiceMock.getParticipant()).andReturn(participant); + + replay(userSessionServiceMock); + replay(mockModule); + replay(activeInterviewServiceMock); + + moduleRegistry.registerModule(mockModule); + + tester.startPanel(new TestPanelSource() { + public Panel getTestPanel(String panelId) { + return commentsModalPanel = new CommentsModalPanel(panelId, new ModalWindow("bogus")) { + @Override + public void onAddComments(AjaxRequestTarget target) { + // do nothing + } + }; + } + }); + + verify(userSessionServiceMock); + verify(mockModule); + verify(activeInterviewServiceMock); + + // + // Get a reference to the FIRST comment panel and verify that it contains the most + // recent comment -- i.e., the stage comment. + // + // NOTE: In the current user interface, the comment string is contained in the FOURTH row + // of the comment panel. + // + KeyValueDataPanel commentPanel = (KeyValueDataPanel) commentsModalPanel.get("previousComments:comment-list:1:comment-panel"); + Assert.assertNotNull(commentPanel); + + MultiLineLabel commentLabel = (MultiLineLabel) commentPanel.get("repeating:4:" + KeyValueDataPanel.getRowValueId()); + Assert.assertNotNull(commentLabel); + Assert.assertEquals(stageComment, commentLabel.getModelObjectAsString()); + + // + // Now get a reference to the SECOND comment panel and verify that it contains the + // earlier comment -- i.e., the general comment. + // + commentPanel = (KeyValueDataPanel) commentsModalPanel.get("previousComments:comment-list:2:comment-panel"); + Assert.assertNotNull(commentPanel); + + commentLabel = (MultiLineLabel) commentPanel.get("repeating:4:" + KeyValueDataPanel.getRowValueId()); + Assert.assertNotNull(commentLabel); + Assert.assertEquals(generalComment, commentLabel.getModelObjectAsString()); + } + + private User createUser() { + User user = new User(); + user.setId(1l); + + return user; + } + + private Interview createInterview(long id) { + Interview interview = new Interview(); + interview.setId(id); + + return interview; + } + + private Stage createStage(String module, String name, String description, int displayOrder) { + Stage stage = new Stage(); + stage.setModule(module); + stage.setDisplayOrder(displayOrder); + + return stage; + } + + private Participant createParticipant(long id, String firstName, String lastName) { + Participant participant = new Participant(); + participant.setId(id); + participant.setFirstName(firstName); + participant.setLastName(lastName); + + return participant; + } + + private Action createGeneralComment(User user, Interview interview, Date date, String comment) { + Action commentAction = new Action(); + + commentAction.setActionType(ActionType.COMMENT); + commentAction.setUser(user); + commentAction.setInterview(interview); + commentAction.setDateTime(date); + commentAction.setComment(comment); + + return commentAction; + } + + private Action createStageComment(User user, Interview interview, Stage stage, ActionType type, Date date, String comment) { + Action commentAction = new Action(); + + commentAction.setActionType(type); + commentAction.setUser(user); + commentAction.setInterview(interview); + commentAction.setStage(stage.getName()); + commentAction.setDateTime(date); + commentAction.setComment(comment); + + return commentAction; + } +} diff --git a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanelTest.java b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanelTest.java index f899fd02f..3eecce59a 100644 --- a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanelTest.java +++ b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/participant/panel/EditParticipantPanelTest.java @@ -1,92 +1,101 @@ -package org.obiba.onyx.webapp.participant.panel; - -import static org.easymock.EasyMock.createMock; - -import java.util.Date; - -import org.apache.wicket.Page; -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.apache.wicket.util.tester.FormTester; -import org.apache.wicket.util.tester.TestPanelSource; -import org.apache.wicket.util.tester.WicketTester; -import org.easymock.EasyMock; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.onyx.core.domain.participant.Gender; -import org.obiba.onyx.core.domain.participant.Participant; -import org.obiba.onyx.core.domain.participant.Province; -import org.obiba.onyx.core.service.ParticipantService; -import org.obiba.wicket.test.MockSpringApplication; - -@SuppressWarnings("serial") -public class EditParticipantPanelTest { - - WicketTester tester; - - ParticipantService mockParticipantService; - - @Before - public void setup() { - - ApplicationContextMock mockCtx = new ApplicationContextMock(); - - mockParticipantService = createMock(ParticipantService.class); - - mockCtx.putBean("participantService", mockParticipantService); - - MockSpringApplication application = new MockSpringApplication(); - application.setApplicationContext(mockCtx); - application.setHomePage(Page.class); - - tester = new WicketTester(application); - } - - @SuppressWarnings("serial") - @Test - public void testUpdateParticipantInfo() { - final Participant p = newTestParticipant(); - - // We expect the updateParticipant method to be called once - mockParticipantService.updateParticipant(p); - - EasyMock.replay(mockParticipantService); - - tester.startPanel(new TestPanelSource() { - public Panel getTestPanel(String panelId) { - return new EditParticipantPanel(panelId, new Model(p), new ModalWindow("bogus")); - } - }); - tester.dumpPage(); - - FormTester formTester = tester.newFormTester("panel:editParticipantForm"); - - formTester.setValue("apartment", "400"); - - // formTester.submit(); WICKET-1828: does not submit through AJAX - // tester.clickLink("panel:editParticipantForm:saveAction", true); WICKET-1828: does not submit new values - - tester.executeAjaxEvent("panel:editParticipantForm:saveAction", "onclick"); - - tester.assertNoErrorMessage(); - - EasyMock.verify(mockParticipantService); - - Assert.assertEquals("400", p.getApartment()); - } - - public Participant newTestParticipant() { - Participant p = new Participant(); - p.setFirstName("Marcel"); - p.setLastName("Tremblay"); - p.setBarcode("1234"); - p.setBirthDate(new Date()); - p.setCity("Montréal"); - p.setProvince(Province.QC); - p.setGender(Gender.MALE); - return p; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.participant.panel; + +import static org.easymock.EasyMock.createMock; + +import java.util.Date; + +import org.apache.wicket.Page; +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.apache.wicket.util.tester.FormTester; +import org.apache.wicket.util.tester.TestPanelSource; +import org.apache.wicket.util.tester.WicketTester; +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.onyx.core.domain.participant.Gender; +import org.obiba.onyx.core.domain.participant.Participant; +import org.obiba.onyx.core.domain.participant.Province; +import org.obiba.onyx.core.service.ParticipantService; +import org.obiba.wicket.test.MockSpringApplication; + +@SuppressWarnings("serial") +public class EditParticipantPanelTest { + + WicketTester tester; + + ParticipantService mockParticipantService; + + @Before + public void setup() { + + ApplicationContextMock mockCtx = new ApplicationContextMock(); + + mockParticipantService = createMock(ParticipantService.class); + + mockCtx.putBean("participantService", mockParticipantService); + + MockSpringApplication application = new MockSpringApplication(); + application.setApplicationContext(mockCtx); + application.setHomePage(Page.class); + + tester = new WicketTester(application); + } + + @SuppressWarnings("serial") + @Test + public void testUpdateParticipantInfo() { + final Participant p = newTestParticipant(); + + // We expect the updateParticipant method to be called once + mockParticipantService.updateParticipant(p); + + EasyMock.replay(mockParticipantService); + + tester.startPanel(new TestPanelSource() { + public Panel getTestPanel(String panelId) { + return new EditParticipantPanel(panelId, new Model(p), new ModalWindow("bogus")); + } + }); + tester.dumpPage(); + + FormTester formTester = tester.newFormTester("panel:editParticipantForm"); + + formTester.setValue("apartment", "400"); + + // formTester.submit(); WICKET-1828: does not submit through AJAX + // tester.clickLink("panel:editParticipantForm:saveAction", true); WICKET-1828: does not submit new values + + tester.executeAjaxEvent("panel:editParticipantForm:saveAction", "onclick"); + + tester.assertNoErrorMessage(); + + EasyMock.verify(mockParticipantService); + + Assert.assertEquals("400", p.getApartment()); + } + + public Participant newTestParticipant() { + Participant p = new Participant(); + p.setFirstName("Marcel"); + p.setLastName("Tremblay"); + p.setBarcode("1234"); + p.setBirthDate(new Date()); + p.setCity("Montr�al"); + p.setProvince(Province.QC); + p.setGender(Gender.MALE); + return p; + } +} diff --git a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/user/panel/UserPanelTest.java b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/user/panel/UserPanelTest.java index 575e3a43f..afdc4d7d7 100644 --- a/onyx-webapp/src/test/java/org/obiba/onyx/webapp/user/panel/UserPanelTest.java +++ b/onyx-webapp/src/test/java/org/obiba/onyx/webapp/user/panel/UserPanelTest.java @@ -1,220 +1,229 @@ -package org.obiba.onyx.webapp.user.panel; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.spring.test.ApplicationContextMock; -import org.apache.wicket.util.tester.FormTester; -import org.apache.wicket.util.tester.TestPanelSource; -import org.apache.wicket.util.tester.WicketTester; -import org.apache.wicket.util.value.ValueMap; -import org.easymock.EasyMock; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.obiba.core.service.SortingClause; -import org.obiba.onyx.core.domain.user.Role; -import org.obiba.onyx.core.domain.user.User; -import org.obiba.onyx.core.service.UserService; -import org.obiba.wicket.test.MockSpringApplication; - -public class UserPanelTest { - - private WicketTester tester; - - private UserService userServiceMock; - - private UserPanel userPanel; - - @Before - public void setUp() { - ApplicationContextMock mockCtx = new ApplicationContextMock(); - userServiceMock = createMock(UserService.class); - - mockCtx.putBean("userService", userServiceMock); - - MockSpringApplication application = new MockSpringApplication(); - application.setApplicationContext(mockCtx); - tester = new WicketTester(application); - } - - @Test - public void testRetrieveUser() { - final User u = newUserTest(); - - expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); - - replay(userServiceMock); - - tester.startPanel(new TestPanelSource() { - - private static final long serialVersionUID = 1L; - - public Panel getTestPanel(String panelId) { - return (new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); - } - }); - - FormTester formTester = tester.newFormTester("panel:userPanelForm"); - - verify(userServiceMock); - - Assert.assertEquals("ndupont", formTester.getTextComponentValue("login")); - Assert.assertEquals("Dupont", formTester.getTextComponentValue("lastName")); - Assert.assertEquals("Nathalie", formTester.getTextComponentValue("firstName")); - Assert.assertEquals("ndupont@obiba.org", formTester.getTextComponentValue("email")); - Assert.assertEquals(Locale.ENGLISH, formTester.getForm().get("languageSelect:localeSelect").getModelObject()); - assertSetsEquals(getUserRoles(), (Set) formTester.getForm().get("roles").getModelObject()); - } - - @Test - public void testEditUser() { - final User u = newUserTest(); - - expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); - - replay(userServiceMock); - - tester.startPanel(new TestPanelSource() { - - private static final long serialVersionUID = 1L; - - public Panel getTestPanel(String panelId) { - return (new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); - } - }); - - FormTester formTester = tester.newFormTester("panel:userPanelForm"); - - formTester.setValue("email", "ndupont@obiba.com"); - - // formTester.select n'a pas l'air de fonctionner - // formTester.select("languageSelect:localeSelect", 0); - - formTester.submit(); - tester.assertNoErrorMessage(); - - verify(userServiceMock); - - Assert.assertEquals("ndupont@obiba.com", u.getEmail()); - } - - @Test - public void testAddUserError() { - final User u = new User(); - expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); - - replay(userServiceMock); - - tester.startPanel(new TestPanelSource() { - - private static final long serialVersionUID = 1L; - - public Panel getTestPanel(String panelId) { - return (userPanel = new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); - } - }); - - FormTester formTester = tester.newFormTester("panel:userPanelForm"); - formTester.setValue("lastName", "Tremblay"); - formTester.setValue("firstName", "Patrick"); - formTester.setValue("email", "ptremblay@obiba.org"); - formTester.submit(); - - StringResourceModel strModel = new StringResourceModel("Required", userPanel, new Model(new ValueMap("label=password"))); - StringResourceModel strModel1 = new StringResourceModel("Required", userPanel, new Model(new ValueMap("label=roles"))); - tester.assertErrorMessages(new String[] { strModel.getString(), strModel1.getString() }); - - verify(userServiceMock); - } - - @Test - public void testAddUser() { - final User u = new User(); - expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); - - replay(userServiceMock); - - tester.startPanel(new TestPanelSource() { - - private static final long serialVersionUID = 1L; - - public Panel getTestPanel(String panelId) { - return (userPanel = new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); - } - }); - - FormTester formTester = tester.newFormTester("panel:userPanelForm"); - formTester.setValue("lastName", "Tremblay"); - formTester.setValue("firstName", "Patrick"); - formTester.setValue("email", "ptremblay@obiba.org"); - formTester.setValue("password", "password01"); - formTester.selectMultiple("roles", new int[] { 0, 1 }); - formTester.submit(); - - tester.assertNoErrorMessage(); - verify(userServiceMock); - Assert.assertEquals("Tremblay", u.getLastName()); - // Assert that two Sets are identical - assertSetsEquals(getUserRoles(), u.getRoles()); - } - - private User newUserTest() { - User u = new User(); - - u.setId(1); - u.setLogin("ndupont"); - u.setLastName("Dupont"); - u.setFirstName("Nathalie"); - u.setEmail("ndupont@obiba.org"); - u.setLanguage(Locale.ENGLISH); - u.setPassword("password01"); - u.setRoles(getUserRoles()); - - return (u); - } - - private Set getUserRoles() { - Set roles = new HashSet(); - roles.add(Role.DATA_COLLECTION_OPERATOR); - roles.add(Role.PARTICIPANT_MANAGER); - return roles; - } - - private List newRoleListTest() { - List roleList = new ArrayList(); - - Role roleInstance = Role.DATA_COLLECTION_OPERATOR; - roleInstance.setId(1); - roleList.add(roleInstance); - - roleInstance = Role.PARTICIPANT_MANAGER; - roleInstance.setId(2); - roleList.add(roleInstance); - - roleInstance = Role.SYSTEM_ADMINISTRATOR; - roleInstance.setId(3); - roleList.add(roleInstance); - - return (roleList); - } - - private void assertSetsEquals(Set lhs, Set rhs) { - // Assert that lhs contains all the items in rhs AND that rhs contains all the items in lhs - // Testing both sides assures us that one set is not simply a subset of the other - Assert.assertTrue(lhs.containsAll(rhs) && rhs.containsAll(lhs)); - } - -} +/******************************************************************************* + * Copyright 2008(c) The OBiBa Consortium. All rights reserved. + * + * This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + ******************************************************************************/ +package org.obiba.onyx.webapp.user.panel; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.spring.test.ApplicationContextMock; +import org.apache.wicket.util.tester.FormTester; +import org.apache.wicket.util.tester.TestPanelSource; +import org.apache.wicket.util.tester.WicketTester; +import org.apache.wicket.util.value.ValueMap; +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.obiba.core.service.SortingClause; +import org.obiba.onyx.core.domain.user.Role; +import org.obiba.onyx.core.domain.user.User; +import org.obiba.onyx.core.service.UserService; +import org.obiba.wicket.test.MockSpringApplication; + +public class UserPanelTest { + + private WicketTester tester; + + private UserService userServiceMock; + + private UserPanel userPanel; + + @Before + public void setUp() { + ApplicationContextMock mockCtx = new ApplicationContextMock(); + userServiceMock = createMock(UserService.class); + + mockCtx.putBean("userService", userServiceMock); + + MockSpringApplication application = new MockSpringApplication(); + application.setApplicationContext(mockCtx); + tester = new WicketTester(application); + } + + @Test + public void testRetrieveUser() { + final User u = newUserTest(); + + expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); + + replay(userServiceMock); + + tester.startPanel(new TestPanelSource() { + + private static final long serialVersionUID = 1L; + + public Panel getTestPanel(String panelId) { + return (new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); + } + }); + + FormTester formTester = tester.newFormTester("panel:userPanelForm"); + + verify(userServiceMock); + + Assert.assertEquals("ndupont", formTester.getTextComponentValue("login")); + Assert.assertEquals("Dupont", formTester.getTextComponentValue("lastName")); + Assert.assertEquals("Nathalie", formTester.getTextComponentValue("firstName")); + Assert.assertEquals("ndupont@obiba.org", formTester.getTextComponentValue("email")); + Assert.assertEquals(Locale.ENGLISH, formTester.getForm().get("languageSelect:localeSelect").getModelObject()); + assertSetsEquals(getUserRoles(), (Set) formTester.getForm().get("roles").getModelObject()); + } + + @Test + public void testEditUser() { + final User u = newUserTest(); + + expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); + + replay(userServiceMock); + + tester.startPanel(new TestPanelSource() { + + private static final long serialVersionUID = 1L; + + public Panel getTestPanel(String panelId) { + return (new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); + } + }); + + FormTester formTester = tester.newFormTester("panel:userPanelForm"); + + formTester.setValue("email", "ndupont@obiba.com"); + + // formTester.select n'a pas l'air de fonctionner + // formTester.select("languageSelect:localeSelect", 0); + + formTester.submit(); + tester.assertNoErrorMessage(); + + verify(userServiceMock); + + Assert.assertEquals("ndupont@obiba.com", u.getEmail()); + } + + @Test + public void testAddUserError() { + final User u = new User(); + expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); + + replay(userServiceMock); + + tester.startPanel(new TestPanelSource() { + + private static final long serialVersionUID = 1L; + + public Panel getTestPanel(String panelId) { + return (userPanel = new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); + } + }); + + FormTester formTester = tester.newFormTester("panel:userPanelForm"); + formTester.setValue("lastName", "Tremblay"); + formTester.setValue("firstName", "Patrick"); + formTester.setValue("email", "ptremblay@obiba.org"); + formTester.submit(); + + StringResourceModel strModel = new StringResourceModel("Required", userPanel, new Model(new ValueMap("label=password"))); + StringResourceModel strModel1 = new StringResourceModel("Required", userPanel, new Model(new ValueMap("label=roles"))); + tester.assertErrorMessages(new String[] { strModel.getString(), strModel1.getString() }); + + verify(userServiceMock); + } + + @Test + public void testAddUser() { + final User u = new User(); + expect(userServiceMock.getRoles((SortingClause) EasyMock.anyObject())).andReturn(newRoleListTest()); + + replay(userServiceMock); + + tester.startPanel(new TestPanelSource() { + + private static final long serialVersionUID = 1L; + + public Panel getTestPanel(String panelId) { + return (userPanel = new UserPanel(panelId, new Model(u), new ModalWindow("windowMock"))); + } + }); + + FormTester formTester = tester.newFormTester("panel:userPanelForm"); + formTester.setValue("lastName", "Tremblay"); + formTester.setValue("firstName", "Patrick"); + formTester.setValue("email", "ptremblay@obiba.org"); + formTester.setValue("password", "password01"); + formTester.selectMultiple("roles", new int[] { 0, 1 }); + formTester.submit(); + + tester.assertNoErrorMessage(); + verify(userServiceMock); + Assert.assertEquals("Tremblay", u.getLastName()); + // Assert that two Sets are identical + assertSetsEquals(getUserRoles(), u.getRoles()); + } + + private User newUserTest() { + User u = new User(); + + u.setId(1); + u.setLogin("ndupont"); + u.setLastName("Dupont"); + u.setFirstName("Nathalie"); + u.setEmail("ndupont@obiba.org"); + u.setLanguage(Locale.ENGLISH); + u.setPassword("password01"); + u.setRoles(getUserRoles()); + + return (u); + } + + private Set getUserRoles() { + Set roles = new HashSet(); + roles.add(Role.DATA_COLLECTION_OPERATOR); + roles.add(Role.PARTICIPANT_MANAGER); + return roles; + } + + private List newRoleListTest() { + List roleList = new ArrayList(); + + Role roleInstance = Role.DATA_COLLECTION_OPERATOR; + roleInstance.setId(1); + roleList.add(roleInstance); + + roleInstance = Role.PARTICIPANT_MANAGER; + roleInstance.setId(2); + roleList.add(roleInstance); + + roleInstance = Role.SYSTEM_ADMINISTRATOR; + roleInstance.setId(3); + roleList.add(roleInstance); + + return (roleList); + } + + private void assertSetsEquals(Set lhs, Set rhs) { + // Assert that lhs contains all the items in rhs AND that rhs contains all the items in lhs + // Testing both sides assures us that one set is not simply a subset of the other + Assert.assertTrue(lhs.containsAll(rhs) && rhs.containsAll(lhs)); + } + +}