r119 - in trunk: . assembly cantharella.data cantharella.data/src/main/java/nc/ird/cantharella/data/config cantharella.data/src/main/java/nc/ird/cantharella/data/dao cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl cantharella.data/src/main/java/nc/ird/cantharella/data/dao/utils cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions cantharella.data/src/main/java/nc/ird/cantharella/data/model cantharella.data/src/main/java/nc/ird/cantharella/data/model/compara
Author: acheype Date: 2013-02-18 08:27:17 +0100 (Mon, 18 Feb 2013) New Revision: 119 Url: http://forge.codelutin.com/projects/cantharella/repository/revisions/119 Log: - Add the plugin maven-java-formatter-plugin with a multiproject shared config file to uniformize the code in each maven build - Reformat all the classes of the projet with the convention of the shared config file (eclipse format config) Added: trunk/assembly/ trunk/assembly/code-formatter-conf.xml trunk/src/code-formatter-conf/ trunk/src/code-formatter-conf/code-format.xml Modified: trunk/cantharella.data/pom.xml trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/DataContext.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/ValidationIntegrator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/GenericDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/CampagneDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ExtractionDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/HibernateTemplateDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/MoleculeDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PersonneDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ProduitDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PurificationDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/SpecimenDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/StationDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/TestBioDao.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/utils/GenericDaoAspect.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/AbstractException.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataConstraintException.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataNotFoundException.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/UnexpectedException.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Campagne.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagneGroupeDroits.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneDroits.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneParticipant.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Document.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Droits.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ErreurTestBio.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extraction.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extrait.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Fraction.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Groupe.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Lot.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotGroupeDroits.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotPersonneDroits.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeExtraction.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodePurification.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeTestBio.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Molecule.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MoleculeProvenance.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuri.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuriEffectif.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Partie.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Personne.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Produit.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Purification.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ResultatTestBio.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Specimen.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Station.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TestBio.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeDocument.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeExtrait.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Utilisateur.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/CampagnePersonneDroitsComp.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ExtraitsOfExtractionComp.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/FractionsOfPurificationComp.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/LotPersonneDroitsComp.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ResultatsOfTestBioComp.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/ProduitBridge.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/UtilisateurSearchFilter.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/AbstractModel.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/CompositeId.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueField.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueFieldValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCode.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCodeValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueField.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueFieldValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Latitude.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientation.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientationValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Longitude.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientation.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientationValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/QueryConstraintValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Referentiel.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/ReferentielValidator.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorEventListener.java trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorImpl.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/AbstractDataTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/DataContextTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/SchemaExporter.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/GenericDaoTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/SpringTransactionTestAppender.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/TestAppender.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTransactionTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/ModelValidatorTest.java trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/PersonneTest.java trunk/cantharella.service/pom.xml trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/config/ServiceContext.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/exceptions/EmailException.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/MoleculeProvenanceBean.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/SearchResult.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/DocumentService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/ExtractionService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/MailService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PersonneService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PurificationService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/TestBioService.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/CampagneServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/DocumentServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ExtractionServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/LotServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MailServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MoleculeServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PersonneServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ProduitServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PurificationServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SearchServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SpecimenServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/StationServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/TestBioServiceImpl.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/CampagneNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ConfigNameNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/DocumentNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/EmailNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ErreurTestNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ExtractionNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/LotNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeExtractionNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodePurificationNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeTestBioNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MoleculeNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PartieNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PersonneNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PurificationNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/SpecimenNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/StationNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TestBioNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TypeDocumentNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/UniqueFieldNormalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/Normalizer.java trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/NormalizerAspect.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/AbstractServiceTest.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/ServiceContextTest.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/exceptions/ExcelImportException.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/PersonneServiceTest.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/SearchServiceTest.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnStructure.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnsReader.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelSheetStructure.java trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/PopulateDB.java trunk/cantharella.utils/pom.xml trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/AssertTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanLookup.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CantharellaConfig.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CaptchaTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CollectionTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CoordTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenerateCsv.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenericsTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/IntuitiveStringComparator.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/NumberTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/Pair.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/PasswordTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTools.java trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTransformer.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/AssertToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanLookupTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CaptchaToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CollectionToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CoordToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/GenericsToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/NumberToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PairTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PasswordToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringToolsTest.java trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringTransformerTest.java trunk/cantharella.web/pom.xml trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebApplicationImpl.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebContext.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/ContactPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/HomePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/TemplatePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/LinkProduitPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/TaxonomyPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ListCampagnesPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ManageCampagnePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ReadCampagnePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ListConfigurationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageErreurTestBioPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeExtractionPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodePurificationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeTestBioPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManagePartiePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListErreurTestBioPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeExtractionPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodePurificationPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeTestBioPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListPartiePanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/RebuildLuceneIndexPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ManageDocumentPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ReadDocumentPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ExtraitsColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ListExtractionsPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ManageExtractionPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ReadExtractionPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ListLotsPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ManageLotPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ReadLotPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ListMoleculesPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ManageMoleculePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ReadMoleculePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ListPersonnesPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ManagePersonnePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ReadPersonnePage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ManagePersonnePanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ReadPersonnePanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ListPurificationsPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ManagePurificationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ReadPurificationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/search/SearchPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ListSpecimensPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ManageSpecimenPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ReadSpecimenPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ListStationsPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ManageStationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ReadStationPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ListTestsBioPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ManageTestBioPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ReadTestBioPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ManageUtilisateurPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ReadUtilisateurPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/RegisterPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ResetPasswordPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/UpdateUtilisateurPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/panels/ReadDroitsUtilisateurPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/errors/ErrorPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/CaptchaModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ContactModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/LoginModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageCampagneModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageStationModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageUtilisateurModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/RegisterModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/UpdateUtilisateurModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/PersonneRenderer.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/ProduitRenderer.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/CallerPage.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/JSConfirmationBehavior.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeEditorBehavior.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeViewBehavior.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/ReplaceEmptyLabelBehavior.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/AjaxButtonPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/BooleanPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/DecimalPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/EnumPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkableImagePropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/MapValuePropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/PercentPropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/ShortDatePropertyColumn.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/BigDecimalConverterImpl.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/DoubleConverterImpl.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/data/TableExportToolbar.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/AutoCompleteTextFieldString.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButton.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButtonEvents.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayBooleanPropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayDecimalPropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayEnumPropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayMapValuePropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayPercentPropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayShortDatePropertyModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/GenericLoadableDetachableModel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/LoadableDetachableSortableListDataProvider.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/SimpleSortableListDataProvider.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/CollapsiblePanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkProduitPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/SimpleTooltipPanel.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/EnumChoiceRenderer.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/MapChoiceRenderer.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/resources/WebMessages.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthContainer.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthSession.java trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthStrategy.java trunk/cantharella.web/src/test/java/nc/ird/cantharella/web/AbstractWebTest.java trunk/pom.xml Added: trunk/assembly/code-formatter-conf.xml =================================================================== --- trunk/assembly/code-formatter-conf.xml (rev 0) +++ trunk/assembly/code-formatter-conf.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -0,0 +1,20 @@ +<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" + + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd"> + <id>code-formatter-conf</id> + <formats> + <format>zip</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>${project.basedir}/src/code-formatter-conf</directory> + <outputDirectory/> + <includes> + <include>code-format.xml</include> + </includes> + </fileSet> + </fileSets> +</assembly> Modified: trunk/cantharella.data/pom.xml =================================================================== --- trunk/cantharella.data/pom.xml 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/pom.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -41,6 +41,14 @@ </dependency> </dependencies> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + <plugin> + <groupId>com.googlecode.maven-java-formatter-plugin</groupId> + <artifactId>maven-java-formatter-plugin</artifactId> + </plugin> </plugins> </build> Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/DataContext.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/DataContext.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/DataContext.java 2013-02-18 07:27:17 UTC (rev 119) @@ -77,7 +77,7 @@ // Import the spring context file @ImportResource(value = "classpath:/dataContext.xml") // Scans for @Repository, @Service and @Component -@ComponentScan(basePackages = {"nc.ird.cantharella.data.dao", "nc.ird.cantharella.data.validation.utils"}) +@ComponentScan(basePackages = { "nc.ird.cantharella.data.dao", "nc.ird.cantharella.data.validation.utils" }) // Enable @Transactional support -> not work with <aop:aspectj-autoproxy /> in xml context file @EnableTransactionManagement // This is a configuration class @@ -88,96 +88,113 @@ * Logger */ private static final Logger LOG = LoggerFactory.getLogger(DataContext.class); + /** * Country codes */ public static final List<String> COUNTRY_CODES = Collections.unmodifiableList(Arrays.asList(Locale - .getISOCountries())); + .getISOCountries())); + /** * DB connection: acquire retry attemps */ private static final int DB_CONNECTION_ACQUIRE_RETRY_ATTEMPS = 30; + /** * DB connexion: acquire retry delay */ private static final int DB_CONNECTION_ACQUIRE_RETRY_DELAY = 1000; + /** * DB pool: acquire increment */ private static final int DB_POOL_ACQUIRE_INCREMENT = 3; + /** * DB pool: max size */ private static final int DB_POOL_MAX_SIZE = 15; + /** * DB pool: min size */ private static final int DB_POOL_MIN_SIZE = 3; + /** * Encoding */ public static final String ENCODING = Charset.forName("UTF-8").name(); + /** * Availables locales for the application */ public static final List<Locale> LOCALES; + /** * Precision is the total number of digits */ public static final int DECIMAL_PRECISION = 9; + /** * Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a * precision of 5 and a scale of 2 * */ public static final int DECIMAL_SCALE = 4; + /** * According to DECIMAL_PRECISION and DECIMAL_SCALE, number max allowed for decimals. Attention to ensure that is * equal to 10^(DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE) -1 */ public static final int DECIMAL_MAX = 99999; + /** * Référentiels */ public static final Map<Integer, String> REFERENTIELS; + /** * DB debug */ @Value("${db.debug}") protected boolean dbDebugProperty; + /** * DB password */ @Value("${db.password}") protected String dbPasswordProperty; + /** * DB URL */ @Value("${db.url}") protected String dbUrlProperty; + /** * DB user */ @Value("${db.user}") protected String dbUserProperty; + /** * DB user */ @Value("${db.hbm2ddl:validate}") protected String hbm2ddl; - + static { - // The first Locale in the list is the default one - List<Locale> locales = new ArrayList<Locale>(); - locales.add(Locale.FRENCH); - locales.add(Locale.ENGLISH); + // The first Locale in the list is the default one + List<Locale> locales = new ArrayList<Locale>(); + locales.add(Locale.FRENCH); + locales.add(Locale.ENGLISH); - LOCALES = Collections.unmodifiableList(locales); - Locale.setDefault(LOCALES.get(0)); + LOCALES = Collections.unmodifiableList(locales); + Locale.setDefault(LOCALES.get(0)); - Map<Integer, String> referentiels = new HashMap<Integer, String>(); - referentiels.put(4326, "WGS84"); - REFERENTIELS = Collections.unmodifiableMap(referentiels); + Map<Integer, String> referentiels = new HashMap<Integer, String>(); + referentiels.put(4326, "WGS84"); + REFERENTIELS = Collections.unmodifiableMap(referentiels); } /** @@ -185,12 +202,12 @@ */ @Bean public MessageSourceAccessor dataMessageSource() { - // The ResourceBundleMessageSource does not handle UTF-8, so we use the Reloadable one - ReloadableResourceBundleMessageSource dataMessageSource = new ReloadableResourceBundleMessageSource(); - dataMessageSource.setBasename("data"); - dataMessageSource.setDefaultEncoding(ENCODING); - dataMessageSource.setCacheSeconds(-1); - return new MessageSourceAccessor(dataMessageSource); + // The ResourceBundleMessageSource does not handle UTF-8, so we use the Reloadable one + ReloadableResourceBundleMessageSource dataMessageSource = new ReloadableResourceBundleMessageSource(); + dataMessageSource.setBasename("data"); + dataMessageSource.setDefaultEncoding(ENCODING); + dataMessageSource.setCacheSeconds(-1); + return new MessageSourceAccessor(dataMessageSource); } /** @@ -198,53 +215,53 @@ */ @Bean public DataSource dataSource() { - ComboPooledDataSource dataSource = new ComboPooledDataSource(); - // Connexion - try { - dataSource.setDriverClass(Driver.class.getName()); - } catch (PropertyVetoException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - dataSource.setJdbcUrl(dbUrlProperty); - dataSource.setPassword(dbPasswordProperty); - dataSource.setUser(dbUserProperty); - // Pool: basic configuration - dataSource.setInitialPoolSize(DB_POOL_MIN_SIZE); - // Pool: size and connection age - dataSource.setMaxConnectionAge(0); - dataSource.setMaxIdleTimeExcessConnections(0); - // Pool: connection testing - dataSource.setAutomaticTestTable(null); - try { - dataSource.setConnectionTesterClassName(DefaultConnectionTester.class.getName()); - } catch (PropertyVetoException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - dataSource.setPreferredTestQuery(null); - dataSource.setTestConnectionOnCheckin(false); - dataSource.setTestConnectionOnCheckout(false); - // Pool: statement pooling - dataSource.setMaxStatementsPerConnection(0); - // Pool: recovery from database outages - dataSource.setAcquireRetryAttempts(DB_CONNECTION_ACQUIRE_RETRY_ATTEMPS); - dataSource.setAcquireRetryDelay(DB_CONNECTION_ACQUIRE_RETRY_DELAY); - dataSource.setBreakAfterAcquireFailure(false); - // Pool: connection lifecycles with connection customizer - dataSource.setConnectionCustomizerClassName(null); - // Pool: unresolved transaction handling - dataSource.setAutoCommitOnClose(false); - dataSource.setForceIgnoreUnresolvedTransactions(false); - // Pool: debug and workaround broken client applications - dataSource.setDebugUnreturnedConnectionStackTraces(false); - dataSource.setUnreturnedConnectionTimeout(0); - // Pool: dataSource - dataSource.setCheckoutTimeout(0); - dataSource.setFactoryClassLocation(null); - dataSource.setMaxAdministrativeTaskTime(0); - dataSource.setUsesTraditionalReflectiveProxies(false); - return dataSource; + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + // Connexion + try { + dataSource.setDriverClass(Driver.class.getName()); + } catch (PropertyVetoException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + dataSource.setJdbcUrl(dbUrlProperty); + dataSource.setPassword(dbPasswordProperty); + dataSource.setUser(dbUserProperty); + // Pool: basic configuration + dataSource.setInitialPoolSize(DB_POOL_MIN_SIZE); + // Pool: size and connection age + dataSource.setMaxConnectionAge(0); + dataSource.setMaxIdleTimeExcessConnections(0); + // Pool: connection testing + dataSource.setAutomaticTestTable(null); + try { + dataSource.setConnectionTesterClassName(DefaultConnectionTester.class.getName()); + } catch (PropertyVetoException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + dataSource.setPreferredTestQuery(null); + dataSource.setTestConnectionOnCheckin(false); + dataSource.setTestConnectionOnCheckout(false); + // Pool: statement pooling + dataSource.setMaxStatementsPerConnection(0); + // Pool: recovery from database outages + dataSource.setAcquireRetryAttempts(DB_CONNECTION_ACQUIRE_RETRY_ATTEMPS); + dataSource.setAcquireRetryDelay(DB_CONNECTION_ACQUIRE_RETRY_DELAY); + dataSource.setBreakAfterAcquireFailure(false); + // Pool: connection lifecycles with connection customizer + dataSource.setConnectionCustomizerClassName(null); + // Pool: unresolved transaction handling + dataSource.setAutoCommitOnClose(false); + dataSource.setForceIgnoreUnresolvedTransactions(false); + // Pool: debug and workaround broken client applications + dataSource.setDebugUnreturnedConnectionStackTraces(false); + dataSource.setUnreturnedConnectionTimeout(0); + // Pool: dataSource + dataSource.setCheckoutTimeout(0); + dataSource.setFactoryClassLocation(null); + dataSource.setMaxAdministrativeTaskTime(0); + dataSource.setUsesTraditionalReflectiveProxies(false); + return dataSource; } /** @@ -252,64 +269,65 @@ */ @Bean public SessionFactory sessionFactory() { - LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); - sessionFactoryBean.setDataSource(dataSource()); - sessionFactoryBean.setPackagesToScan(new String[]{"nc.ird.cantharella.data.model"}); - Properties hibernateProperties = new Properties(); - // Hibernate: basic - hibernateProperties.setProperty(Environment.DIALECT, PostgreSQL82Dialect.class.getName()); - //System.setProperty(Environment.BYTECODE_PROVIDER, "cglib"); - hibernateProperties.setProperty(Environment.HBM2DDL_AUTO, hbm2ddl); - // hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); - hibernateProperties.setProperty("hibernate.generate_statistics", String.valueOf(dbDebugProperty)); - hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty)); - hibernateProperties.setProperty("hibernate.show_sql", String.valueOf(false)); - hibernateProperties.setProperty("hibernate.format_sql", String.valueOf(false)); - hibernateProperties.setProperty("hibernate.use_sql_comments", String.valueOf(dbDebugProperty)); - // Hibernate: cache - hibernateProperties.setProperty("hibernate.cache.region.factory_class", SingletonEhCacheRegionFactory.class.getName()); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", String.valueOf(true)); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", String.valueOf(true)); - hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty)); - // Hibernate: connection - hibernateProperties.setProperty("hibernate.connection.autocommit", String.valueOf(false)); - hibernateProperties.setProperty("hibernate.connection.release_mode", "on_close"); - // Pool: c3p0 properties overrided by Hibernate - // echatellier 20121129 : désactivé car la datasource est construite - // à partir de c3p0, il ne faut donc pas que hibernate la gère - // sur c3p0 en plus - //hibernateProperties.setProperty(Environment.CONNECTION_PROVIDER, "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"); - //hibernateProperties.setProperty("hibernate.c3p0.acquire_increment", String.valueOf(DB_POOL_ACQUIRE_INCREMENT)); // acquireIncrement - //hibernateProperties.setProperty("hibernate.c3p0.idle_test_period", String.valueOf(0)); // idleConnectionTestPeriod - //hibernateProperties.setProperty("hibernate.c3p0.timeout", String.valueOf(0)); // maxIdleTime - //hibernateProperties.setProperty("hibernate.c3p0.max_size", String.valueOf(DB_POOL_MAX_SIZE)); // maxPoolSize - //hibernateProperties.setProperty("hibernate.c3p0.max_statements", String.valueOf(0)); // maxStatements - //hibernateProperties.setProperty("hibernate.c3p0.min_size", String.valueOf(DB_POOL_MIN_SIZE)); // minPoolSize - // Hibernate search - hibernateProperties.setProperty("hibernate.search.default.directory_provider", "filesystem"); - hibernateProperties.setProperty("hibernate.search.default.indexBase", "/tmp/cantharella/hs"); - hibernateProperties.setProperty("hibernate.search.analyzer", "org.apache.lucene.analysis.fr.FrenchAnalyzer"); + LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); + sessionFactoryBean.setDataSource(dataSource()); + sessionFactoryBean.setPackagesToScan(new String[] { "nc.ird.cantharella.data.model" }); + Properties hibernateProperties = new Properties(); + // Hibernate: basic + hibernateProperties.setProperty(Environment.DIALECT, PostgreSQL82Dialect.class.getName()); + //System.setProperty(Environment.BYTECODE_PROVIDER, "cglib"); + hibernateProperties.setProperty(Environment.HBM2DDL_AUTO, hbm2ddl); + // hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + hibernateProperties.setProperty("hibernate.generate_statistics", String.valueOf(dbDebugProperty)); + hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty)); + hibernateProperties.setProperty("hibernate.show_sql", String.valueOf(false)); + hibernateProperties.setProperty("hibernate.format_sql", String.valueOf(false)); + hibernateProperties.setProperty("hibernate.use_sql_comments", String.valueOf(dbDebugProperty)); + // Hibernate: cache + hibernateProperties.setProperty("hibernate.cache.region.factory_class", SingletonEhCacheRegionFactory.class + .getName()); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", String.valueOf(true)); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", String.valueOf(true)); + hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty)); + // Hibernate: connection + hibernateProperties.setProperty("hibernate.connection.autocommit", String.valueOf(false)); + hibernateProperties.setProperty("hibernate.connection.release_mode", "on_close"); + // Pool: c3p0 properties overrided by Hibernate + // echatellier 20121129 : désactivé car la datasource est construite + // à partir de c3p0, il ne faut donc pas que hibernate la gère + // sur c3p0 en plus + //hibernateProperties.setProperty(Environment.CONNECTION_PROVIDER, "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"); + //hibernateProperties.setProperty("hibernate.c3p0.acquire_increment", String.valueOf(DB_POOL_ACQUIRE_INCREMENT)); // acquireIncrement + //hibernateProperties.setProperty("hibernate.c3p0.idle_test_period", String.valueOf(0)); // idleConnectionTestPeriod + //hibernateProperties.setProperty("hibernate.c3p0.timeout", String.valueOf(0)); // maxIdleTime + //hibernateProperties.setProperty("hibernate.c3p0.max_size", String.valueOf(DB_POOL_MAX_SIZE)); // maxPoolSize + //hibernateProperties.setProperty("hibernate.c3p0.max_statements", String.valueOf(0)); // maxStatements + //hibernateProperties.setProperty("hibernate.c3p0.min_size", String.valueOf(DB_POOL_MIN_SIZE)); // minPoolSize + // Hibernate search + hibernateProperties.setProperty("hibernate.search.default.directory_provider", "filesystem"); + hibernateProperties.setProperty("hibernate.search.default.indexBase", "/tmp/cantharella/hs"); + hibernateProperties.setProperty("hibernate.search.analyzer", "org.apache.lucene.analysis.fr.FrenchAnalyzer"); - // Hibernate: Session - //hibernateProperties.setProperty("hibernate.current_session_context_class", "thread"); - //hibernateProperties.setProperty(Environment.JTA_PLATFORM, "hibernate.transaction.factory_class", SpringTransactionFactory.class.getName()); - // TODO batch_size à ajuster - hibernateProperties.setProperty("hibernate.default_batch_fetch_size", String.valueOf(20)); + // Hibernate: Session + //hibernateProperties.setProperty("hibernate.current_session_context_class", "thread"); + //hibernateProperties.setProperty(Environment.JTA_PLATFORM, "hibernate.transaction.factory_class", SpringTransactionFactory.class.getName()); + // TODO batch_size à ajuster + hibernateProperties.setProperty("hibernate.default_batch_fetch_size", String.valueOf(20)); - sessionFactoryBean.setHibernateProperties(hibernateProperties); + sessionFactoryBean.setHibernateProperties(hibernateProperties); - //Map<String, Object> eventListeners = new HashMap<String, Object>(); - //ModelValidatorEventListener validationListener = new ModelValidatorEventListener(validatorFactory()); - //eventListeners.put("pre-insert", validationListener); - //eventListeners.put("pre-update", validationListener); - //sessionFactoryBean.setEventListeners(eventListeners); + //Map<String, Object> eventListeners = new HashMap<String, Object>(); + //ModelValidatorEventListener validationListener = new ModelValidatorEventListener(validatorFactory()); + //eventListeners.put("pre-insert", validationListener); + //eventListeners.put("pre-update", validationListener); + //sessionFactoryBean.setEventListeners(eventListeners); - try { - sessionFactoryBean.afterPropertiesSet(); - } catch (Exception e) { - throw new RuntimeException("SessionFactory misconfiguration", e); - } - return sessionFactoryBean.getObject(); + try { + sessionFactoryBean.afterPropertiesSet(); + } catch (Exception e) { + throw new RuntimeException("SessionFactory misconfiguration", e); + } + return sessionFactoryBean.getObject(); } /** @@ -317,7 +335,7 @@ */ @Bean public HibernateTransactionManager transactionManager() { - return new HibernateTransactionManager(sessionFactory()); + return new HibernateTransactionManager(sessionFactory()); } /** @@ -325,9 +343,9 @@ */ @Bean public ValidatorFactory validatorFactory() { - // LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean(); - // return validatorFactory; - return Validation.buildDefaultValidatorFactory(); + // LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean(); + // return validatorFactory; + return Validation.buildDefaultValidatorFactory(); } /** @@ -335,7 +353,7 @@ */ @Bean public ModelValidator dataModelValidator() { - return new ModelValidatorImpl(validatorFactory(), dataMessageSource()); + return new ModelValidatorImpl(validatorFactory(), dataMessageSource()); } /** @@ -344,15 +362,14 @@ */ @Bean public static PropertySourcesPlaceholderConfigurer properties() { - PropertySourcesPlaceholderConfigurer pspc = - new PropertySourcesPlaceholderConfigurer(); - try { - pspc.setProperties(CantharellaConfig.getProperties()); - } catch (ArgumentsParserException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - pspc.setIgnoreUnresolvablePlaceholders(true); - return pspc; + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + try { + pspc.setProperties(CantharellaConfig.getProperties()); + } catch (ArgumentsParserException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/ValidationIntegrator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/ValidationIntegrator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/config/ValidationIntegrator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,33 +49,30 @@ private static final Logger LOG = LoggerFactory.getLogger(ValidationIntegrator.class); @Override - public void integrate(Configuration configuration, - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) { - if (LOG.isDebugEnabled()) { - LOG.debug("Registering validator into hibernate"); - } + public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, + SessionFactoryServiceRegistry serviceRegistry) { + if (LOG.isDebugEnabled()) { + LOG.debug("Registering validator into hibernate"); + } - // declare validator - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - ModelValidatorEventListener validationListener = new ModelValidatorEventListener(factory); + // declare validator + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ModelValidatorEventListener validationListener = new ModelValidatorEventListener(factory); - // register validator - EventListenerRegistry eventRegistry = serviceRegistry.getService(EventListenerRegistry.class); - eventRegistry.prependListeners(EventType.PRE_INSERT, validationListener); - eventRegistry.prependListeners(EventType.PRE_UPDATE, validationListener); + // register validator + EventListenerRegistry eventRegistry = serviceRegistry.getService(EventListenerRegistry.class); + eventRegistry.prependListeners(EventType.PRE_INSERT, validationListener); + eventRegistry.prependListeners(EventType.PRE_UPDATE, validationListener); } @Override - public void integrate(MetadataImplementor metadata, - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) { - integrate((Configuration)null, sessionFactory, serviceRegistry); + public void integrate(MetadataImplementor metadata, SessionFactoryImplementor sessionFactory, + SessionFactoryServiceRegistry serviceRegistry) { + integrate((Configuration) null, sessionFactory, serviceRegistry); } @Override - public void disintegrate(SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) { - + public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { + } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/GenericDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/GenericDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/GenericDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -102,7 +102,7 @@ */ @Transactional <M extends AbstractModel> void delete(Class<M> modelClass, Serializable id) throws DataConstraintException, - DataNotFoundException; + DataNotFoundException; /** * Delete a model @@ -210,7 +210,7 @@ */ @Transactional(readOnly = true) <M extends AbstractModel> List<M> readList(Class<M> modelClass, int firstResult, int maxResults, - String... sortColumns); + String... sortColumns); /** * Read models according to the order of @Id or @EmbeddedId column @@ -246,7 +246,7 @@ */ @Transactional(readOnly = true) <M extends AbstractModel> M read(Class<M> modelClass, String uniqueProperty, Serializable value) - throws DataNotFoundException; + throws DataNotFoundException; /** * Refresh a model object Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/CampagneDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/CampagneDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/CampagneDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,14 +37,14 @@ public final class CampagneDao extends AbstractModelDao { /** Criteria : différents programmes des campagnes déjà saisis */ - public static final DetachedCriteria CRITERIA_DISTINCT_CAMPAGNE_PROGRAMMES = DetachedCriteria - .forClass(Campagne.class).setProjection(Projections.distinct(Projections.property("programme"))) - .addOrder(Order.asc("programme")); + public static final DetachedCriteria CRITERIA_DISTINCT_CAMPAGNE_PROGRAMMES = DetachedCriteria.forClass( + Campagne.class).setProjection(Projections.distinct(Projections.property("programme"))).addOrder( + Order.asc("programme")); /** * Constructor (prevents from instantiation) */ private CampagneDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ExtractionDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ExtractionDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ExtractionDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,7 +39,7 @@ * Constructor (empêche l'instantiation) */ private ExtractionDao() { - // + // } /** @@ -48,8 +48,8 @@ * @return Le criteria **/ public static DetachedCriteria getCriteriaCountExtraitOfTypeExtrait(Integer idTypeExtrait) { - return DetachedCriteria.forClass(Extrait.class).createAlias("typeExtrait", "type") - .add(Restrictions.eq("type.idTypeExtrait", idTypeExtrait)).setProjection(Projections.rowCount()); + return DetachedCriteria.forClass(Extrait.class).createAlias("typeExtrait", "type").add( + Restrictions.eq("type.idTypeExtrait", idTypeExtrait)).setProjection(Projections.rowCount()); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/HibernateTemplateDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/HibernateTemplateDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/HibernateTemplateDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -65,8 +65,8 @@ * @return Criteria */ private static DetachedCriteria criteriaByProperty(Class<? extends AbstractModel> modelClass, String propertyName, - Serializable value) { - return DetachedCriteria.forClass(modelClass).add(Restrictions.eq(propertyName, value)); + Serializable value) { + return DetachedCriteria.forClass(modelClass).add(Restrictions.eq(propertyName, value)); } /* @@ -86,15 +86,15 @@ */ @Override public long count(DetachedCriteria criteria) { - AssertTools.assertNotNull(criteria); - return (Long) list(criteria.setProjection(Projections.rowCount())).get(0); + AssertTools.assertNotNull(criteria); + return (Long) list(criteria.setProjection(Projections.rowCount())).get(0); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> long count(Class<M> modelClass) { - AssertTools.assertNotNull(modelClass); - return (Long) list(DetachedCriteria.forClass(modelClass).setProjection(Projections.rowCount())).get(0); + AssertTools.assertNotNull(modelClass); + return (Long) list(DetachedCriteria.forClass(modelClass).setProjection(Projections.rowCount())).get(0); } /** @@ -102,202 +102,202 @@ */ @Override public long count(String hqlQuery, Object... parameters) { - AssertTools.assertNotEmpty(hqlQuery); - Query query = sessionFactory.getCurrentSession().createQuery(hqlQuery); - for (int i = 0; i < parameters.length; i++) { - query.setParameter(i, parameters[i]); - } - return (Long)query.iterate().next(); + AssertTools.assertNotEmpty(hqlQuery); + Query query = sessionFactory.getCurrentSession().createQuery(hqlQuery); + for (int i = 0; i < parameters.length; i++) { + query.setParameter(i, parameters[i]); + } + return (Long) query.iterate().next(); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void create(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().save(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().save(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void createOrUpdate(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().saveOrUpdate(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().saveOrUpdate(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void delete(Class<M> modelClass, Serializable id) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertNotNull(id); - sessionFactory.getCurrentSession().delete(read(modelClass, id)); + AssertTools.assertNotNull(modelClass); + AssertTools.assertNotNull(id); + sessionFactory.getCurrentSession().delete(read(modelClass, id)); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void delete(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().delete(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().delete(model); } /** {@inheritDoc} */ @Override public List<?> list(DetachedCriteria criteria) { - AssertTools.assertNotNull(criteria); - Criteria execCriteria = criteria.getExecutableCriteria(sessionFactory.getCurrentSession()); - return execCriteria.list(); + AssertTools.assertNotNull(criteria); + Criteria execCriteria = criteria.getExecutableCriteria(sessionFactory.getCurrentSession()); + return execCriteria.list(); } /** {@inheritDoc} */ @Override public List<?> list(String hqlQuery, Object... parameters) { - Query query = sessionFactory.getCurrentSession().createQuery(hqlQuery); - for (int i = 0; i < parameters.length; i++) { - query.setParameter(i, parameters[i]); - } - return query.list(); + Query query = sessionFactory.getCurrentSession().createQuery(hqlQuery); + for (int i = 0; i < parameters.length; i++) { + query.setParameter(i, parameters[i]); + } + return query.list(); } /** {@inheritDoc} */ @Override public int execute(final String sqlQuery, final Object... parameters) { - AssertTools.assertNotEmpty(sqlQuery); - Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); - for (int i = 0; i < parameters.length; i++) { - query.setParameter(i, parameters[i]); - } - int nbLines = Integer.valueOf(query.executeUpdate()); - // This way to execute requests shortcuts the Hibernate process, so we need to refresh the data cache - sessionFactory.getCurrentSession().flush(); - sessionFactory.getCurrentSession().clear(); - return nbLines; + AssertTools.assertNotEmpty(sqlQuery); + Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); + for (int i = 0; i < parameters.length; i++) { + query.setParameter(i, parameters[i]); + } + int nbLines = Integer.valueOf(query.executeUpdate()); + // This way to execute requests shortcuts the Hibernate process, so we need to refresh the data cache + sessionFactory.getCurrentSession().flush(); + sessionFactory.getCurrentSession().clear(); + return nbLines; } /** {@inheritDoc} */ @Override public <M extends AbstractModel> boolean exists(Class<M> modelClass, Serializable id) { - return count(criteriaByProperty(modelClass, AbstractModel.getIdField(modelClass).getName(), id).setProjection( - Projections.rowCount())) > 0; + return count(criteriaByProperty(modelClass, AbstractModel.getIdField(modelClass).getName(), id).setProjection( + Projections.rowCount())) > 0; } /** {@inheritDoc} */ @Override public <M extends AbstractModel> boolean exists(Class<M> modelClass, String property, Serializable value) { - return count(criteriaByProperty(modelClass, property, value).setProjection(Projections.rowCount())) > 0; + return count(criteriaByProperty(modelClass, property, value).setProjection(Projections.rowCount())) > 0; } /** {@inheritDoc} */ @Override public boolean exists(DetachedCriteria criteria) { - return count(criteria) > 0; + return count(criteria) > 0; } /** {@inheritDoc} */ @Override public <M extends AbstractModel> List<M> readList(Class<M> modelClass) { - AssertTools.assertNotNull(modelClass); - Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); - criteria.addOrder(Order.asc(AbstractModel.getIdField(modelClass).getName())); - return GenericsTools.cast(criteria.list()); + AssertTools.assertNotNull(modelClass); + Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); + criteria.addOrder(Order.asc(AbstractModel.getIdField(modelClass).getName())); + return GenericsTools.cast(criteria.list()); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> List<M> readList(Class<M> modelClass, String... sortColumns) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertNotEmpty(sortColumns); - Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); - for (String sortCol : sortColumns) { - criteria.addOrder(Order.asc(sortCol)); - } - return GenericsTools.cast(criteria.list()); + AssertTools.assertNotNull(modelClass); + AssertTools.assertNotEmpty(sortColumns); + Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); + for (String sortCol : sortColumns) { + criteria.addOrder(Order.asc(sortCol)); + } + return GenericsTools.cast(criteria.list()); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> List<M> readList(Class<M> modelClass, int firstResult, int maxResults) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertPositive(firstResult); - AssertTools.assertPositive(maxResults); - Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); - criteria.addOrder(Order.asc(AbstractModel.getIdField(modelClass).getName())); - criteria.setFirstResult(firstResult); - criteria.setMaxResults(maxResults); - return GenericsTools.cast(criteria.list()); + AssertTools.assertNotNull(modelClass); + AssertTools.assertPositive(firstResult); + AssertTools.assertPositive(maxResults); + Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); + criteria.addOrder(Order.asc(AbstractModel.getIdField(modelClass).getName())); + criteria.setFirstResult(firstResult); + criteria.setMaxResults(maxResults); + return GenericsTools.cast(criteria.list()); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> List<M> readList(Class<M> modelClass, int firstResult, int maxResults, - String... sortColumns) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertNotEmpty(sortColumns); - AssertTools.assertPositive(firstResult); - AssertTools.assertPositive(maxResults); - Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); - for (String sortCol : sortColumns) { - criteria.addOrder(Order.asc(sortCol)); - } - criteria.setFirstResult(firstResult); - criteria.setMaxResults(maxResults); - return GenericsTools.cast(criteria.list()); + String... sortColumns) { + AssertTools.assertNotNull(modelClass); + AssertTools.assertNotEmpty(sortColumns); + AssertTools.assertPositive(firstResult); + AssertTools.assertPositive(maxResults); + Criteria criteria = sessionFactory.getCurrentSession().createCriteria(modelClass); + for (String sortCol : sortColumns) { + criteria.addOrder(Order.asc(sortCol)); + } + criteria.setFirstResult(firstResult); + criteria.setMaxResults(maxResults); + return GenericsTools.cast(criteria.list()); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> M read(Class<M> modelClass, Serializable id) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertNotNull(id); + AssertTools.assertNotNull(modelClass); + AssertTools.assertNotNull(id); - M m = modelClass.cast(sessionFactory.getCurrentSession().get(modelClass, id)); - if (m == null) { - throw new ObjectRetrievalFailureException(modelClass, id); - } - return m; + M m = modelClass.cast(sessionFactory.getCurrentSession().get(modelClass, id)); + if (m == null) { + throw new ObjectRetrievalFailureException(modelClass, id); + } + return m; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <M extends AbstractModel> M read(Class<M> modelClass, String uniqueProperty, Serializable value) { - List<M> list = (List<M>) list(criteriaByProperty(modelClass, uniqueProperty, value)); - if (list.size() != 1) { - throw new ObjectRetrievalFailureException(modelClass, value); - } - return list.get(0); + List<M> list = (List<M>) list(criteriaByProperty(modelClass, uniqueProperty, value)); + if (list.size() != 1) { + throw new ObjectRetrievalFailureException(modelClass, value); + } + return list.get(0); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void refresh(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().refresh(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().refresh(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void update(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().update(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().update(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void evict(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().evict(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().evict(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> boolean contains(M model) { - AssertTools.assertNotNull(model); - return sessionFactory.getCurrentSession().contains(model); + AssertTools.assertNotNull(model); + return sessionFactory.getCurrentSession().contains(model); } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void merge(M model) { - AssertTools.assertNotNull(model); - sessionFactory.getCurrentSession().merge(model); + AssertTools.assertNotNull(model); + sessionFactory.getCurrentSession().merge(model); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/MoleculeDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/MoleculeDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/MoleculeDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,14 +38,14 @@ public final class MoleculeDao extends AbstractModelDao { /** Criteria : différents organismes des molécules déjà saisis */ - public static final DetachedCriteria CRITERIA_DISTINCT_MOLECULE_ORGANISMES = DetachedCriteria - .forClass(Molecule.class).setProjection(Projections.distinct(Projections.property("identifieePar"))) - .addOrder(Order.asc("identifieePar")); + public static final DetachedCriteria CRITERIA_DISTINCT_MOLECULE_ORGANISMES = DetachedCriteria.forClass( + Molecule.class).setProjection(Projections.distinct(Projections.property("identifieePar"))).addOrder( + Order.asc("identifieePar")); /** * Constructor (prevents from instantiation) */ private MoleculeDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PersonneDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PersonneDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PersonneDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,38 +36,37 @@ public final class PersonneDao extends AbstractModelDao { /** Criteria : compte les administrateurs */ - public static final DetachedCriteria CRITERIA_COUNT_ADMINS = DetachedCriteria.forClass(Utilisateur.class) - .add(Restrictions.eq("typeDroit", TypeDroit.ADMINISTRATEUR)) - .add(Restrictions.eq("estValide", Boolean.TRUE)).setProjection(Projections.rowCount()); + public static final DetachedCriteria CRITERIA_COUNT_ADMINS = DetachedCriteria.forClass(Utilisateur.class).add( + Restrictions.eq("typeDroit", TypeDroit.ADMINISTRATEUR)).add(Restrictions.eq("estValide", Boolean.TRUE)) + .setProjection(Projections.rowCount()); /** Criteria : liste les administrateurs */ - public static final DetachedCriteria CRITERIA_LIST_ADMINS = DetachedCriteria.forClass(Utilisateur.class) - .add(Restrictions.eq("typeDroit", TypeDroit.ADMINISTRATEUR)) - .add(Restrictions.eq("estValide", Boolean.TRUE)); + public static final DetachedCriteria CRITERIA_LIST_ADMINS = DetachedCriteria.forClass(Utilisateur.class).add( + Restrictions.eq("typeDroit", TypeDroit.ADMINISTRATEUR)).add(Restrictions.eq("estValide", Boolean.TRUE)); /** Criteria : liste les utilisateurs à valider */ - public static final DetachedCriteria CRITERIA_LIST_UTILISATEURS_INVALID = DetachedCriteria - .forClass(Utilisateur.class).add(Restrictions.eq("estValide", Boolean.FALSE)).addOrder(Order.asc("nom")) - .addOrder(Order.asc("prenom")); + public static final DetachedCriteria CRITERIA_LIST_UTILISATEURS_INVALID = DetachedCriteria.forClass( + Utilisateur.class).add(Restrictions.eq("estValide", Boolean.FALSE)).addOrder(Order.asc("nom")).addOrder( + Order.asc("prenom")); /** Criteria : liste les utilisateurs qui sont déjà valides */ public static final DetachedCriteria CRITERIA_LIST_UTILISATEURS_VALID = DetachedCriteria - .forClass(Utilisateur.class).add(Restrictions.eq("estValide", Boolean.TRUE)).addOrder(Order.asc("nom")) - .addOrder(Order.asc("prenom")); + .forClass(Utilisateur.class).add(Restrictions.eq("estValide", Boolean.TRUE)).addOrder(Order.asc("nom")) + .addOrder(Order.asc("prenom")); /** SQL : créé un utilisateur à partir d'une personne */ public static final String SQL_CREATE_UTILISATEUR_FROM_PERSONNE = String.format( - "INSERT INTO %s(estValide, passwordHash, typeDroit, idPersonne) VALUES (?, ?, ?, ?);", - Utilisateur.class.getSimpleName()); + "INSERT INTO %s(estValide, passwordHash, typeDroit, idPersonne) VALUES (?, ?, ?, ?);", Utilisateur.class + .getSimpleName()); /** SQL : supprime un utilisateur (mais pas la personne associée) */ public static final String SQL_DELETE_UTILISATEUR = String.format("DELETE FROM %s WHERE idPersonne = ?;", - Utilisateur.class.getSimpleName()); + Utilisateur.class.getSimpleName()); /** Criteria : valeurs existantes du champ 'organisme' pour les personnes existantes */ - public static final DetachedCriteria CRITERIA_DISTINCT_PERSONNE_ORGANISMES = DetachedCriteria - .forClass(Personne.class).setProjection(Projections.distinct(Projections.property("organisme"))) - .addOrder(Order.asc("organisme")); + public static final DetachedCriteria CRITERIA_DISTINCT_PERSONNE_ORGANISMES = DetachedCriteria.forClass( + Personne.class).setProjection(Projections.distinct(Projections.property("organisme"))).addOrder( + Order.asc("organisme")); /** * Liste l'utilisateur qui a le courriel et le password donné et qui est un utilisateur validé @@ -76,14 +75,14 @@ * @return Le criteria **/ public static DetachedCriteria getCriteriaAuthenticateUser(String courriel, String passwordHash) { - return DetachedCriteria.forClass(Utilisateur.class).add(Restrictions.eq("courriel", courriel)) - .add(Restrictions.eq("passwordHash", passwordHash)).add(Restrictions.eq("estValide", Boolean.TRUE)); + return DetachedCriteria.forClass(Utilisateur.class).add(Restrictions.eq("courriel", courriel)).add( + Restrictions.eq("passwordHash", passwordHash)).add(Restrictions.eq("estValide", Boolean.TRUE)); } /** * Constructor (empêche l'instantiation) */ private PersonneDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ProduitDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ProduitDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/ProduitDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,7 +38,7 @@ * Constructor (empêche l'instantiation) */ private ProduitDao() { - // + // } /** @@ -47,8 +47,8 @@ * @return Le criteria **/ public static DetachedCriteria getCriteriaCountPurifFromProduit(String refProduit) { - return DetachedCriteria.forClass(Purification.class).createAlias("produit", "prod").add( - Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); + return DetachedCriteria.forClass(Purification.class).createAlias("produit", "prod").add( + Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); } /** @@ -57,8 +57,8 @@ * @return Le criteria **/ public static DetachedCriteria getCriteriaCountTestBioFromProduit(String refProduit) { - return DetachedCriteria.forClass(ResultatTestBio.class).createAlias("produit", "prod").add( - Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); + return DetachedCriteria.forClass(ResultatTestBio.class).createAlias("produit", "prod").add( + Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); } /** @@ -67,8 +67,8 @@ * @return Le criteria **/ public static DetachedCriteria getCriteriaCountMoleculeFromProduit(String refProduit) { - return DetachedCriteria.forClass(MoleculeProvenance.class).createAlias("produit", "prod").add( - Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); + return DetachedCriteria.forClass(MoleculeProvenance.class).createAlias("produit", "prod").add( + Restrictions.eq("prod.ref", refProduit)).setProjection(Projections.rowCount()); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PurificationDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PurificationDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/PurificationDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -33,13 +33,13 @@ * du paramètre de la méthode. **/ public final static String COUNT_PURIF_WITH_PARAM_METHO = "select count(purif) from Purification purif inner join purif.paramsMetho paramsEff " - + "where paramsEff.id.pk2.idParamMethoPuri = ?"; + + "where paramsEff.id.pk2.idParamMethoPuri = ?"; /** * Constructor (empêche l'instantiation) */ private PurificationDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/SpecimenDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/SpecimenDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/SpecimenDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,42 +36,42 @@ public class SpecimenDao extends AbstractModelDao { /** Criteria : valeurs existantes du champ 'embranchement' existants pour les spécimens existants */ - public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_EMBRANCHEMENTS = DetachedCriteria - .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("embranchement"))) - .addOrder(Order.asc("embranchement")); + public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_EMBRANCHEMENTS = DetachedCriteria.forClass( + Specimen.class).setProjection(Projections.distinct(Projections.property("embranchement"))).addOrder( + Order.asc("embranchement")); /** Criteria : valeurs existantes du champ 'famille' existants pour les spécimens existants */ public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_FAMILLES = DetachedCriteria - .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("famille"))) - .addOrder(Order.asc("famille")); + .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("famille"))).addOrder( + Order.asc("famille")); /** Criteria : valeurs existantes du champ 'genre' existants pour les spécimens existants */ public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_GENRES = DetachedCriteria.forClass(Specimen.class) - .setProjection(Projections.distinct(Projections.property("genre"))).addOrder(Order.asc("genre")); + .setProjection(Projections.distinct(Projections.property("genre"))).addOrder(Order.asc("genre")); /** Criteria : valeurs existantes du champ 'espece' existants pour les spécimens existants */ public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_ESPECES = DetachedCriteria.forClass(Specimen.class) - .setProjection(Projections.distinct(Projections.property("espece"))).addOrder(Order.asc("espece")); + .setProjection(Projections.distinct(Projections.property("espece"))).addOrder(Order.asc("espece")); /** Criteria : valeurs existantes du champ 'sousEspece' existants pour les spécimens existants */ - public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_SOUSESPECES = DetachedCriteria - .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("sousEspece"))) - .addOrder(Order.asc("sousEspece")); + public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_SOUSESPECES = DetachedCriteria.forClass( + Specimen.class).setProjection(Projections.distinct(Projections.property("sousEspece"))).addOrder( + Order.asc("sousEspece")); /** Criteria : valeurs existantes du champ 'variete' existants pour les spécimens existants */ public static final DetachedCriteria CRITERIA_DISTINCT_SPECIMEN_VARIETES = DetachedCriteria - .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("variete"))) - .addOrder(Order.asc("variete")); + .forClass(Specimen.class).setProjection(Projections.distinct(Projections.property("variete"))).addOrder( + Order.asc("variete")); /** Criteria : valeurs existantes du champ 'variete' existants pour les spécimens existants */ public static final DetachedCriteria CRITERIA_DISTINCT_LIEUX_DEPOT = DetachedCriteria.forClass(Specimen.class) - .setProjection(Projections.distinct(Projections.property("lieuDepot"))).addOrder(Order.asc("lieuDepot")); + .setProjection(Projections.distinct(Projections.property("lieuDepot"))).addOrder(Order.asc("lieuDepot")); /** * Constructeur (empêche l'instantiation) */ private SpecimenDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/StationDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/StationDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/StationDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,12 +38,12 @@ /** Criteria : différentes localités des stations déjà saisies */ public static final DetachedCriteria CRITERIA_DISTINCT_STATION_LOCALITES = DetachedCriteria.forClass(Station.class) - .setProjection(Projections.distinct(Projections.property("localite"))).addOrder(Order.asc("localite")); + .setProjection(Projections.distinct(Projections.property("localite"))).addOrder(Order.asc("localite")); /** * Constructeur (empêche l'instantiation) */ private StationDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/TestBioDao.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/TestBioDao.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/impl/TestBioDao.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,36 +42,36 @@ * Criteria : liste les résultats de tests bio qui sont de type "produit". L'ensemble est trié par (cible, produit, * id) */ - public static final DetachedCriteria CRITERIA_LIST_RESULTATS_TYPE_PRODUIT = DetachedCriteria - .forClass(ResultatTestBio.class, "r").add(Restrictions.eq("r.typeResultat", TypeResultat.PRODUIT)) - .createCriteria("testBio", "t").createCriteria("t.methode", "m").addOrder(Order.asc("m.cible")) - .createCriteria("r.produit", "p").addOrder(Order.asc("p.ref")).addOrder(Order.asc("r.id")); + public static final DetachedCriteria CRITERIA_LIST_RESULTATS_TYPE_PRODUIT = DetachedCriteria.forClass( + ResultatTestBio.class, "r").add(Restrictions.eq("r.typeResultat", TypeResultat.PRODUIT)).createCriteria( + "testBio", "t").createCriteria("t.methode", "m").addOrder(Order.asc("m.cible")).createCriteria("r.produit", + "p").addOrder(Order.asc("p.ref")).addOrder(Order.asc("r.id")); /** Criteria : compte les résultats de tests bio qui sont de type "produit" */ - public static final DetachedCriteria CRITERIA_COUNT_RESULTATS_TYPE_PRODUIT = DetachedCriteria - .forClass(ResultatTestBio.class).add(Restrictions.eq("typeResultat", TypeResultat.PRODUIT)) - .setProjection(Projections.rowCount()); + public static final DetachedCriteria CRITERIA_COUNT_RESULTATS_TYPE_PRODUIT = DetachedCriteria.forClass( + ResultatTestBio.class).add(Restrictions.eq("typeResultat", TypeResultat.PRODUIT)).setProjection( + Projections.rowCount()); /** Criteria : valeurs existantes du champ 'domaines' existants pour les méthodes de tests biologiques */ - public static final DetachedCriteria CRITERIA_DISTINCT_DOMAINES_METHODES = DetachedCriteria - .forClass(MethodeTestBio.class).setProjection(Projections.distinct(Projections.property("domaine"))) - .addOrder(Order.asc("domaine")); + public static final DetachedCriteria CRITERIA_DISTINCT_DOMAINES_METHODES = DetachedCriteria.forClass( + MethodeTestBio.class).setProjection(Projections.distinct(Projections.property("domaine"))).addOrder( + Order.asc("domaine")); /** Criteria : valeurs existantes du champ 'uniteResultat' existants pour les méthodes de tests biologiques */ - public static final DetachedCriteria CRITERIA_DISTINCT_UNITES_RESULTAT_METHODES = DetachedCriteria - .forClass(MethodeTestBio.class).setProjection(Projections.distinct(Projections.property("uniteResultat"))) - .addOrder(Order.asc("uniteResultat")); + public static final DetachedCriteria CRITERIA_DISTINCT_UNITES_RESULTAT_METHODES = DetachedCriteria.forClass( + MethodeTestBio.class).setProjection(Projections.distinct(Projections.property("uniteResultat"))).addOrder( + Order.asc("uniteResultat")); /** Criteria : valeurs existantes du champ 'uniteResultat' existants pour les méthodes de tests biologiques */ - public static final DetachedCriteria CRITERIA_DISTINCT_PRODUITS_TEMOINS = DetachedCriteria - .forClass(ResultatTestBio.class).setProjection(Projections.distinct(Projections.property("produitTemoin"))) - .addOrder(Order.asc("produitTemoin")); + public static final DetachedCriteria CRITERIA_DISTINCT_PRODUITS_TEMOINS = DetachedCriteria.forClass( + ResultatTestBio.class).setProjection(Projections.distinct(Projections.property("produitTemoin"))).addOrder( + Order.asc("produitTemoin")); /** * Constructor (empêche l'instantiation) */ private TestBioDao() { - // + // } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/utils/GenericDaoAspect.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/utils/GenericDaoAspect.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/dao/utils/GenericDaoAspect.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,7 +53,7 @@ */ @AfterThrowing(pointcut = "execution(* nc.ird.cantharella.data.dao.GenericDao.*(..))", throwing = "e") public void afterThrowing(DataIntegrityViolationException e) throws DataConstraintException { - throw new DataConstraintException(e); + throw new DataConstraintException(e); } /** @@ -63,6 +63,6 @@ */ @AfterThrowing(pointcut = "execution(* nc.ird.cantharella.data.dao.GenericDao.*(..))", throwing = "e") public void afterThrowing(DataRetrievalFailureException e) throws DataNotFoundException { - throw new DataNotFoundException(e); + throw new DataNotFoundException(e); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/AbstractException.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/AbstractException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/AbstractException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -33,7 +33,7 @@ * Constructor */ protected AbstractException() { - // + // } /** @@ -41,7 +41,7 @@ * @param cause Cause */ protected AbstractException(Exception cause) { - super(cause.getMessage(), cause); + super(cause.getMessage(), cause); } /** @@ -49,7 +49,7 @@ * @param message Message */ protected AbstractException(String message) { - super(message); + super(message); } /** @@ -58,6 +58,6 @@ * @param cause Cause */ protected AbstractException(String message, Exception cause) { - super(message, cause); + super(message, cause); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataConstraintException.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataConstraintException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataConstraintException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,7 +35,7 @@ * Constructor */ public DataConstraintException() { - // + // } /** @@ -43,6 +43,6 @@ * @param cause Cause */ public DataConstraintException(DataIntegrityViolationException cause) { - super(cause); + super(cause); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataNotFoundException.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataNotFoundException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/DataNotFoundException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,6 +36,6 @@ * @param cause Cause */ public DataNotFoundException(DataRetrievalFailureException cause) { - super(cause); + super(cause); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/UnexpectedException.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/UnexpectedException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/exceptions/UnexpectedException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -34,16 +34,16 @@ * @param cause Cause */ public UnexpectedException(Exception cause) { - super(cause.getMessage(), cause); + super(cause.getMessage(), cause); } - + /** * Constructor * @param message Message * @param cause Cause */ public UnexpectedException(String message, Exception cause) { - super(message, cause); + super(message, cause); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Campagne.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Campagne.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Campagne.java 2013-02-18 07:27:17 UTC (rev 119) @@ -76,7 +76,7 @@ @NotNull @NotEmpty @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String nom; /** Code pays */ @@ -91,12 +91,14 @@ /** Mention légale décrivant les droits sur les données */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String mentionLegale; /** Complément */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Date début */ @@ -127,7 +129,7 @@ /** Participants */ @NotNull @OneToMany(mappedBy = "id.pk1", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private List<CampagnePersonneParticipant> participants; /** Droits personnes */ @@ -138,30 +140,30 @@ /** Stations prospectées **/ @NotNull @ManyToMany(fetch = FetchType.LAZY) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private List<Station> stations; /** * Constructor */ public Campagne() { - lots = new ArrayList<Lot>(); - participants = new ArrayList<CampagnePersonneParticipant>(); - stations = new ArrayList<Station>(); - personnesDroits = new ArrayList<CampagnePersonneDroits>(); - groupesDroits = new ArrayList<CampagneGroupeDroits>(); + lots = new ArrayList<Lot>(); + participants = new ArrayList<CampagnePersonneParticipant>(); + stations = new ArrayList<Station>(); + personnesDroits = new ArrayList<CampagnePersonneDroits>(); + groupesDroits = new ArrayList<CampagneGroupeDroits>(); } /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(Campagne campagne) { - return new BeanComparator("nom").compare(this, campagne); + return new BeanComparator("nom").compare(this, campagne); } /** @@ -169,8 +171,8 @@ * @return Les stations triées */ public List<Station> getSortedStations() { - Collections.sort(stations); - return stations; + Collections.sort(stations); + return stations; } /** @@ -178,7 +180,7 @@ * @return idCampagne */ public Integer getIdCampagne() { - return idCampagne; + return idCampagne; } /** @@ -186,7 +188,7 @@ * @param idCampagne idCampagne */ public void setIdCampagne(Integer idCampagne) { - this.idCampagne = idCampagne; + this.idCampagne = idCampagne; } /** @@ -194,7 +196,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -202,7 +204,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -210,7 +212,7 @@ * @return codePays */ public String getCodePays() { - return codePays; + return codePays; } /** @@ -218,7 +220,7 @@ * @param codePays codePays */ public void setCodePays(String codePays) { - this.codePays = codePays; + this.codePays = codePays; } /** @@ -226,7 +228,7 @@ * @return programme */ public String getProgramme() { - return programme; + return programme; } /** @@ -234,7 +236,7 @@ * @param programme programme */ public void setProgramme(String programme) { - this.programme = programme; + this.programme = programme; } /** @@ -242,7 +244,7 @@ * @return mentionLegale */ public String getMentionLegale() { - return mentionLegale; + return mentionLegale; } /** @@ -250,7 +252,7 @@ * @param mentionLegale mentionLegale */ public void setMentionLegale(String mentionLegale) { - this.mentionLegale = mentionLegale; + this.mentionLegale = mentionLegale; } /** @@ -258,7 +260,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -266,7 +268,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -274,7 +276,7 @@ * @return dateDeb */ public Date getDateDeb() { - return dateDeb; + return dateDeb; } /** @@ -282,7 +284,7 @@ * @param dateDeb dateDeb */ public void setDateDeb(Date dateDeb) { - this.dateDeb = dateDeb; + this.dateDeb = dateDeb; } /** @@ -290,7 +292,7 @@ * @return dateFin */ public Date getDateFin() { - return dateFin; + return dateFin; } /** @@ -298,7 +300,7 @@ * @param dateFin dateFin */ public void setDateFin(Date dateFin) { - this.dateFin = dateFin; + this.dateFin = dateFin; } /** @@ -306,7 +308,7 @@ * @return groupesDroits */ public List<CampagneGroupeDroits> getGroupesDroits() { - return groupesDroits; + return groupesDroits; } /** @@ -314,7 +316,7 @@ * @param groupesDroits groupesDroits */ public void setGroupesDroits(List<CampagneGroupeDroits> groupesDroits) { - this.groupesDroits = groupesDroits; + this.groupesDroits = groupesDroits; } /** @@ -322,7 +324,7 @@ * @return lots */ public List<Lot> getLots() { - return lots; + return lots; } /** @@ -330,7 +332,7 @@ * @param lots lots */ public void setLots(List<Lot> lots) { - this.lots = lots; + this.lots = lots; } /** @@ -338,7 +340,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -346,7 +348,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -354,7 +356,7 @@ * @return participants */ public List<CampagnePersonneParticipant> getParticipants() { - return participants; + return participants; } /** @@ -362,7 +364,7 @@ * @param participants participants */ public void setParticipants(List<CampagnePersonneParticipant> participants) { - this.participants = participants; + this.participants = participants; } /** @@ -370,7 +372,7 @@ * @return personnesDroits */ public List<CampagnePersonneDroits> getPersonnesDroits() { - return personnesDroits; + return personnesDroits; } /** @@ -378,7 +380,7 @@ * @param personnesDroits personnesDroits */ public void setPersonnesDroits(List<CampagnePersonneDroits> personnesDroits) { - this.personnesDroits = personnesDroits; + this.personnesDroits = personnesDroits; } /** @@ -386,7 +388,7 @@ * @return stations */ public List<Station> getStations() { - return stations; + return stations; } /** @@ -394,7 +396,7 @@ * @param stations stations */ public void setStations(List<Station> stations) { - this.stations = stations; + this.stations = stations; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagneGroupeDroits.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagneGroupeDroits.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagneGroupeDroits.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,8 +52,8 @@ * Constructeur */ public CampagneGroupeDroits() { - droits = new Droits(); - id = new CompositeId<Campagne, Groupe>(); + droits = new Droits(); + id = new CompositeId<Campagne, Groupe>(); } /** @@ -61,7 +61,7 @@ * @return droits */ public Droits getDroits() { - return droits; + return droits; } /** @@ -69,7 +69,7 @@ * @param droits droits */ public void setDroits(Droits droits) { - this.droits = droits; + this.droits = droits; } /** @@ -77,7 +77,7 @@ * @return id */ public CompositeId<Campagne, Groupe> getId() { - return id; + return id; } /** @@ -85,7 +85,7 @@ * @param id id */ public void setId(CompositeId<Campagne, Groupe> id) { - this.id = id; + this.id = id; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneDroits.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneDroits.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneDroits.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,17 +51,17 @@ * Constructeur */ public CampagnePersonneDroits() { - droits = new Droits(); - id = new CompositeId<Campagne, Personne>(); + droits = new Droits(); + id = new CompositeId<Campagne, Personne>(); } /** {@inheritDoc} */ @Override public CampagnePersonneDroits clone() throws CloneNotSupportedException { - CampagnePersonneDroits clone = new CampagnePersonneDroits(); - clone.id = id.clone(); - clone.droits = droits.clone(); - return clone; + CampagnePersonneDroits clone = new CampagnePersonneDroits(); + clone.id = id.clone(); + clone.droits = droits.clone(); + return clone; } /** @@ -69,7 +69,7 @@ * @return droits */ public Droits getDroits() { - return droits; + return droits; } /** @@ -77,7 +77,7 @@ * @param droits droits */ public void setDroits(Droits droits) { - this.droits = droits; + this.droits = droits; } /** @@ -85,7 +85,7 @@ * @return id */ public CompositeId<Campagne, Personne> getId() { - return id; + return id; } /** @@ -93,7 +93,7 @@ * @param id id */ public void setId(CompositeId<Campagne, Personne> id) { - this.id = id; + this.id = id; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneParticipant.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneParticipant.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/CampagnePersonneParticipant.java 2013-02-18 07:27:17 UTC (rev 119) @@ -43,7 +43,8 @@ /** Complément */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** ID */ @@ -55,16 +56,16 @@ * Constructor */ public CampagnePersonneParticipant() { - id = new CompositeId<Campagne, Personne>(); + id = new CompositeId<Campagne, Personne>(); } /** {@inheritDoc} */ @Override public final CampagnePersonneParticipant clone() throws CloneNotSupportedException { - CampagnePersonneParticipant clone = (CampagnePersonneParticipant) super.clone(); - clone.id = id.clone(); - clone.complement = complement; - return clone; + CampagnePersonneParticipant clone = (CampagnePersonneParticipant) super.clone(); + clone.id = id.clone(); + clone.complement = complement; + return clone; } /** @@ -72,7 +73,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -80,7 +81,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -88,7 +89,7 @@ * @return id */ public CompositeId<Campagne, Personne> getId() { - return id; + return id; } /** @@ -96,6 +97,6 @@ * @param id id */ public void setId(CompositeId<Campagne, Personne> id) { - this.id = id; + this.id = id; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Document.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Document.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Document.java 2013-02-18 07:27:17 UTC (rev 119) @@ -75,7 +75,8 @@ /** Description. */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Langue. */ @@ -112,106 +113,106 @@ private String fileMimetype; public Integer getIdDocument() { - return idDocument; + return idDocument; } public void setIdDocument(Integer idDocument) { - this.idDocument = idDocument; + this.idDocument = idDocument; } public String getTitre() { - return titre; + return titre; } public void setTitre(String titre) { - this.titre = titre; + this.titre = titre; } public Personne getCreateur() { - return createur; + return createur; } public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } public Date getDateCreation() { - return dateCreation; + return dateCreation; } public void setDateCreation(Date dateCreation) { - this.dateCreation = dateCreation; + this.dateCreation = dateCreation; } public String getEditeur() { - return editeur; + return editeur; } public void setEditeur(String editeur) { - this.editeur = editeur; + this.editeur = editeur; } public String getDescription() { - return description; + return description; } public void setDescription(String description) { - this.description = description; + this.description = description; } public String getLangue() { - return langue; + return langue; } public void setLangue(String langue) { - this.langue = langue; + this.langue = langue; } public String getContrainteLegale() { - return contrainteLegale; + return contrainteLegale; } public void setContrainteLegale(String contrainteLegale) { - this.contrainteLegale = contrainteLegale; + this.contrainteLegale = contrainteLegale; } public Personne getAjoutePar() { - return ajoutePar; + return ajoutePar; } public void setAjoutePar(Personne ajoutePar) { - this.ajoutePar = ajoutePar; + this.ajoutePar = ajoutePar; } public TypeDocument getTypeDocument() { - return typeDocument; + return typeDocument; } public void setTypeDocument(TypeDocument typeDocument) { - this.typeDocument = typeDocument; + this.typeDocument = typeDocument; } public String getFileName() { - return fileName; + return fileName; } public void setFileName(String fileName) { - this.fileName = fileName; + this.fileName = fileName; } public byte[] getFileContent() { - return fileContent; + return fileContent; } public void setFileContent(byte[] fileContent) { - this.fileContent = fileContent; + this.fileContent = fileContent; } public String getFileMimetype() { - return fileMimetype; + return fileMimetype; } public void setFileMimetype(String fileMimetype) { - this.fileMimetype = fileMimetype; + this.fileMimetype = fileMimetype; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Droits.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Droits.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Droits.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,25 +57,25 @@ /** {@inheritDoc} */ @Override public Droits clone() throws CloneNotSupportedException { - Droits clone = (Droits) super.clone(); - clone.droitExtrait = droitExtrait; - clone.droitPuri = droitPuri; - clone.droitRecolte = droitRecolte; - clone.droitTestBio = droitTestBio; - return clone; + Droits clone = (Droits) super.clone(); + clone.droitExtrait = droitExtrait; + clone.droitPuri = droitPuri; + clone.droitRecolte = droitRecolte; + clone.droitTestBio = droitTestBio; + return clone; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { - return BeanTools.equals(this, obj, AccessType.GETTER, "droitExtrait", "droitPuri", "droitRecolte", - "droitTestBio"); + return BeanTools.equals(this, obj, AccessType.GETTER, "droitExtrait", "droitPuri", "droitRecolte", + "droitTestBio"); } /** {@inheritDoc} */ @Override public int hashCode() { - return BeanTools.hashCode(this, droitExtrait, droitPuri, droitRecolte, droitTestBio); + return BeanTools.hashCode(this, droitExtrait, droitPuri, droitRecolte, droitTestBio); } /** @@ -83,7 +83,7 @@ * @return droitExtrait */ public Boolean getDroitExtrait() { - return droitExtrait; + return droitExtrait; } /** @@ -91,7 +91,7 @@ * @param droitExtrait droitExtrait */ public void setDroitExtrait(Boolean droitExtrait) { - this.droitExtrait = droitExtrait; + this.droitExtrait = droitExtrait; } /** @@ -99,7 +99,7 @@ * @return droitPuri */ public Boolean getDroitPuri() { - return droitPuri; + return droitPuri; } /** @@ -107,7 +107,7 @@ * @param droitPuri droitPuri */ public void setDroitPuri(Boolean droitPuri) { - this.droitPuri = droitPuri; + this.droitPuri = droitPuri; } /** @@ -115,7 +115,7 @@ * @return droitRecolte */ public Boolean getDroitRecolte() { - return droitRecolte; + return droitRecolte; } /** @@ -123,7 +123,7 @@ * @param droitRecolte droitRecolte */ public void setDroitRecolte(Boolean droitRecolte) { - this.droitRecolte = droitRecolte; + this.droitRecolte = droitRecolte; } /** @@ -131,7 +131,7 @@ * @return droitTestBio */ public Boolean getDroitTestBio() { - return droitTestBio; + return droitTestBio; } /** @@ -139,7 +139,7 @@ * @param droitTestBio droitTestBio */ public void setDroitTestBio(Boolean droitTestBio) { - this.droitTestBio = droitTestBio; + this.droitTestBio = droitTestBio; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ErreurTestBio.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ErreurTestBio.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ErreurTestBio.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,20 +57,21 @@ /** Description */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 @NotEmpty private String description; /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(ErreurTestBio erreurTest) { - return new BeanComparator("nom").compare(this, erreurTest); + return new BeanComparator("nom").compare(this, erreurTest); } /** @@ -78,7 +79,7 @@ * @return idErreurTest */ public Integer getIdErreurTest() { - return idErreurTest; + return idErreurTest; } /** @@ -86,7 +87,7 @@ * @param idErreurTest idErreurTest */ public void setIdErreurTest(Integer idErreurTest) { - this.idErreurTest = idErreurTest; + this.idErreurTest = idErreurTest; } /** @@ -94,7 +95,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -102,7 +103,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -110,7 +111,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -118,6 +119,6 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extraction.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extraction.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extraction.java 2013-02-18 07:27:17 UTC (rev 119) @@ -70,9 +70,7 @@ */ @Entity @Indexed -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Extraction", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Extraction", impl = UtilisateurSearchFilter.class) }) public class Extraction extends AbstractModel implements Comparable<Extraction> { /** Id de l'extraction */ @@ -84,7 +82,7 @@ @Length(max = LENGTH_MEDIUM_TEXT) @Column(unique = true) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Manipulateur */ @@ -105,7 +103,7 @@ /** Lot utilisé pour l'extraction **/ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Lot lot; /** Masse avant l'extraction **/ @@ -116,7 +114,8 @@ /** Commentaire pour la manip */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Créateur */ @@ -128,7 +127,7 @@ /** Extraits produits par l'extraction */ @NotNull @OneToMany(mappedBy = "extraction", fetch = FetchType.EAGER, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) @ContainedIn private List<Extrait> extraits; @@ -136,22 +135,22 @@ * Constructeur */ public Extraction() { - extraits = new ArrayList<Extrait>(); + extraits = new ArrayList<Extrait>(); } /** {@inheritDoc} */ @Override public String toString() { - return ref; + return ref; } /** {@inheritDoc} */ @Override public int compareTo(Extraction extraction) { - ComparatorChain comparatorChain = new ComparatorChain(); - comparatorChain.addComparator(new BeanComparator("lot")); - comparatorChain.addComparator(new BeanComparator("ref")); - return comparatorChain.compare(this, extraction); + ComparatorChain comparatorChain = new ComparatorChain(); + comparatorChain.addComparator(new BeanComparator("lot")); + comparatorChain.addComparator(new BeanComparator("ref")); + return comparatorChain.compare(this, extraction); } /** @@ -159,10 +158,10 @@ * @return resultats */ public List<Extrait> getSortedExtraits() { - // comme "@Sort(type = SortType.COMPARATOR, comparator = ExtraitsOfExtractionComp.class)" ne rend pas une - // liste triée avec List, tri dans le getter - Collections.sort(extraits, new ExtraitsOfExtractionComp()); - return extraits; + // comme "@Sort(type = SortType.COMPARATOR, comparator = ExtraitsOfExtractionComp.class)" ne rend pas une + // liste triée avec List, tri dans le getter + Collections.sort(extraits, new ExtraitsOfExtractionComp()); + return extraits; } /** @@ -170,7 +169,7 @@ * @return idExtraction */ public Integer getIdExtraction() { - return idExtraction; + return idExtraction; } /** @@ -178,7 +177,7 @@ * @param idExtraction idExtraction */ public void setIdExtraction(Integer idExtraction) { - this.idExtraction = idExtraction; + this.idExtraction = idExtraction; } /** @@ -186,7 +185,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -194,7 +193,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -202,7 +201,7 @@ * @return manipulateur */ public Personne getManipulateur() { - return manipulateur; + return manipulateur; } /** @@ -210,7 +209,7 @@ * @param manipulateur manipulateur */ public void setManipulateur(Personne manipulateur) { - this.manipulateur = manipulateur; + this.manipulateur = manipulateur; } /** @@ -218,7 +217,7 @@ * @return methode */ public MethodeExtraction getMethode() { - return methode; + return methode; } /** @@ -226,7 +225,7 @@ * @param methode methode */ public void setMethode(MethodeExtraction methode) { - this.methode = methode; + this.methode = methode; } /** @@ -234,7 +233,7 @@ * @return date */ public Date getDate() { - return date; + return date; } /** @@ -242,7 +241,7 @@ * @param date date */ public void setDate(Date date) { - this.date = date; + this.date = date; } /** @@ -250,7 +249,7 @@ * @return lot */ public Lot getLot() { - return lot; + return lot; } /** @@ -258,7 +257,7 @@ * @param lot lot */ public void setLot(Lot lot) { - this.lot = lot; + this.lot = lot; } /** @@ -266,7 +265,7 @@ * @return masseDepart */ public BigDecimal getMasseDepart() { - return masseDepart; + return masseDepart; } /** @@ -274,7 +273,7 @@ * @param masseDepart masseDepart */ public void setMasseDepart(BigDecimal masseDepart) { - this.masseDepart = masseDepart; + this.masseDepart = masseDepart; } /** @@ -282,7 +281,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -290,7 +289,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -298,7 +297,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -306,7 +305,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -314,7 +313,7 @@ * @return extraits */ public List<Extrait> getExtraits() { - return extraits; + return extraits; } /** @@ -322,7 +321,7 @@ * @param extraits extraits */ public void setExtraits(List<Extrait> extraits) { - this.extraits = extraits; + this.extraits = extraits; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extrait.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extrait.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Extrait.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,7 +56,7 @@ * Constructor */ public Extrait() { - super(); + super(); } /** @@ -64,35 +64,35 @@ * @return le résultat ou null si les valeurs actuelles ne donnent pas un résultat cohérent */ public Float getRendement() { - if (getExtraction() != null && getExtraction().getMasseDepart() != null - && getExtraction().getMasseDepart().floatValue() != 0f && getMasseObtenue() != null) { - Float rendement = getMasseObtenue().floatValue() / getExtraction().getMasseDepart().floatValue(); - if (rendement <= 1f && rendement >= 0) { - return rendement; - } - } - return null; + if (getExtraction() != null && getExtraction().getMasseDepart() != null + && getExtraction().getMasseDepart().floatValue() != 0f && getMasseObtenue() != null) { + Float rendement = getMasseObtenue().floatValue() / getExtraction().getMasseDepart().floatValue(); + if (rendement <= 1f && rendement >= 0) { + return rendement; + } + } + return null; } /** {@inheritDoc} */ @Override public boolean isExtrait() { - return true; + return true; } /** {@inheritDoc} */ @Override public boolean isFraction() { - return false; + return false; } /** {@inheritDoc} */ @Override public Extrait clone() throws CloneNotSupportedException { - Extrait clone = (Extrait) super.clone(); - clone.typeExtrait = typeExtrait; - clone.extraction = extraction; - return clone; + Extrait clone = (Extrait) super.clone(); + clone.typeExtrait = typeExtrait; + clone.extraction = extraction; + return clone; } /** @@ -100,7 +100,7 @@ * @return typeExtrait */ public TypeExtrait getTypeExtrait() { - return typeExtrait; + return typeExtrait; } /** @@ -108,7 +108,7 @@ * @param typeExtrait typeExtrait */ public void setTypeExtrait(TypeExtrait typeExtrait) { - this.typeExtrait = typeExtrait; + this.typeExtrait = typeExtrait; } /** @@ -116,7 +116,7 @@ * @return extraction */ public Extraction getExtraction() { - return extraction; + return extraction; } /** @@ -124,7 +124,7 @@ * @param extraction extraction */ public void setExtraction(Extraction extraction) { - this.extraction = extraction; + this.extraction = extraction; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Fraction.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Fraction.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Fraction.java 2013-02-18 07:27:17 UTC (rev 119) @@ -61,7 +61,7 @@ * Constructor */ public Fraction() { - super(); + super(); } /** @@ -69,35 +69,35 @@ * @return le résultat ou null si les valeurs actuelles ne donnent pas un résultat cohérent */ public Float getRendement() { - if (getPurification() != null && getPurification().getMasseDepart() != null - && getPurification().getMasseDepart().floatValue() != 0f && getMasseObtenue() != null) { - Float rendement = getMasseObtenue().floatValue() / getPurification().getMasseDepart().floatValue(); - if (rendement <= 1f && rendement >= 0) { - return rendement; - } - } - return null; + if (getPurification() != null && getPurification().getMasseDepart() != null + && getPurification().getMasseDepart().floatValue() != 0f && getMasseObtenue() != null) { + Float rendement = getMasseObtenue().floatValue() / getPurification().getMasseDepart().floatValue(); + if (rendement <= 1f && rendement >= 0) { + return rendement; + } + } + return null; } /** {@inheritDoc} */ @Override public boolean isExtrait() { - return false; + return false; } /** {@inheritDoc} */ @Override public boolean isFraction() { - return true; + return true; } /** {@inheritDoc} */ @Override public Fraction clone() throws CloneNotSupportedException { - Fraction clone = (Fraction) super.clone(); - clone.indice = indice; - clone.purification = purification; - return clone; + Fraction clone = (Fraction) super.clone(); + clone.indice = indice; + clone.purification = purification; + return clone; } /** @@ -105,7 +105,7 @@ * @return indice */ public String getIndice() { - return indice; + return indice; } /** @@ -113,7 +113,7 @@ * @param indice indice */ public void setIndice(String indice) { - this.indice = indice; + this.indice = indice; } /** @@ -121,7 +121,7 @@ * @return purification */ public Purification getPurification() { - return purification; + return purification; } /** @@ -129,7 +129,7 @@ * @param purification purification */ public void setPurification(Purification purification) { - this.purification = purification; + this.purification = purification; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Groupe.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Groupe.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Groupe.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,7 +56,8 @@ /** Description */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Groupe */ @@ -84,15 +85,15 @@ * Constructeur */ public Groupe() { - utilisateurs = new ArrayList<Utilisateur>(); - campagnesDroits = new ArrayList<CampagneGroupeDroits>(); - lotsDroits = new ArrayList<LotGroupeDroits>(); + utilisateurs = new ArrayList<Utilisateur>(); + campagnesDroits = new ArrayList<CampagneGroupeDroits>(); + lotsDroits = new ArrayList<LotGroupeDroits>(); } /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** @@ -100,7 +101,7 @@ * @return campagnesDroits */ public List<CampagneGroupeDroits> getCampagnesDroits() { - return campagnesDroits; + return campagnesDroits; } /** @@ -108,7 +109,7 @@ * @param campagnesDroits campagnesDroits */ public void setCampagnesDroits(List<CampagneGroupeDroits> campagnesDroits) { - this.campagnesDroits = campagnesDroits; + this.campagnesDroits = campagnesDroits; } /** @@ -116,7 +117,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -124,7 +125,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -132,7 +133,7 @@ * @return idGroupe */ public Integer getIdGroupe() { - return idGroupe; + return idGroupe; } /** @@ -140,7 +141,7 @@ * @param idGroupe idGroupe */ public void setIdGroupe(Integer idGroupe) { - this.idGroupe = idGroupe; + this.idGroupe = idGroupe; } /** @@ -148,7 +149,7 @@ * @return lotsDroits */ public List<LotGroupeDroits> getLotsDroits() { - return lotsDroits; + return lotsDroits; } /** @@ -156,7 +157,7 @@ * @param lotsDroits lotsDroits */ public void setLotsDroits(List<LotGroupeDroits> lotsDroits) { - this.lotsDroits = lotsDroits; + this.lotsDroits = lotsDroits; } /** @@ -164,7 +165,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -172,7 +173,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -180,7 +181,7 @@ * @return utilisateurs */ public List<Utilisateur> getUtilisateurs() { - return utilisateurs; + return utilisateurs; } /** @@ -188,7 +189,7 @@ * @param utilisateurs utilisateurs */ public void setUtilisateurs(List<Utilisateur> utilisateurs) { - this.utilisateurs = utilisateurs; + this.utilisateurs = utilisateurs; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Lot.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Lot.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Lot.java 2013-02-18 07:27:17 UTC (rev 119) @@ -70,9 +70,7 @@ @Table @Indexed @Embeddable -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Lot", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Lot", impl = UtilisateurSearchFilter.class) }) public class Lot extends AbstractModel implements Comparable<Lot> { /** ID */ @@ -84,18 +82,19 @@ @Column(unique = true) @NotEmpty @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Campagne */ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Campagne campagne; /** complement */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** createur */ @@ -151,13 +150,13 @@ /** Spécimen source */ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Specimen specimenRef; /** Station */ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Station station; /** Extractions provenants du lot */ @@ -169,21 +168,21 @@ * Constructeur */ public Lot() { - personnesDroits = new ArrayList<LotPersonneDroits>(); - groupesDroits = new ArrayList<LotGroupeDroits>(); - extractions = new ArrayList<Extraction>(); + personnesDroits = new ArrayList<LotPersonneDroits>(); + groupesDroits = new ArrayList<LotGroupeDroits>(); + extractions = new ArrayList<Extraction>(); } /** {@inheritDoc} */ @Override public String toString() { - return ref; + return ref; } /** {@inheritDoc} */ @Override public int compareTo(Lot lot) { - return new BeanComparator("ref").compare(this, lot); + return new BeanComparator("ref").compare(this, lot); } /** @@ -191,7 +190,7 @@ * @return campagne */ public Campagne getCampagne() { - return campagne; + return campagne; } /** @@ -199,7 +198,7 @@ * @param campagne campagne */ public void setCampagne(Campagne campagne) { - this.campagne = campagne; + this.campagne = campagne; } /** @@ -207,7 +206,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -215,7 +214,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -223,7 +222,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -231,7 +230,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -239,7 +238,7 @@ * @return dateRecolte */ public Date getDateRecolte() { - return dateRecolte; + return dateRecolte; } /** @@ -247,7 +246,7 @@ * @param dateRecolte dateRecolte */ public void setDateRecolte(Date dateRecolte) { - this.dateRecolte = dateRecolte; + this.dateRecolte = dateRecolte; } /** @@ -255,7 +254,7 @@ * @return echantillonColl */ public Boolean getEchantillonColl() { - return echantillonColl; + return echantillonColl; } /** @@ -263,7 +262,7 @@ * @param echantillonColl echantillonColl */ public void setEchantillonColl(Boolean echantillonColl) { - this.echantillonColl = echantillonColl; + this.echantillonColl = echantillonColl; } /** @@ -271,7 +270,7 @@ * @return echantillonIdent */ public Boolean getEchantillonIdent() { - return echantillonIdent; + return echantillonIdent; } /** @@ -279,7 +278,7 @@ * @param echantillonIdent echantillonIdent */ public void setEchantillonIdent(Boolean echantillonIdent) { - this.echantillonIdent = echantillonIdent; + this.echantillonIdent = echantillonIdent; } /** @@ -287,7 +286,7 @@ * @return echantillonPhylo */ public Boolean getEchantillonPhylo() { - return echantillonPhylo; + return echantillonPhylo; } /** @@ -295,7 +294,7 @@ * @param echantillonPhylo echantillonPhylo */ public void setEchantillonPhylo(Boolean echantillonPhylo) { - this.echantillonPhylo = echantillonPhylo; + this.echantillonPhylo = echantillonPhylo; } /** @@ -303,7 +302,7 @@ * @return groupesDroits */ public List<LotGroupeDroits> getGroupesDroits() { - return groupesDroits; + return groupesDroits; } /** @@ -311,7 +310,7 @@ * @param groupesDroits groupesDroits */ public void setGroupesDroits(List<LotGroupeDroits> groupesDroits) { - this.groupesDroits = groupesDroits; + this.groupesDroits = groupesDroits; } /** @@ -319,7 +318,7 @@ * @return idLot */ public Integer getIdLot() { - return idLot; + return idLot; } /** @@ -327,7 +326,7 @@ * @param idLot idLot */ public void setIdLot(Integer idLot) { - this.idLot = idLot; + this.idLot = idLot; } /** @@ -335,7 +334,7 @@ * @return masseFraiche */ public BigDecimal getMasseFraiche() { - return masseFraiche; + return masseFraiche; } /** @@ -343,7 +342,7 @@ * @param masseFraiche masseFraiche */ public void setMasseFraiche(BigDecimal masseFraiche) { - this.masseFraiche = masseFraiche; + this.masseFraiche = masseFraiche; } /** @@ -351,7 +350,7 @@ * @return masseSeche */ public BigDecimal getMasseSeche() { - return masseSeche; + return masseSeche; } /** @@ -359,7 +358,7 @@ * @param masseSeche masseSeche */ public void setMasseSeche(BigDecimal masseSeche) { - this.masseSeche = masseSeche; + this.masseSeche = masseSeche; } /** @@ -367,7 +366,7 @@ * @return partie */ public Partie getPartie() { - return partie; + return partie; } /** @@ -375,7 +374,7 @@ * @param partie partie */ public void setPartie(Partie partie) { - this.partie = partie; + this.partie = partie; } /** @@ -383,7 +382,7 @@ * @return personnesDroits */ public List<LotPersonneDroits> getPersonnesDroits() { - return personnesDroits; + return personnesDroits; } /** @@ -391,7 +390,7 @@ * @param personnesDroits personnesDroits */ public void setPersonnesDroits(List<LotPersonneDroits> personnesDroits) { - this.personnesDroits = personnesDroits; + this.personnesDroits = personnesDroits; } /** @@ -399,7 +398,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -407,7 +406,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -415,7 +414,7 @@ * @return specimenRef */ public Specimen getSpecimenRef() { - return specimenRef; + return specimenRef; } /** @@ -423,7 +422,7 @@ * @param specimenRef specimenRef */ public void setSpecimenRef(Specimen specimenRef) { - this.specimenRef = specimenRef; + this.specimenRef = specimenRef; } /** @@ -431,7 +430,7 @@ * @return station */ public Station getStation() { - return station; + return station; } /** @@ -439,7 +438,7 @@ * @param station station */ public void setStation(Station station) { - this.station = station; + this.station = station; } /** @@ -447,7 +446,7 @@ * @return extractions */ public List<Extraction> getExtractions() { - return extractions; + return extractions; } /** @@ -455,6 +454,6 @@ * @param extractions extractions */ public void setExtractions(List<Extraction> extractions) { - this.extractions = extractions; + this.extractions = extractions; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotGroupeDroits.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotGroupeDroits.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotGroupeDroits.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,8 +51,8 @@ * Constructeur */ public LotGroupeDroits() { - droits = new Droits(); - id = new CompositeId<Lot, Groupe>(); + droits = new Droits(); + id = new CompositeId<Lot, Groupe>(); } /** @@ -60,7 +60,7 @@ * @return droits */ public Droits getDroits() { - return droits; + return droits; } /** @@ -68,7 +68,7 @@ * @param droits droits */ public void setDroits(Droits droits) { - this.droits = droits; + this.droits = droits; } /** @@ -76,7 +76,7 @@ * @return id */ public CompositeId<Lot, Groupe> getId() { - return id; + return id; } /** @@ -84,7 +84,7 @@ * @param id id */ public void setId(CompositeId<Lot, Groupe> id) { - this.id = id; + this.id = id; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotPersonneDroits.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotPersonneDroits.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/LotPersonneDroits.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,17 +51,17 @@ * Constructeur */ public LotPersonneDroits() { - droits = new Droits(); - id = new CompositeId<Lot, Personne>(); + droits = new Droits(); + id = new CompositeId<Lot, Personne>(); } /** {@inheritDoc} */ @Override public final LotPersonneDroits clone() throws CloneNotSupportedException { - LotPersonneDroits clone = new LotPersonneDroits(); - clone.id = id.clone(); - clone.droits = droits.clone(); - return clone; + LotPersonneDroits clone = new LotPersonneDroits(); + clone.id = id.clone(); + clone.droits = droits.clone(); + return clone; } /** @@ -69,7 +69,7 @@ * @return droits */ public Droits getDroits() { - return droits; + return droits; } /** @@ -77,7 +77,7 @@ * @param droits droits */ public void setDroits(Droits droits) { - this.droits = droits; + this.droits = droits; } /** @@ -85,7 +85,7 @@ * @return id */ public CompositeId<Lot, Personne> getId() { - return id; + return id; } /** @@ -93,7 +93,7 @@ * @param id id */ public void setId(CompositeId<Lot, Personne> id) { - this.id = id; + this.id = id; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeExtraction.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeExtraction.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeExtraction.java 2013-02-18 07:27:17 UTC (rev 119) @@ -65,31 +65,32 @@ /** Description de la méthode */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Types extraits définis en sortie pour la méthode */ @OneToMany(mappedBy = "methodeExtraction", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private List<TypeExtrait> typesEnSortie; /** * Constructor */ public MethodeExtraction() { - typesEnSortie = new ArrayList<TypeExtrait>(); + typesEnSortie = new ArrayList<TypeExtrait>(); } /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(MethodeExtraction methodeExtraction) { - return new BeanComparator("nom").compare(this, methodeExtraction); + return new BeanComparator("nom").compare(this, methodeExtraction); } /** @@ -97,8 +98,8 @@ * @return Les types d'extraits */ public List<TypeExtrait> getSortedTypesEnSortie() { - Collections.sort(typesEnSortie); - return typesEnSortie; + Collections.sort(typesEnSortie); + return typesEnSortie; } /** @@ -106,7 +107,7 @@ * @return idMethodeExtraction */ public Integer getIdMethodeExtraction() { - return idMethodeExtraction; + return idMethodeExtraction; } /** @@ -114,7 +115,7 @@ * @param idMethodeExtraction idMethodeExtraction */ public void setIdMethodeExtraction(Integer idMethodeExtraction) { - this.idMethodeExtraction = idMethodeExtraction; + this.idMethodeExtraction = idMethodeExtraction; } /** @@ -122,7 +123,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -130,7 +131,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -138,7 +139,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -146,7 +147,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -154,7 +155,7 @@ * @return typesEnSortie */ public List<TypeExtrait> getTypesEnSortie() { - return typesEnSortie; + return typesEnSortie; } /** @@ -162,7 +163,7 @@ * @param typesEnSortie typesEnSortie */ public void setTypesEnSortie(List<TypeExtrait> typesEnSortie) { - this.typesEnSortie = typesEnSortie; + this.typesEnSortie = typesEnSortie; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodePurification.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodePurification.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodePurification.java 2013-02-18 07:27:17 UTC (rev 119) @@ -65,12 +65,13 @@ /** Description de la méthode */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Types extraits définis en sortie pour la méthode */ @OneToMany(mappedBy = "methodePurification", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) @OrderBy("index") private List<ParamMethoPuri> parametres; @@ -78,19 +79,19 @@ * Constructor */ public MethodePurification() { - parametres = new ArrayList<ParamMethoPuri>(); + parametres = new ArrayList<ParamMethoPuri>(); } /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(MethodePurification methodePurification) { - return new BeanComparator("nom").compare(this, methodePurification); + return new BeanComparator("nom").compare(this, methodePurification); } /** @@ -98,8 +99,8 @@ * @return Les paramètres */ public List<ParamMethoPuri> getSortedParametres() { - Collections.sort(parametres); - return parametres; + Collections.sort(parametres); + return parametres; } /** @@ -107,7 +108,7 @@ * @return idMethodePurification */ public Integer getIdMethodePurification() { - return idMethodePurification; + return idMethodePurification; } /** @@ -115,7 +116,7 @@ * @param idMethodePurification idMethodePurification */ public void setIdMethodePurification(Integer idMethodePurification) { - this.idMethodePurification = idMethodePurification; + this.idMethodePurification = idMethodePurification; } /** @@ -123,7 +124,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -131,7 +132,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -139,7 +140,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -147,7 +148,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -155,7 +156,7 @@ * @return parametres */ public List<ParamMethoPuri> getParametres() { - return parametres; + return parametres; } /** @@ -163,7 +164,7 @@ * @param parametres parametres */ public void setParametres(List<ParamMethoPuri> parametres) { - this.parametres = parametres; + this.parametres = parametres; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeTestBio.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeTestBio.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MethodeTestBio.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,14 +57,14 @@ @Length(max = LENGTH_MEDIUM_TEXT) @Column(unique = true) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String nom; /** Cible pour un test (acronyme du nom de méthode) */ @Length(max = LENGTH_MEDIUM_TEXT) @Column(unique = true) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String cible; /** Domaine de recherche pour le test */ @@ -75,7 +75,8 @@ /** Description de la méthode */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Valeur mesurée pour la méthode */ @@ -95,13 +96,13 @@ /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(MethodeTestBio methodeTest) { - return new BeanComparator("nom").compare(this, methodeTest); + return new BeanComparator("nom").compare(this, methodeTest); } /** @@ -109,7 +110,7 @@ * @return idMethodeTest */ public Integer getIdMethodeTest() { - return idMethodeTest; + return idMethodeTest; } /** @@ -117,7 +118,7 @@ * @param idMethodeTest idMethodeTest */ public void setIdMethodeTest(Integer idMethodeTest) { - this.idMethodeTest = idMethodeTest; + this.idMethodeTest = idMethodeTest; } /** @@ -125,7 +126,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -133,7 +134,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -141,7 +142,7 @@ * @return cible */ public String getCible() { - return cible; + return cible; } /** @@ -149,7 +150,7 @@ * @param cible cible */ public void setCible(String cible) { - this.cible = cible; + this.cible = cible; } /** @@ -157,7 +158,7 @@ * @return domaine */ public String getDomaine() { - return domaine; + return domaine; } /** @@ -165,7 +166,7 @@ * @param domaine domaine */ public void setDomaine(String domaine) { - this.domaine = domaine; + this.domaine = domaine; } /** @@ -173,7 +174,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -181,7 +182,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -189,7 +190,7 @@ * @return valeurMesuree */ public String getValeurMesuree() { - return valeurMesuree; + return valeurMesuree; } /** @@ -197,7 +198,7 @@ * @param valeurMesuree valeurMesuree */ public void setValeurMesuree(String valeurMesuree) { - this.valeurMesuree = valeurMesuree; + this.valeurMesuree = valeurMesuree; } /** @@ -205,7 +206,7 @@ * @return uniteResultat */ public String getUniteResultat() { - return uniteResultat; + return uniteResultat; } /** @@ -213,7 +214,7 @@ * @param uniteResultat uniteResultat */ public void setUniteResultat(String uniteResultat) { - this.uniteResultat = uniteResultat; + this.uniteResultat = uniteResultat; } /** @@ -221,7 +222,7 @@ * @return critereActivite */ public String getCritereActivite() { - return critereActivite; + return critereActivite; } /** @@ -229,7 +230,7 @@ * @param critereActivite critereActivite */ public void setCritereActivite(String critereActivite) { - this.critereActivite = critereActivite; + this.critereActivite = critereActivite; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Molecule.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Molecule.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Molecule.java 2013-02-18 07:27:17 UTC (rev 119) @@ -66,35 +66,34 @@ */ @Entity @Indexed -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Molecule", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Molecule", impl = UtilisateurSearchFilter.class) }) public class Molecule extends AbstractModel implements DocumentAttachable { /** ID */ @Id - @GeneratedValue(generator="molecule_sequence_gen") - @SequenceGenerator(name="molecule_sequence_gen", sequenceName="molecule_sequence") + @GeneratedValue(generator = "molecule_sequence_gen") + @SequenceGenerator(name = "molecule_sequence_gen", sequenceName = "molecule_sequence") private Integer idMolecule; /** Nom commun */ @Length(max = LENGTH_LONG_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String nomCommun; /** Famille chimique */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String familleChimique; /** Famille developpée */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String formuleDevMol; /** Nom IUPAC */ @Length(max = LENGTH_BIG_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String nomIupca; /** Formule brute */ @@ -113,22 +112,24 @@ /** Campagne. */ @ManyToOne(fetch = FetchType.EAGER) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Campagne campagne; /** Identifiee par. */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String identifieePar; /** Publication d'origine */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String publiOrigine; /** Complement */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Créateur */ @@ -139,21 +140,21 @@ /** Produit utilisé obtenir le résultat */ @OneToMany(mappedBy = "molecule", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private List<MoleculeProvenance> provenances; /** Liste des documents attachés. */ @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true) - @JoinColumn(name="molecule") - @Cascade({ CascadeType.SAVE_UPDATE }) + @JoinColumn(name = "molecule") + @Cascade( { CascadeType.SAVE_UPDATE }) private List<Document> documents; /** * Constructor. */ public Molecule() { - provenances = new ArrayList<MoleculeProvenance>(); - documents = new ArrayList<Document>(); + provenances = new ArrayList<MoleculeProvenance>(); + documents = new ArrayList<Document>(); } /** @@ -162,7 +163,7 @@ * @return the idMolecule */ public Integer getIdMolecule() { - return idMolecule; + return idMolecule; } /** @@ -171,7 +172,7 @@ * @param idMolecule the idMolecule to set */ public void setIdMolecule(Integer idMolecule) { - this.idMolecule = idMolecule; + this.idMolecule = idMolecule; } /** @@ -180,7 +181,7 @@ * @return the nomCommun */ public String getNomCommun() { - return nomCommun; + return nomCommun; } /** @@ -189,7 +190,7 @@ * @param nomCommun the nomCommun to set */ public void setNomCommun(String nomCommun) { - this.nomCommun = nomCommun; + this.nomCommun = nomCommun; } /** @@ -198,7 +199,7 @@ * @return the familleChimique */ public String getFamilleChimique() { - return familleChimique; + return familleChimique; } /** @@ -207,7 +208,7 @@ * @param familleChimique the familleChimique to set */ public void setFamilleChimique(String familleChimique) { - this.familleChimique = familleChimique; + this.familleChimique = familleChimique; } /** @@ -216,7 +217,7 @@ * @return the formuleDevMol */ public String getFormuleDevMol() { - return formuleDevMol; + return formuleDevMol; } /** @@ -225,7 +226,7 @@ * @param formuleDevMol the formuleDevMol to set */ public void setFormuleDevMol(String formuleDevMol) { - this.formuleDevMol = formuleDevMol; + this.formuleDevMol = formuleDevMol; } /** @@ -234,7 +235,7 @@ * @return the nomIupca */ public String getNomIupca() { - return nomIupca; + return nomIupca; } /** @@ -243,7 +244,7 @@ * @param nomIupca the nomIupca to set */ public void setNomIupca(String nomIupca) { - this.nomIupca = nomIupca; + this.nomIupca = nomIupca; } /** @@ -252,7 +253,7 @@ * @return the formuleBrute */ public String getFormuleBrute() { - return formuleBrute; + return formuleBrute; } /** @@ -261,7 +262,7 @@ * @param formuleBrute the formuleBrute to set */ public void setFormuleBrute(String formuleBrute) { - this.formuleBrute = formuleBrute; + this.formuleBrute = formuleBrute; } /** @@ -270,7 +271,7 @@ * @return the masseMolaire */ public BigDecimal getMasseMolaire() { - return masseMolaire; + return masseMolaire; } /** @@ -279,7 +280,7 @@ * @param masseMolaire the masseMolaire to set */ public void setMasseMolaire(BigDecimal masseMolaire) { - this.masseMolaire = masseMolaire; + this.masseMolaire = masseMolaire; } /** @@ -288,7 +289,7 @@ * @return the nouvMolecul */ public boolean isNouvMolecul() { - return nouvMolecul; + return nouvMolecul; } /** @@ -297,7 +298,7 @@ * @param nouvMolecul the nouvMolecul to set */ public void setNouvMolecul(boolean nouvMolecul) { - this.nouvMolecul = nouvMolecul; + this.nouvMolecul = nouvMolecul; } /** @@ -306,7 +307,7 @@ * @return the campagne */ public Campagne getCampagne() { - return campagne; + return campagne; } /** @@ -315,7 +316,7 @@ * @param campagne the campagne to set */ public void setCampagne(Campagne campagne) { - this.campagne = campagne; + this.campagne = campagne; } /** @@ -324,7 +325,7 @@ * @return the identifieePar */ public String getIdentifieePar() { - return identifieePar; + return identifieePar; } /** @@ -333,7 +334,7 @@ * @param identifieePar the identifieePar to set */ public void setIdentifieePar(String identifieePar) { - this.identifieePar = identifieePar; + this.identifieePar = identifieePar; } /** @@ -342,7 +343,7 @@ * @return the publiOrigine */ public String getPubliOrigine() { - return publiOrigine; + return publiOrigine; } /** @@ -351,7 +352,7 @@ * @param publiOrigine the publiOrigine to set */ public void setPubliOrigine(String publiOrigine) { - this.publiOrigine = publiOrigine; + this.publiOrigine = publiOrigine; } /** @@ -360,7 +361,7 @@ * @return the complement */ public String getComplement() { - return complement; + return complement; } /** @@ -369,7 +370,7 @@ * @param complement the complement to set */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -378,7 +379,7 @@ * @return the createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -387,7 +388,7 @@ * @param createur the createur to set */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -396,7 +397,7 @@ * @return the provenances */ public List<MoleculeProvenance> getProvenances() { - return provenances; + return provenances; } /** @@ -405,12 +406,12 @@ * @param provenances the provenances to set */ public void setProvenances(List<MoleculeProvenance> provenances) { - this.provenances = provenances; + this.provenances = provenances; } /** {@inheritDoc} */ public List<Document> getDocuments() { - return documents; + return documents; } /** @@ -419,18 +420,18 @@ * @param documents the documents to set */ public void setDocuments(List<Document> documents) { - this.documents = documents; + this.documents = documents; } /** {@inheritDoc} */ @Override public void addDocument(Document document) { - documents.add(document); + documents.add(document); } /** {@inheritDoc} */ @Override public void removeDocument(Document document) { - documents.remove(document); + documents.remove(document); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MoleculeProvenance.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MoleculeProvenance.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/MoleculeProvenance.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,19 +49,19 @@ @Id @GeneratedValue private Integer id; - + /** Concentration/masse **/ @Min(value = 0) @Max(value = 100) @Column(precision = DataContext.DECIMAL_PRECISION, scale = DataContext.DECIMAL_SCALE) @NotNull private BigDecimal pourcentage; - + /** Molecule dont fait partie la provenance */ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) private Molecule molecule; - + /** Produit sur lequel porte la provenance **/ @NotNull @ManyToOne(fetch = FetchType.EAGER, optional = false) @@ -73,7 +73,7 @@ * @return the id */ public Integer getId() { - return id; + return id; } /** @@ -82,7 +82,7 @@ * @param id the id to set */ public void setId(Integer id) { - this.id = id; + this.id = id; } /** @@ -91,7 +91,7 @@ * @return the pourcentage */ public BigDecimal getPourcentage() { - return pourcentage; + return pourcentage; } /** @@ -100,7 +100,7 @@ * @param pourcentage the pourcentage to set */ public void setPourcentage(BigDecimal pourcentage) { - this.pourcentage = pourcentage; + this.pourcentage = pourcentage; } /** @@ -109,7 +109,7 @@ * @return the molecule */ public Molecule getMolecule() { - return molecule; + return molecule; } /** @@ -118,7 +118,7 @@ * @param molecule the molecule to set */ public void setMolecule(Molecule molecule) { - this.molecule = molecule; + this.molecule = molecule; } /** @@ -127,7 +127,7 @@ * @return the produit */ public Produit getProduit() { - return produit; + return produit; } /** @@ -136,17 +136,17 @@ * @param produit the produit to set */ public void setProduit(Produit produit) { - this.produit = produit; + this.produit = produit; } /** {@inheritDoc} */ @Override public MoleculeProvenance clone() throws CloneNotSupportedException { - MoleculeProvenance clone = (MoleculeProvenance) super.clone(); - clone.id = id; - clone.pourcentage = pourcentage; - clone.molecule = molecule; - clone.produit = produit; - return clone; + MoleculeProvenance clone = (MoleculeProvenance) super.clone(); + clone.id = id; + clone.pourcentage = pourcentage; + clone.molecule = molecule; + clone.produit = produit; + return clone; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuri.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuri.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuri.java 2013-02-18 07:27:17 UTC (rev 119) @@ -65,7 +65,8 @@ /** Description du type d'extrait */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Méthode d'extraction pour laquelle est défini le type d'extrait */ @@ -76,23 +77,23 @@ /** {@inheritDoc} */ @Override public ParamMethoPuri clone() throws CloneNotSupportedException { - ParamMethoPuri clone = (ParamMethoPuri) super.clone(); - clone.idParamMethoPuri = idParamMethoPuri; - clone.nom = nom; - clone.description = description; - return clone; + ParamMethoPuri clone = (ParamMethoPuri) super.clone(); + clone.idParamMethoPuri = idParamMethoPuri; + clone.nom = nom; + clone.description = description; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return this.nom; + return this.nom; } /** {@inheritDoc} */ @Override public int compareTo(ParamMethoPuri paramMethoPuri) { - return new BeanComparator("index").compare(this, paramMethoPuri); + return new BeanComparator("index").compare(this, paramMethoPuri); } /** @@ -100,7 +101,7 @@ * @return idParamMethoPuri */ public Integer getIdParamMethoPuri() { - return idParamMethoPuri; + return idParamMethoPuri; } /** @@ -108,7 +109,7 @@ * @param idParamMethoPuri idParamMethoPuri */ public void setIdParamMethoPuri(Integer idParamMethoPuri) { - this.idParamMethoPuri = idParamMethoPuri; + this.idParamMethoPuri = idParamMethoPuri; } /** @@ -116,7 +117,7 @@ * @return index */ public Integer getIndex() { - return index; + return index; } /** @@ -124,7 +125,7 @@ * @param index index */ public void setIndex(Integer index) { - this.index = index; + this.index = index; } /** @@ -132,7 +133,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -140,7 +141,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -148,7 +149,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -156,7 +157,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -164,7 +165,7 @@ * @return methodePurification */ public MethodePurification getMethodePurification() { - return methodePurification; + return methodePurification; } /** @@ -172,7 +173,7 @@ * @param methodePurification methodePurification */ public void setMethodePurification(MethodePurification methodePurification) { - this.methodePurification = methodePurification; + this.methodePurification = methodePurification; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuriEffectif.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuriEffectif.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ParamMethoPuriEffectif.java 2013-02-18 07:27:17 UTC (rev 119) @@ -65,23 +65,23 @@ * Constructor */ public ParamMethoPuriEffectif() { - // + // } /** {@inheritDoc} */ @Override public ParamMethoPuriEffectif clone() throws CloneNotSupportedException { - ParamMethoPuriEffectif clone = (ParamMethoPuriEffectif) super.clone(); - clone.idParamMethoPuriEffectif = idParamMethoPuriEffectif; - clone.param = param; - clone.valeur = valeur; - return clone; + ParamMethoPuriEffectif clone = (ParamMethoPuriEffectif) super.clone(); + clone.idParamMethoPuriEffectif = idParamMethoPuriEffectif; + clone.param = param; + clone.valeur = valeur; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return param + " : " + valeur; + return param + " : " + valeur; } /** @@ -89,7 +89,7 @@ * @return idParamMethoPuriEffectif */ public Integer getIdParamMethoPuriEffectif() { - return idParamMethoPuriEffectif; + return idParamMethoPuriEffectif; } /** @@ -97,7 +97,7 @@ * @param idParamMethoPuriEffectif idParamMethoPuriEffectif */ public void setIdParamMethoPuriEffectif(Integer idParamMethoPuriEffectif) { - this.idParamMethoPuriEffectif = idParamMethoPuriEffectif; + this.idParamMethoPuriEffectif = idParamMethoPuriEffectif; } /** @@ -105,7 +105,7 @@ * @return param */ public ParamMethoPuri getParam() { - return param; + return param; } /** @@ -113,7 +113,7 @@ * @param param param */ public void setParam(ParamMethoPuri param) { - this.param = param; + this.param = param; } /** @@ -121,7 +121,7 @@ * @return valeur */ public String getValeur() { - return valeur; + return valeur; } /** @@ -129,7 +129,7 @@ * @param valeur valeur */ public void setValeur(String valeur) { - this.valeur = valeur; + this.valeur = valeur; } /** @@ -137,7 +137,7 @@ * @return purification */ public Purification getPurification() { - return purification; + return purification; } /** @@ -145,7 +145,7 @@ * @param purification purification */ public void setPurification(Purification purification) { - this.purification = purification; + this.purification = purification; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Partie.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Partie.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Partie.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,13 +57,13 @@ /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(Partie partie) { - return new BeanComparator("nom").compare(this, partie); + return new BeanComparator("nom").compare(this, partie); } /** @@ -71,7 +71,7 @@ * @return idPartie */ public Integer getIdPartie() { - return idPartie; + return idPartie; } /** @@ -79,7 +79,7 @@ * @param idPartie idPartie */ public void setIdPartie(Integer idPartie) { - this.idPartie = idPartie; + this.idPartie = idPartie; } /** @@ -87,7 +87,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -95,7 +95,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Personne.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Personne.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Personne.java 2013-02-18 07:27:17 UTC (rev 119) @@ -72,7 +72,8 @@ /** Adresse postale */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String adressePostale; /** Campagnes créées */ @@ -84,7 +85,7 @@ @NotNull @OneToMany(mappedBy = "id.pk2", fetch = FetchType.LAZY, orphanRemoval = true) @MapKey(name = "id.pk1") - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private Map<Campagne, CampagnePersonneDroits> campagnesDroits; /** Campagnes participées */ @@ -128,7 +129,7 @@ @NotNull @OneToMany(mappedBy = "id.pk2", fetch = FetchType.LAZY, orphanRemoval = true) @MapKey(name = "id.pk1") - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private Map<Lot, LotPersonneDroits> lotsDroits; /** Nom */ @@ -184,31 +185,31 @@ * Constructeur */ public Personne() { - campagnesCreees = new ArrayList<Campagne>(); - campagnesParticipees = new ArrayList<CampagnePersonneParticipant>(); - campagnesDroits = new HashMap<Campagne, CampagnePersonneDroits>(); - lotsCrees = new ArrayList<Lot>(); - lotsDroits = new HashMap<Lot, LotPersonneDroits>(); - stationsCrees = new ArrayList<Station>(); - specimensCrees = new ArrayList<Specimen>(); - extractionsCrees = new ArrayList<Extraction>(); - purificationsCrees = new ArrayList<Purification>(); - testsBioCrees = new ArrayList<TestBio>(); + campagnesCreees = new ArrayList<Campagne>(); + campagnesParticipees = new ArrayList<CampagnePersonneParticipant>(); + campagnesDroits = new HashMap<Campagne, CampagnePersonneDroits>(); + lotsCrees = new ArrayList<Lot>(); + lotsDroits = new HashMap<Lot, LotPersonneDroits>(); + stationsCrees = new ArrayList<Station>(); + specimensCrees = new ArrayList<Specimen>(); + extractionsCrees = new ArrayList<Extraction>(); + purificationsCrees = new ArrayList<Purification>(); + testsBioCrees = new ArrayList<TestBio>(); } /** {@inheritDoc} */ @Override public String toString() { - return prenom + " " + nom; + return prenom + " " + nom; } /** {@inheritDoc} */ @Override public int compareTo(Personne personne) { - ComparatorChain comparatorChain = new ComparatorChain(); - comparatorChain.addComparator(new BeanComparator("nom")); - comparatorChain.addComparator(new BeanComparator("prenom")); - return comparatorChain.compare(this, personne); + ComparatorChain comparatorChain = new ComparatorChain(); + comparatorChain.addComparator(new BeanComparator("nom")); + comparatorChain.addComparator(new BeanComparator("prenom")); + return comparatorChain.compare(this, personne); } /** @@ -216,7 +217,7 @@ * @return idPersonne */ public Integer getIdPersonne() { - return idPersonne; + return idPersonne; } /** @@ -224,7 +225,7 @@ * @param idPersonne idPersonne */ public void setIdPersonne(Integer idPersonne) { - this.idPersonne = idPersonne; + this.idPersonne = idPersonne; } /** @@ -232,7 +233,7 @@ * @return adressePostale */ public String getAdressePostale() { - return adressePostale; + return adressePostale; } /** @@ -240,7 +241,7 @@ * @param adressePostale adressePostale */ public void setAdressePostale(String adressePostale) { - this.adressePostale = adressePostale; + this.adressePostale = adressePostale; } /** @@ -248,7 +249,7 @@ * @return campagnesCreees */ public List<Campagne> getCampagnesCreees() { - return campagnesCreees; + return campagnesCreees; } /** @@ -256,7 +257,7 @@ * @param campagnesCreees campagnesCreees */ public void setCampagnesCreees(List<Campagne> campagnesCreees) { - this.campagnesCreees = campagnesCreees; + this.campagnesCreees = campagnesCreees; } /** @@ -264,7 +265,7 @@ * @return campagnesDroits */ public Map<Campagne, CampagnePersonneDroits> getCampagnesDroits() { - return campagnesDroits; + return campagnesDroits; } /** @@ -272,7 +273,7 @@ * @param campagnesDroits campagnesDroits */ public void setCampagnesDroits(Map<Campagne, CampagnePersonneDroits> campagnesDroits) { - this.campagnesDroits = campagnesDroits; + this.campagnesDroits = campagnesDroits; } /** @@ -280,7 +281,7 @@ * @return campagnesParticipees */ public List<CampagnePersonneParticipant> getCampagnesParticipees() { - return campagnesParticipees; + return campagnesParticipees; } /** @@ -288,7 +289,7 @@ * @param campagnesParticipees campagnesParticipees */ public void setCampagnesParticipees(List<CampagnePersonneParticipant> campagnesParticipees) { - this.campagnesParticipees = campagnesParticipees; + this.campagnesParticipees = campagnesParticipees; } /** @@ -296,7 +297,7 @@ * @return codePays */ public String getCodePays() { - return codePays; + return codePays; } /** @@ -304,7 +305,7 @@ * @param codePays codePays */ public void setCodePays(String codePays) { - this.codePays = codePays; + this.codePays = codePays; } /** @@ -312,7 +313,7 @@ * @return codePostal */ public String getCodePostal() { - return codePostal; + return codePostal; } /** @@ -320,7 +321,7 @@ * @param codePostal codePostal */ public void setCodePostal(String codePostal) { - this.codePostal = codePostal; + this.codePostal = codePostal; } /** @@ -328,7 +329,7 @@ * @return courriel */ public String getCourriel() { - return courriel; + return courriel; } /** @@ -336,7 +337,7 @@ * @param courriel courriel */ public void setCourriel(String courriel) { - this.courriel = courriel; + this.courriel = courriel; } /** @@ -344,7 +345,7 @@ * @return fax */ public String getFax() { - return fax; + return fax; } /** @@ -352,7 +353,7 @@ * @param fax fax */ public void setFax(String fax) { - this.fax = fax; + this.fax = fax; } /** @@ -360,7 +361,7 @@ * @return fonction */ public String getFonction() { - return fonction; + return fonction; } /** @@ -368,7 +369,7 @@ * @param fonction fonction */ public void setFonction(String fonction) { - this.fonction = fonction; + this.fonction = fonction; } /** @@ -376,7 +377,7 @@ * @return lotsCrees */ public List<Lot> getLotsCrees() { - return lotsCrees; + return lotsCrees; } /** @@ -384,7 +385,7 @@ * @param lotsCrees lotsCrees */ public void setLotsCrees(List<Lot> lotsCrees) { - this.lotsCrees = lotsCrees; + this.lotsCrees = lotsCrees; } /** @@ -392,7 +393,7 @@ * @return lotsDroits */ public Map<Lot, LotPersonneDroits> getLotsDroits() { - return lotsDroits; + return lotsDroits; } /** @@ -400,7 +401,7 @@ * @param lotsDroits lotsDroits */ public void setLotsDroits(Map<Lot, LotPersonneDroits> lotsDroits) { - this.lotsDroits = lotsDroits; + this.lotsDroits = lotsDroits; } /** @@ -408,7 +409,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -416,7 +417,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -424,7 +425,7 @@ * @return organisme */ public String getOrganisme() { - return organisme; + return organisme; } /** @@ -432,7 +433,7 @@ * @param organisme organisme */ public void setOrganisme(String organisme) { - this.organisme = organisme; + this.organisme = organisme; } /** @@ -440,7 +441,7 @@ * @return prenom */ public String getPrenom() { - return prenom; + return prenom; } /** @@ -448,7 +449,7 @@ * @param prenom prenom */ public void setPrenom(String prenom) { - this.prenom = prenom; + this.prenom = prenom; } /** @@ -456,7 +457,7 @@ * @return tel */ public String getTel() { - return tel; + return tel; } /** @@ -464,7 +465,7 @@ * @param tel tel */ public void setTel(String tel) { - this.tel = tel; + this.tel = tel; } /** @@ -472,7 +473,7 @@ * @return ville */ public String getVille() { - return ville; + return ville; } /** @@ -480,7 +481,7 @@ * @param ville ville */ public void setVille(String ville) { - this.ville = ville; + this.ville = ville; } /** @@ -488,7 +489,7 @@ * @return stationsCrees */ public List<Station> getStationsCrees() { - return stationsCrees; + return stationsCrees; } /** @@ -496,7 +497,7 @@ * @param stationsCrees stationsCrees */ public void setStationsCrees(List<Station> stationsCrees) { - this.stationsCrees = stationsCrees; + this.stationsCrees = stationsCrees; } /** @@ -504,7 +505,7 @@ * @return specimensCrees */ public List<Specimen> getSpecimensCrees() { - return specimensCrees; + return specimensCrees; } /** @@ -512,7 +513,7 @@ * @param specimensCrees specimensCrees */ public void setSpecimensCrees(List<Specimen> specimensCrees) { - this.specimensCrees = specimensCrees; + this.specimensCrees = specimensCrees; } /** @@ -520,7 +521,7 @@ * @return extractionsCrees */ public List<Extraction> getExtractionsCrees() { - return extractionsCrees; + return extractionsCrees; } /** @@ -528,7 +529,7 @@ * @param extractionsCrees extractionsCrees */ public void setExtractionsCrees(List<Extraction> extractionsCrees) { - this.extractionsCrees = extractionsCrees; + this.extractionsCrees = extractionsCrees; } /** @@ -536,7 +537,7 @@ * @return purificationsCrees */ public List<Purification> getPurificationsCrees() { - return purificationsCrees; + return purificationsCrees; } /** @@ -544,7 +545,7 @@ * @param purificationsCrees purificationsCrees */ public void setPurificationsCrees(List<Purification> purificationsCrees) { - this.purificationsCrees = purificationsCrees; + this.purificationsCrees = purificationsCrees; } /** @@ -552,7 +553,7 @@ * @return testsBioCrees */ public List<TestBio> getTestsBioCrees() { - return testsBioCrees; + return testsBioCrees; } /** @@ -560,7 +561,7 @@ * @param testsBioCrees testsBioCrees */ public void setTestsBioCrees(List<TestBio> testsBioCrees) { - this.testsBioCrees = testsBioCrees; + this.testsBioCrees = testsBioCrees; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Produit.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Produit.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Produit.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,10 +58,7 @@ */ @Entity @Inheritance(strategy = InheritanceType.JOINED) -@ClassBridge(name="produitBridge", - index=Index.YES, - store=Store.YES, - impl = ProduitBridge.class) +@ClassBridge(name = "produitBridge", index = Index.YES, store = Store.YES, impl = ProduitBridge.class) public abstract class Produit extends AbstractModel implements Cloneable, Comparable<Produit> { /** Id du produit */ @@ -73,7 +70,7 @@ @Length(max = LENGTH_MEDIUM_TEXT) @NotEmpty @Column(unique = true) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Masse obtenue pour le produit **/ @@ -97,9 +94,9 @@ * Constructor */ public Produit() { - super(); - purificationsSuivantes = new ArrayList<Purification>(); - resultatsTestsBioSuivants = new ArrayList<ResultatTestBio>(); + super(); + purificationsSuivantes = new ArrayList<Purification>(); + resultatsTestsBioSuivants = new ArrayList<ResultatTestBio>(); } /** @@ -117,22 +114,22 @@ /** {@inheritDoc} */ @Override public Produit clone() throws CloneNotSupportedException { - Produit clone = (Produit) super.clone(); - clone.id = id; - clone.ref = ref; - return clone; + Produit clone = (Produit) super.clone(); + clone.id = id; + clone.ref = ref; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return this.ref; + return this.ref; } /** {@inheritDoc} */ @Override public int compareTo(Produit produit) { - return new BeanComparator("ref").compare(this, produit); + return new BeanComparator("ref").compare(this, produit); } /** @@ -140,7 +137,7 @@ * @return id */ public Integer getId() { - return id; + return id; } /** @@ -148,7 +145,7 @@ * @param id id */ public void setId(Integer id) { - this.id = id; + this.id = id; } /** @@ -156,7 +153,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -164,7 +161,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -172,7 +169,7 @@ * @return masseObtenue */ public BigDecimal getMasseObtenue() { - return masseObtenue; + return masseObtenue; } /** @@ -180,7 +177,7 @@ * @param masseObtenue masseObtenue */ public void setMasseObtenue(BigDecimal masseObtenue) { - this.masseObtenue = masseObtenue; + this.masseObtenue = masseObtenue; } /** @@ -188,7 +185,7 @@ * @return purificationsSuivantes */ public List<Purification> getPurificationsSuivantes() { - return purificationsSuivantes; + return purificationsSuivantes; } /** @@ -196,7 +193,7 @@ * @param purificationsSuivantes purificationsSuivantes */ public void setPurificationsSuivantes(List<Purification> purificationsSuivantes) { - this.purificationsSuivantes = purificationsSuivantes; + this.purificationsSuivantes = purificationsSuivantes; } /** @@ -204,7 +201,7 @@ * @return resultatsTestsBioSuivants */ public List<ResultatTestBio> getResultatsTestsBioSuivants() { - return resultatsTestsBioSuivants; + return resultatsTestsBioSuivants; } /** @@ -212,7 +209,7 @@ * @param resultatsTestsBioSuivants resultatsTestsBioSuivants */ public void setResultatsTestsBioSuivants(List<ResultatTestBio> resultatsTestsBioSuivants) { - this.resultatsTestsBioSuivants = resultatsTestsBioSuivants; + this.resultatsTestsBioSuivants = resultatsTestsBioSuivants; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Purification.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Purification.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Purification.java 2013-02-18 07:27:17 UTC (rev 119) @@ -71,9 +71,7 @@ */ @Entity @Indexed -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Purification", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Purification", impl = UtilisateurSearchFilter.class) }) public class Purification extends AbstractModel implements Comparable<Purification> { /** Id de la purification */ @@ -85,7 +83,7 @@ @Length(max = LENGTH_MEDIUM_TEXT) @Column(unique = true) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Manipulateur */ @@ -106,7 +104,7 @@ /** Paramètres qui caractérisent la méthode pour cette purification */ @NotNull @OneToMany(mappedBy = "purification", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) private List<ParamMethoPuriEffectif> paramsMetho; /** Produit utilisé pour la purification **/ @@ -123,7 +121,8 @@ /** Commentaire pour la manip */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Détermine si la manip doit être confidentielle */ @@ -143,7 +142,7 @@ /** Fractions produites par la purification */ @NotNull @OneToMany(mappedBy = "purification", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.REFRESH, CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.REFRESH, CascadeType.SAVE_UPDATE }) private List<Fraction> fractions; /** @@ -157,23 +156,23 @@ * Constructeur */ public Purification() { - fractions = new ArrayList<Fraction>(); - paramsMetho = new ArrayList<ParamMethoPuriEffectif>(); + fractions = new ArrayList<Fraction>(); + paramsMetho = new ArrayList<ParamMethoPuriEffectif>(); } /** {@inheritDoc} */ @Override public String toString() { - return ref; + return ref; } /** {@inheritDoc} */ @Override public int compareTo(Purification purification) { - ComparatorChain comparatorChain = new ComparatorChain(); - comparatorChain.addComparator(new BeanComparator("produit")); - comparatorChain.addComparator(new BeanComparator("ref")); - return comparatorChain.compare(this, purification); + ComparatorChain comparatorChain = new ComparatorChain(); + comparatorChain.addComparator(new BeanComparator("produit")); + comparatorChain.addComparator(new BeanComparator("ref")); + return comparatorChain.compare(this, purification); } /** @@ -181,8 +180,8 @@ * @param produit produit */ public void setProduit(Produit produit) { - this.lotSource = findLotSourceFromProduit(produit); - this.produit = produit; + this.lotSource = findLotSourceFromProduit(produit); + this.produit = produit; } /** @@ -190,10 +189,10 @@ * @return fractions */ public List<Fraction> getSortedFractions() { - // comme "@Sort(type = SortType.COMPARATOR, comparator = FractionsOfPurificationComp.class)" ne rend pas une - // liste triée avec List, tri dans le getter - Collections.sort(fractions, new FractionsOfPurificationComp()); - return fractions; + // comme "@Sort(type = SortType.COMPARATOR, comparator = FractionsOfPurificationComp.class)" ne rend pas une + // liste triée avec List, tri dans le getter + Collections.sort(fractions, new FractionsOfPurificationComp()); + return fractions; } /** @@ -202,8 +201,8 @@ */ @SuppressWarnings("unchecked") public List<ParamMethoPuriEffectif> getSortedParamsMetho() { - Collections.sort(paramsMetho, new BeanComparator("param.index")); - return paramsMetho; + Collections.sort(paramsMetho, new BeanComparator("param.index")); + return paramsMetho; } /** @@ -211,7 +210,7 @@ * @return idPurification */ public Integer getIdPurification() { - return idPurification; + return idPurification; } /** @@ -219,7 +218,7 @@ * @param idPurification idPurification */ public void setIdPurification(Integer idPurification) { - this.idPurification = idPurification; + this.idPurification = idPurification; } /** @@ -227,7 +226,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -235,7 +234,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -243,7 +242,7 @@ * @return manipulateur */ public Personne getManipulateur() { - return manipulateur; + return manipulateur; } /** @@ -251,7 +250,7 @@ * @param manipulateur manipulateur */ public void setManipulateur(Personne manipulateur) { - this.manipulateur = manipulateur; + this.manipulateur = manipulateur; } /** @@ -259,7 +258,7 @@ * @return date */ public Date getDate() { - return date; + return date; } /** @@ -267,7 +266,7 @@ * @param date date */ public void setDate(Date date) { - this.date = date; + this.date = date; } /** @@ -275,7 +274,7 @@ * @return methode */ public MethodePurification getMethode() { - return methode; + return methode; } /** @@ -283,7 +282,7 @@ * @param methode methode */ public void setMethode(MethodePurification methode) { - this.methode = methode; + this.methode = methode; } /** @@ -291,7 +290,7 @@ * @return paramsMetho */ public List<ParamMethoPuriEffectif> getParamsMetho() { - return paramsMetho; + return paramsMetho; } /** @@ -299,7 +298,7 @@ * @param paramsMetho paramsMetho */ public void setParamsMetho(List<ParamMethoPuriEffectif> paramsMetho) { - this.paramsMetho = paramsMetho; + this.paramsMetho = paramsMetho; } /** @@ -307,7 +306,7 @@ * @return masseDepart */ public BigDecimal getMasseDepart() { - return masseDepart; + return masseDepart; } /** @@ -315,7 +314,7 @@ * @param masseDepart masseDepart */ public void setMasseDepart(BigDecimal masseDepart) { - this.masseDepart = masseDepart; + this.masseDepart = masseDepart; } /** @@ -323,7 +322,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -331,7 +330,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -339,7 +338,7 @@ * @return confidentiel */ public boolean isConfidentiel() { - return confidentiel; + return confidentiel; } /** @@ -347,7 +346,7 @@ * @param confidentiel confidentiel */ public void setConfidentiel(boolean confidentiel) { - this.confidentiel = confidentiel; + this.confidentiel = confidentiel; } /** @@ -355,7 +354,7 @@ * @return dateConfidentialite */ public Date getDateConfidentialite() { - return dateConfidentialite; + return dateConfidentialite; } /** @@ -363,7 +362,7 @@ * @param dateConfidentialite dateConfidentialite */ public void setDateConfidentialite(Date dateConfidentialite) { - this.dateConfidentialite = dateConfidentialite; + this.dateConfidentialite = dateConfidentialite; } /** @@ -371,7 +370,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -379,7 +378,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -387,7 +386,7 @@ * @return lotSource */ public Lot getLotSource() { - return lotSource; + return lotSource; } /** @@ -395,7 +394,7 @@ * @return fractions */ public List<Fraction> getFractions() { - return fractions; + return fractions; } /** @@ -403,7 +402,7 @@ * @param fractions fractions */ public void setFractions(List<Fraction> fractions) { - this.fractions = fractions; + this.fractions = fractions; } /** @@ -411,7 +410,7 @@ * @param lotSource lotSource */ public void setLotSource(Lot lotSource) { - this.lotSource = lotSource; + this.lotSource = lotSource; } /** @@ -419,7 +418,7 @@ * @return produit */ public Produit getProduit() { - return produit; + return produit; } /** @@ -428,16 +427,16 @@ * @return Le lot */ public Lot findLotSourceFromProduit(Produit produit) { - Produit curProd = produit; - while (curProd.isFraction()) { - Fraction curFraction = (Fraction) curProd; - curProd = curFraction.getPurification().getProduit(); - } - AssertTools.assertClassOrInterface(curProd, Extrait.class); + Produit curProd = produit; + while (curProd.isFraction()) { + Fraction curFraction = (Fraction) curProd; + curProd = curFraction.getPurification().getProduit(); + } + AssertTools.assertClassOrInterface(curProd, Extrait.class); - Extrait extrait = (Extrait) curProd; + Extrait extrait = (Extrait) curProd; - return extrait.getExtraction().getLot(); + return extrait.getExtraction().getLot(); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ResultatTestBio.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ResultatTestBio.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/ResultatTestBio.java 2013-02-18 07:27:17 UTC (rev 119) @@ -63,52 +63,49 @@ @Entity @CollectionUniqueField(fieldName = "repere", pathToCollection = "testBio.resultats") @Indexed -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-ResultatTestBio", impl = UtilisateurSearchFilter.class) -}) -public class ResultatTestBio extends AbstractModel implements Cloneable, - Comparable<ResultatTestBio> { +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-ResultatTestBio", impl = UtilisateurSearchFilter.class) }) +public class ResultatTestBio extends AbstractModel implements Cloneable, Comparable<ResultatTestBio> { /** * Type du résultat de test biologique */ public enum TypeResultat implements Comparable<TypeResultat> { - /** Blanc, dans ce cas pas de réf, conc./masse, stade et actif renseigné */ - BLANC, - /** Témoin, dans ce cas pas de stade renseigné */ - TEMOIN, - /** Produit */ - PRODUIT + /** Blanc, dans ce cas pas de réf, conc./masse, stade et actif renseigné */ + BLANC, + /** Témoin, dans ce cas pas de stade renseigné */ + TEMOIN, + /** Produit */ + PRODUIT } /** * Stade du résultat de test biologique */ public enum Stade implements Comparable<Stade> { - /** Détection */ - DETECTION, - /** Confirmation */ - CONFIRMATION, - /** Fractionnement */ - FRACTIONNEMENT + /** Détection */ + DETECTION, + /** Confirmation */ + CONFIRMATION, + /** Fractionnement */ + FRACTIONNEMENT } /** * Unité de la concentration/masse d'un test biologique */ public enum UniteConcMasse implements Comparable<UniteConcMasse> { - /** mg **/ - MG, - /** μg **/ - MICROG, - /** ng **/ - NG, - /** ng/ml **/ - MG_ML, - /** μg/ml **/ - MICROG_ML, - /** ng/ml **/ - NG_ML + /** mg **/ + MG, + /** μg **/ + MICROG, + /** ng **/ + NG, + /** ng/ml **/ + MG_ML, + /** μg/ml **/ + MICROG_ML, + /** ng/ml **/ + NG_ML } /** Id du produit */ @@ -179,7 +176,7 @@ * Constructor */ public ResultatTestBio() { - super(); + super(); } /** @@ -188,53 +185,48 @@ * @return Le lot source */ public Lot getLotSource() { - if (produit == null) { - return null; - } - if (produit.isExtrait()) { - Extrait extrait = (Extrait) produit; - return extrait.getExtraction().getLot(); - } - // cas où c'est une fraction - Fraction fraction = (Fraction) produit; - return fraction.getPurification().getLotSource(); + if (produit == null) { + return null; + } + if (produit.isExtrait()) { + Extrait extrait = (Extrait) produit; + return extrait.getExtraction().getLot(); + } + // cas où c'est une fraction + Fraction fraction = (Fraction) produit; + return fraction.getPurification().getLotSource(); } /** {@inheritDoc} */ @Override public ResultatTestBio clone() throws CloneNotSupportedException { - ResultatTestBio clone = (ResultatTestBio) super.clone(); - clone.id = id; - clone.repere = repere; - clone.typeResultat = typeResultat; - clone.produit = produit; - clone.stade = stade; - clone.estActif = estActif; - clone.testBio = testBio; - return clone; + ResultatTestBio clone = (ResultatTestBio) super.clone(); + clone.id = id; + clone.repere = repere; + clone.typeResultat = typeResultat; + clone.produit = produit; + clone.stade = stade; + clone.estActif = estActif; + clone.testBio = testBio; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return "(" - + this.getRepere() - + ", " - + this.getTypeResultat() - + ", " - + (TypeResultat.PRODUIT.equals(this.getTypeResultat()) ? this - .getProduit() : this.getProduitTemoin()) + ")"; + return "(" + this.getRepere() + ", " + this.getTypeResultat() + ", " + + (TypeResultat.PRODUIT.equals(this.getTypeResultat()) ? this.getProduit() : this.getProduitTemoin()) + + ")"; } /** {@inheritDoc} */ @Override public final int compareTo(ResultatTestBio resultat) { - ComparatorChain comparatorChain = new ComparatorChain(); - comparatorChain.addComparator(new BeanComparator( - "testBio.methode.cible")); - comparatorChain.addComparator(new BeanComparator("produit")); - comparatorChain.addComparator(new BeanComparator("repere")); - return comparatorChain.compare(this, resultat); + ComparatorChain comparatorChain = new ComparatorChain(); + comparatorChain.addComparator(new BeanComparator("testBio.methode.cible")); + comparatorChain.addComparator(new BeanComparator("produit")); + comparatorChain.addComparator(new BeanComparator("repere")); + return comparatorChain.compare(this, resultat); } /** @@ -245,13 +237,12 @@ * produit */ public void setProduit(Produit produit) { - if (produit == null) { - this.typeExtraitSource = null; - } else { - this.typeExtraitSource = findExtraitSourceFromProduit(produit) - .getTypeExtrait(); - } - this.produit = produit; + if (produit == null) { + this.typeExtraitSource = null; + } else { + this.typeExtraitSource = findExtraitSourceFromProduit(produit).getTypeExtrait(); + } + this.produit = produit; } /** @@ -260,7 +251,7 @@ * @return id */ public Integer getId() { - return id; + return id; } /** @@ -270,7 +261,7 @@ * id */ public void setId(Integer id) { - this.id = id; + this.id = id; } /** @@ -279,7 +270,7 @@ * @return repere */ public String getRepere() { - return repere; + return repere; } /** @@ -289,7 +280,7 @@ * repere */ public void setRepere(String repere) { - this.repere = repere; + this.repere = repere; } /** @@ -298,7 +289,7 @@ * @return typeResultat */ public TypeResultat getTypeResultat() { - return typeResultat; + return typeResultat; } /** @@ -308,7 +299,7 @@ * typeResultat */ public void setTypeResultat(TypeResultat typeResultat) { - this.typeResultat = typeResultat; + this.typeResultat = typeResultat; } /** @@ -317,7 +308,7 @@ * @return produit */ public Produit getProduit() { - return produit; + return produit; } /** @@ -326,7 +317,7 @@ * @return produitTemoin */ public String getProduitTemoin() { - return produitTemoin; + return produitTemoin; } /** @@ -336,7 +327,7 @@ * produitTemoin */ public void setProduitTemoin(String produitTemoin) { - this.produitTemoin = produitTemoin; + this.produitTemoin = produitTemoin; } /** @@ -345,7 +336,7 @@ * @return concMasse */ public BigDecimal getConcMasse() { - return concMasse; + return concMasse; } /** @@ -355,7 +346,7 @@ * concMasse */ public void setConcMasse(BigDecimal concMasse) { - this.concMasse = concMasse; + this.concMasse = concMasse; } /** @@ -364,7 +355,7 @@ * @return uniteConcMasse */ public UniteConcMasse getUniteConcMasse() { - return uniteConcMasse; + return uniteConcMasse; } /** @@ -374,7 +365,7 @@ * uniteConcMasse */ public void setUniteConcMasse(UniteConcMasse uniteConcMasse) { - this.uniteConcMasse = uniteConcMasse; + this.uniteConcMasse = uniteConcMasse; } /** @@ -383,7 +374,7 @@ * @return stade */ public Stade getStade() { - return stade; + return stade; } /** @@ -393,7 +384,7 @@ * stade */ public void setStade(Stade stade) { - this.stade = stade; + this.stade = stade; } /** @@ -402,7 +393,7 @@ * @return valeur */ public BigDecimal getValeur() { - return valeur; + return valeur; } /** @@ -412,7 +403,7 @@ * valeur */ public void setValeur(BigDecimal valeur) { - this.valeur = valeur; + this.valeur = valeur; } /** @@ -421,7 +412,7 @@ * @return estActif */ public Boolean isActif() { - return estActif; + return estActif; } /** @@ -431,7 +422,7 @@ * estActif */ public void setActif(Boolean estActif) { - this.estActif = estActif; + this.estActif = estActif; } /** @@ -440,7 +431,7 @@ * @return erreur */ public ErreurTestBio getErreur() { - return erreur; + return erreur; } /** @@ -450,7 +441,7 @@ * erreur */ public void setErreur(ErreurTestBio erreur) { - this.erreur = erreur; + this.erreur = erreur; } /** @@ -459,7 +450,7 @@ * @return testBio */ public TestBio getTestBio() { - return testBio; + return testBio; } /** @@ -469,7 +460,7 @@ * testBio */ public void setTestBio(TestBio testBio) { - this.testBio = testBio; + this.testBio = testBio; } /** @@ -478,7 +469,7 @@ * @return typeExtraitSource */ public TypeExtrait getTypeExtraitSource() { - return typeExtraitSource; + return typeExtraitSource; } /** @@ -488,7 +479,7 @@ * typeExtraitSource */ public void setTypeExtraitSource(TypeExtrait typeExtraitSource) { - this.typeExtraitSource = typeExtraitSource; + this.typeExtraitSource = typeExtraitSource; } /** @@ -499,19 +490,19 @@ * @return Le lot */ public Extrait findExtraitSourceFromProduit(Produit produit) { - if (produit.isExtrait()) { - Extrait extrait = (Extrait) produit; - return extrait; - } - // cas où c'est une fraction - Produit curProd = produit; - while (curProd.isFraction()) { - Fraction curFraction = (Fraction) curProd; - curProd = curFraction.getPurification().getProduit(); - } - AssertTools.assertClassOrInterface(curProd, Extrait.class); + if (produit.isExtrait()) { + Extrait extrait = (Extrait) produit; + return extrait; + } + // cas où c'est une fraction + Produit curProd = produit; + while (curProd.isFraction()) { + Fraction curFraction = (Fraction) curProd; + curProd = curFraction.getPurification().getProduit(); + } + AssertTools.assertClassOrInterface(curProd, Extrait.class); - return (Extrait) curProd; + return (Extrait) curProd; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Specimen.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Specimen.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Specimen.java 2013-02-18 07:27:17 UTC (rev 119) @@ -64,29 +64,27 @@ @Table @Indexed @Embeddable -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Specimen", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Specimen", impl = UtilisateurSearchFilter.class) }) public class Specimen extends AbstractModel implements Comparable<Specimen> { /** * Types d'organisme pour un spécimen */ public enum TypeOrganisme implements Comparable<TypeOrganisme> { - /** Plante */ - PLANTE, - /** Organisme marin */ - ORGANISME_MARIN, - /** Microorganisme */ - MICROORGANISME, - /** Insecte */ - INSECTE, - /** Champignon */ - CHAMPIGNON, - /** Lichen */ - LICHEN, - /** Autre */ - AUTRE + /** Plante */ + PLANTE, + /** Organisme marin */ + ORGANISME_MARIN, + /** Microorganisme */ + MICROORGANISME, + /** Insecte */ + INSECTE, + /** Champignon */ + CHAMPIGNON, + /** Lichen */ + LICHEN, + /** Autre */ + AUTRE } /** ID */ @@ -98,28 +96,28 @@ @Column(unique = true) @NotEmpty @Length(max = LENGTH_TINY_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Embranchement */ @Length(max = LENGTH_MEDIUM_TEXT) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String embranchement; /** Famille */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String famille; /** Genre */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String genre; /** Espèce */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String espece; /** Sous-espèce */ @@ -153,12 +151,13 @@ /** Station */ @ManyToOne(fetch = FetchType.EAGER) - @IndexedEmbedded(depth=1) + @IndexedEmbedded(depth = 1) private Station station; /** Compléments d'information */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Créateur */ @@ -170,13 +169,13 @@ /** {@inheritDoc} */ @Override public String toString() { - return ref; + return ref; } /** {@inheritDoc} */ @Override public int compareTo(Specimen specimen) { - return new BeanComparator("ref").compare(this, specimen); + return new BeanComparator("ref").compare(this, specimen); } /** @@ -184,7 +183,7 @@ * @return idSpecimen */ public Integer getIdSpecimen() { - return idSpecimen; + return idSpecimen; } /** @@ -192,7 +191,7 @@ * @param idSpecimen idSpecimen */ public void setIdSpecimen(Integer idSpecimen) { - this.idSpecimen = idSpecimen; + this.idSpecimen = idSpecimen; } /** @@ -200,7 +199,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -208,7 +207,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -216,7 +215,7 @@ * @return embranchement */ public String getEmbranchement() { - return embranchement; + return embranchement; } /** @@ -224,7 +223,7 @@ * @param embranchement embranchement */ public void setEmbranchement(String embranchement) { - this.embranchement = embranchement; + this.embranchement = embranchement; } /** @@ -232,7 +231,7 @@ * @return famille */ public String getFamille() { - return famille; + return famille; } /** @@ -240,7 +239,7 @@ * @param famille famille */ public void setFamille(String famille) { - this.famille = famille; + this.famille = famille; } /** @@ -248,7 +247,7 @@ * @return genre */ public String getGenre() { - return genre; + return genre; } /** @@ -256,7 +255,7 @@ * @param genre genre */ public void setGenre(String genre) { - this.genre = genre; + this.genre = genre; } /** @@ -264,7 +263,7 @@ * @return espece */ public String getEspece() { - return espece; + return espece; } /** @@ -272,7 +271,7 @@ * @param espece espece */ public void setEspece(String espece) { - this.espece = espece; + this.espece = espece; } /** @@ -280,7 +279,7 @@ * @return sousEspece */ public String getSousEspece() { - return sousEspece; + return sousEspece; } /** @@ -288,7 +287,7 @@ * @param sousEspece sousEspece */ public void setSousEspece(String sousEspece) { - this.sousEspece = sousEspece; + this.sousEspece = sousEspece; } /** @@ -296,7 +295,7 @@ * @return variete */ public String getVariete() { - return variete; + return variete; } /** @@ -304,7 +303,7 @@ * @param variete variete */ public void setVariete(String variete) { - this.variete = variete; + this.variete = variete; } /** @@ -312,7 +311,7 @@ * @return typeOrganisme */ public TypeOrganisme getTypeOrganisme() { - return typeOrganisme; + return typeOrganisme; } /** @@ -320,7 +319,7 @@ * @param typeOrganisme typeOrganisme */ public void setTypeOrganisme(TypeOrganisme typeOrganisme) { - this.typeOrganisme = typeOrganisme; + this.typeOrganisme = typeOrganisme; } /** @@ -328,7 +327,7 @@ * @return identificateur */ public Personne getIdentificateur() { - return identificateur; + return identificateur; } /** @@ -336,7 +335,7 @@ * @param identificateur identificateur */ public void setIdentificateur(Personne identificateur) { - this.identificateur = identificateur; + this.identificateur = identificateur; } /** @@ -344,7 +343,7 @@ * @return dateDepot */ public Date getDateDepot() { - return dateDepot; + return dateDepot; } /** @@ -352,7 +351,7 @@ * @param dateDepot dateDepot */ public void setDateDepot(Date dateDepot) { - this.dateDepot = dateDepot; + this.dateDepot = dateDepot; } /** @@ -360,7 +359,7 @@ * @return numDepot */ public String getNumDepot() { - return numDepot; + return numDepot; } /** @@ -368,7 +367,7 @@ * @param numDepot numDepot */ public void setNumDepot(String numDepot) { - this.numDepot = numDepot; + this.numDepot = numDepot; } /** @@ -376,7 +375,7 @@ * @return lieuDepot */ public String getLieuDepot() { - return lieuDepot; + return lieuDepot; } /** @@ -384,7 +383,7 @@ * @param lieuDepot lieuDepot */ public void setLieuDepot(String lieuDepot) { - this.lieuDepot = lieuDepot; + this.lieuDepot = lieuDepot; } /** @@ -392,7 +391,7 @@ * @return station */ public Station getStation() { - return station; + return station; } /** @@ -400,7 +399,7 @@ * @param station station */ public void setStation(Station station) { - this.station = station; + this.station = station; } /** @@ -408,7 +407,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -416,7 +415,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -424,7 +423,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -432,7 +431,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Station.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Station.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Station.java 2013-02-18 07:27:17 UTC (rev 119) @@ -69,9 +69,7 @@ @AccessType("field") @Indexed @Embeddable -@FullTextFilterDefs( { - @FullTextFilterDef(name = "utilisateur-Station", impl = UtilisateurSearchFilter.class) -}) +@FullTextFilterDefs( { @FullTextFilterDef(name = "utilisateur-Station", impl = UtilisateurSearchFilter.class) }) public class Station extends AbstractModel implements Cloneable, Comparable<Station> { /** ID */ @@ -83,19 +81,20 @@ @Column(unique = true) @NotEmpty @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String nom; /** Code pays */ @NotNull @Length(min = 2, max = 2) @CountryCode - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String codePays; /** Complément */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Créateur */ @@ -106,7 +105,7 @@ /** Localité */ @Length(max = LENGTH_MEDIUM_TEXT) - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String localite; /** Latitude */ @@ -139,36 +138,36 @@ * Constructeur */ public Station() { - lots = new ArrayList<Lot>(); - campagnes = new ArrayList<Campagne>(); + lots = new ArrayList<Lot>(); + campagnes = new ArrayList<Campagne>(); } /** {@inheritDoc} */ @Override public Station clone() throws CloneNotSupportedException { - Station clone = (Station) super.clone(); - clone.idStation = idStation; - clone.nom = nom; - clone.codePays = codePays; - clone.complement = complement; - clone.createur = createur; - clone.localite = localite; - clone.latitude = latitude; - clone.longitude = longitude; - clone.referentiel = referentiel; - return clone; + Station clone = (Station) super.clone(); + clone.idStation = idStation; + clone.nom = nom; + clone.codePays = codePays; + clone.complement = complement; + clone.createur = createur; + clone.localite = localite; + clone.latitude = latitude; + clone.longitude = longitude; + clone.referentiel = referentiel; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return nom; + return nom; } /** {@inheritDoc} */ @Override public int compareTo(Station station) { - return new BeanComparator("nom").compare(this, station); + return new BeanComparator("nom").compare(this, station); } /** @@ -176,7 +175,7 @@ * @return idStation */ public Integer getIdStation() { - return idStation; + return idStation; } /** @@ -184,7 +183,7 @@ * @param idStation idStation */ public void setIdStation(Integer idStation) { - this.idStation = idStation; + this.idStation = idStation; } /** @@ -192,7 +191,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -200,7 +199,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -208,7 +207,7 @@ * @return codePays */ public String getCodePays() { - return codePays; + return codePays; } /** @@ -216,7 +215,7 @@ * @param codePays codePays */ public void setCodePays(String codePays) { - this.codePays = codePays; + this.codePays = codePays; } /** @@ -224,7 +223,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -232,7 +231,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -240,7 +239,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -248,7 +247,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -256,7 +255,7 @@ * @return localite */ public String getLocalite() { - return localite; + return localite; } /** @@ -264,7 +263,7 @@ * @param localite localite */ public void setLocalite(String localite) { - this.localite = localite; + this.localite = localite; } /** @@ -272,7 +271,7 @@ * @return latitude */ public String getLatitude() { - return latitude; + return latitude; } /** @@ -280,7 +279,7 @@ * @param latitude latitude */ public void setLatitude(String latitude) { - this.latitude = latitude; + this.latitude = latitude; } /** @@ -288,7 +287,7 @@ * @return longitude */ public String getLongitude() { - return longitude; + return longitude; } /** @@ -296,7 +295,7 @@ * @param longitude longitude */ public void setLongitude(String longitude) { - this.longitude = longitude; + this.longitude = longitude; } /** @@ -304,7 +303,7 @@ * @return referentiel */ public Integer getReferentiel() { - return referentiel; + return referentiel; } /** @@ -312,7 +311,7 @@ * @param referentiel referentiel */ public void setReferentiel(Integer referentiel) { - this.referentiel = referentiel; + this.referentiel = referentiel; } /** @@ -320,7 +319,7 @@ * @return lots */ public List<Lot> getLots() { - return lots; + return lots; } /** @@ -328,7 +327,7 @@ * @param lots lots */ public void setLots(List<Lot> lots) { - this.lots = lots; + this.lots = lots; } /** @@ -336,7 +335,7 @@ * @return campagnes */ public List<Campagne> getCampagnes() { - return campagnes; + return campagnes; } /** @@ -344,7 +343,7 @@ * @param campagnes campagnes */ public void setCampagnes(List<Campagne> campagnes) { - this.campagnes = campagnes; + this.campagnes = campagnes; } /** @@ -352,7 +351,7 @@ * @return specimensRattaches */ public List<Specimen> getSpecimensRattaches() { - return specimensRattaches; + return specimensRattaches; } /** @@ -360,7 +359,7 @@ * @param specimensRattaches specimensRattaches */ public void setSpecimensRattaches(List<Specimen> specimensRattaches) { - this.specimensRattaches = specimensRattaches; + this.specimensRattaches = specimensRattaches; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TestBio.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TestBio.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TestBio.java 2013-02-18 07:27:17 UTC (rev 119) @@ -82,7 +82,7 @@ @Length(max = LENGTH_MEDIUM_TEXT) @Column(unique = true) @NotEmpty - @Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES) + @Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES) private String ref; /** Manipulateur */ @@ -121,7 +121,8 @@ /** Commentaire pour la manip */ @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String complement; /** Détermine si la manip doit être confidentielle */ @@ -140,7 +141,7 @@ /** Résultats produits par le test */ @NotNull @OneToMany(mappedBy = "testBio", fetch = FetchType.LAZY, orphanRemoval = true) - @Cascade({ CascadeType.SAVE_UPDATE }) + @Cascade( { CascadeType.SAVE_UPDATE }) @ContainedIn private List<ResultatTestBio> resultats; @@ -148,19 +149,19 @@ * Constructeur */ public TestBio() { - resultats = new ArrayList<ResultatTestBio>(); + resultats = new ArrayList<ResultatTestBio>(); } /** {@inheritDoc} */ @Override public String toString() { - return ref; + return ref; } /** {@inheritDoc} */ @Override public int compareTo(TestBio testBio) { - return new BeanComparator("ref").compare(this, testBio); + return new BeanComparator("ref").compare(this, testBio); } /** @@ -168,10 +169,10 @@ * @return resultats */ public List<ResultatTestBio> getSortedResultats() { - // comme "@Sort(type = SortType.COMPARATOR, comparator = ResultatsOfTestBioComp.class)" ne rend pas une - // liste triée avec List, tri dans le getter - Collections.sort(resultats, new ResultatsOfTestBioComp()); - return resultats; + // comme "@Sort(type = SortType.COMPARATOR, comparator = ResultatsOfTestBioComp.class)" ne rend pas une + // liste triée avec List, tri dans le getter + Collections.sort(resultats, new ResultatsOfTestBioComp()); + return resultats; } /** @@ -179,7 +180,7 @@ * @return idTestBio */ public Integer getIdTestBio() { - return idTestBio; + return idTestBio; } /** @@ -187,7 +188,7 @@ * @param idTestBio idTestBio */ public void setIdTestBio(Integer idTestBio) { - this.idTestBio = idTestBio; + this.idTestBio = idTestBio; } /** @@ -195,7 +196,7 @@ * @return ref */ public String getRef() { - return ref; + return ref; } /** @@ -203,7 +204,7 @@ * @param ref ref */ public void setRef(String ref) { - this.ref = ref; + this.ref = ref; } /** @@ -211,7 +212,7 @@ * @return manipulateur */ public Personne getManipulateur() { - return manipulateur; + return manipulateur; } /** @@ -219,7 +220,7 @@ * @param manipulateur manipulateur */ public void setManipulateur(Personne manipulateur) { - this.manipulateur = manipulateur; + this.manipulateur = manipulateur; } /** @@ -227,7 +228,7 @@ * @return organismeTesteur */ public String getOrganismeTesteur() { - return organismeTesteur; + return organismeTesteur; } /** @@ -235,7 +236,7 @@ * @param organismeTesteur organismeTesteur */ public void setOrganismeTesteur(String organismeTesteur) { - this.organismeTesteur = organismeTesteur; + this.organismeTesteur = organismeTesteur; } /** @@ -243,7 +244,7 @@ * @return date */ public Date getDate() { - return date; + return date; } /** @@ -251,7 +252,7 @@ * @param date date */ public void setDate(Date date) { - this.date = date; + this.date = date; } /** @@ -259,7 +260,7 @@ * @return methode */ public MethodeTestBio getMethode() { - return methode; + return methode; } /** @@ -267,7 +268,7 @@ * @param methode methode */ public void setMethode(MethodeTestBio methode) { - this.methode = methode; + this.methode = methode; } /** @@ -275,7 +276,7 @@ * @return concMasseDefaut */ public BigDecimal getConcMasseDefaut() { - return concMasseDefaut; + return concMasseDefaut; } /** @@ -283,7 +284,7 @@ * @param concMasseDefaut concMasseDefaut */ public void setConcMasseDefaut(BigDecimal concMasseDefaut) { - this.concMasseDefaut = concMasseDefaut; + this.concMasseDefaut = concMasseDefaut; } /** @@ -291,7 +292,7 @@ * @return uniteConcMasseDefaut */ public UniteConcMasse getUniteConcMasseDefaut() { - return uniteConcMasseDefaut; + return uniteConcMasseDefaut; } /** @@ -299,7 +300,7 @@ * @param uniteConcMasseDefaut uniteConcMasseDefaut */ public void setUniteConcMasseDefaut(UniteConcMasse uniteConcMasseDefaut) { - this.uniteConcMasseDefaut = uniteConcMasseDefaut; + this.uniteConcMasseDefaut = uniteConcMasseDefaut; } /** @@ -307,7 +308,7 @@ * @return stadeDefaut */ public Stade getStadeDefaut() { - return stadeDefaut; + return stadeDefaut; } /** @@ -315,7 +316,7 @@ * @param stadeDefaut stadeDefaut */ public void setStadeDefaut(Stade stadeDefaut) { - this.stadeDefaut = stadeDefaut; + this.stadeDefaut = stadeDefaut; } /** @@ -323,7 +324,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -331,7 +332,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -339,7 +340,7 @@ * @return confidentiel */ public boolean isConfidentiel() { - return confidentiel; + return confidentiel; } /** @@ -347,7 +348,7 @@ * @param confidentiel confidentiel */ public void setConfidentiel(boolean confidentiel) { - this.confidentiel = confidentiel; + this.confidentiel = confidentiel; } /** @@ -355,7 +356,7 @@ * @return dateConfidentialite */ public Date getDateConfidentialite() { - return dateConfidentialite; + return dateConfidentialite; } /** @@ -363,7 +364,7 @@ * @param dateConfidentialite dateConfidentialite */ public void setDateConfidentialite(Date dateConfidentialite) { - this.dateConfidentialite = dateConfidentialite; + this.dateConfidentialite = dateConfidentialite; } /** @@ -371,7 +372,7 @@ * @return createur */ public Personne getCreateur() { - return createur; + return createur; } /** @@ -379,7 +380,7 @@ * @param createur createur */ public void setCreateur(Personne createur) { - this.createur = createur; + this.createur = createur; } /** @@ -387,7 +388,7 @@ * @return resultats */ public List<ResultatTestBio> getResultats() { - return resultats; + return resultats; } /** @@ -395,7 +396,7 @@ * @param resultats resultats */ public void setResultats(List<ResultatTestBio> resultats) { - this.resultats = resultats; + this.resultats = resultats; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeDocument.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeDocument.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeDocument.java 2013-02-18 07:27:17 UTC (rev 119) @@ -64,7 +64,8 @@ /** Document type description */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** If the type document represents an image ? */ @@ -74,25 +75,25 @@ /** {@inheritDoc} */ @Override public TypeDocument clone() throws CloneNotSupportedException { - TypeDocument clone = (TypeDocument) super.clone(); - clone.idTypeDocument = idTypeDocument; - clone.nom = nom; - clone.domaine = domaine; - clone.description = description; - clone.estImage = estImage; - return clone; + TypeDocument clone = (TypeDocument) super.clone(); + clone.idTypeDocument = idTypeDocument; + clone.nom = nom; + clone.domaine = domaine; + clone.description = description; + clone.estImage = estImage; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return this.nom; + return this.nom; } /** {@inheritDoc} */ @Override public int compareTo(TypeDocument typeExtrait) { - return new BeanComparator("nom").compare(this, typeExtrait); + return new BeanComparator("nom").compare(this, typeExtrait); } /** @@ -100,7 +101,7 @@ * @return idTypeDocument */ public Integer getIdTypeDocument() { - return idTypeDocument; + return idTypeDocument; } /** @@ -108,7 +109,7 @@ * @param idTypeDocument idTypeDocument */ public void setIdTypeDocument(Integer idTypeDocument) { - this.idTypeDocument = idTypeDocument; + this.idTypeDocument = idTypeDocument; } /** @@ -116,7 +117,7 @@ * @return nom */ public String getNom() { - return nom; + return nom; } /** @@ -124,7 +125,7 @@ * @param nom nom */ public void setNom(String nom) { - this.nom = nom; + this.nom = nom; } /** @@ -132,7 +133,7 @@ * @return domaine */ public String getDomaine() { - return domaine; + return domaine; } /** @@ -140,7 +141,7 @@ * @param domaine domaine */ public void setDomaine(String domaine) { - this.domaine = domaine; + this.domaine = domaine; } /** @@ -148,7 +149,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -156,7 +157,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -164,7 +165,7 @@ * @return estImage */ public Boolean getEstImage() { - return estImage; + return estImage; } /** @@ -172,7 +173,7 @@ * @param estImage estImage */ public void setEstImage(Boolean estImage) { - this.estImage = estImage; + this.estImage = estImage; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeExtrait.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeExtrait.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/TypeExtrait.java 2013-02-18 07:27:17 UTC (rev 119) @@ -60,7 +60,8 @@ /** Description du type d'extrait */ @NotEmpty @Lob - @Type(type="org.hibernate.type.StringClobType") // see HHH-6105 + @Type(type = "org.hibernate.type.StringClobType") + // see HHH-6105 private String description; /** Méthode d'extraction pour laquelle est défini le type d'extrait */ @@ -71,24 +72,24 @@ /** {@inheritDoc} */ @Override public TypeExtrait clone() throws CloneNotSupportedException { - TypeExtrait clone = (TypeExtrait) super.clone(); - clone.idTypeExtrait = idTypeExtrait; - clone.initiales = initiales; - clone.description = description; - clone.methodeExtraction = methodeExtraction; - return clone; + TypeExtrait clone = (TypeExtrait) super.clone(); + clone.idTypeExtrait = idTypeExtrait; + clone.initiales = initiales; + clone.description = description; + clone.methodeExtraction = methodeExtraction; + return clone; } /** {@inheritDoc} */ @Override public String toString() { - return this.initiales; + return this.initiales; } /** {@inheritDoc} */ @Override public int compareTo(TypeExtrait typeExtrait) { - return new BeanComparator("initiales").compare(this, typeExtrait); + return new BeanComparator("initiales").compare(this, typeExtrait); } /** @@ -96,7 +97,7 @@ * @return idTypeExtrait */ public Integer getIdTypeExtrait() { - return idTypeExtrait; + return idTypeExtrait; } /** @@ -104,7 +105,7 @@ * @param idTypeExtrait idTypeExtrait */ public void setIdTypeExtrait(Integer idTypeExtrait) { - this.idTypeExtrait = idTypeExtrait; + this.idTypeExtrait = idTypeExtrait; } /** @@ -112,7 +113,7 @@ * @return initiales */ public String getInitiales() { - return initiales; + return initiales; } /** @@ -120,7 +121,7 @@ * @param initiales initiales */ public void setInitiales(String initiales) { - this.initiales = initiales; + this.initiales = initiales; } /** @@ -128,7 +129,7 @@ * @return description */ public String getDescription() { - return description; + return description; } /** @@ -136,7 +137,7 @@ * @param description description */ public void setDescription(String description) { - this.description = description; + this.description = description; } /** @@ -144,7 +145,7 @@ * @return methodeExtraction */ public MethodeExtraction getMethodeExtraction() { - return methodeExtraction; + return methodeExtraction; } /** @@ -152,7 +153,7 @@ * @param methodeExtraction methodeExtraction */ public void setMethodeExtraction(MethodeExtraction methodeExtraction) { - this.methodeExtraction = methodeExtraction; + this.methodeExtraction = methodeExtraction; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Utilisateur.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Utilisateur.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/Utilisateur.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,10 +54,10 @@ * Types droits */ public enum TypeDroit implements Comparable<TypeDroit> { - /** Administrateur */ - ADMINISTRATEUR, - /** Utilisateur */ - UTILISATEUR + /** Administrateur */ + ADMINISTRATEUR, + /** Utilisateur */ + UTILISATEUR } /** Date de validité du compte */ @@ -88,7 +88,7 @@ * Constructeur */ public Utilisateur() { - super(); + super(); } /** @@ -96,7 +96,7 @@ * @return dateValiditeCompte */ public Date getDateValiditeCompte() { - return dateValiditeCompte; + return dateValiditeCompte; } /** @@ -104,7 +104,7 @@ * @param dateValiditeCompte dateValiditeCompte */ public void setDateValiditeCompte(Date dateValiditeCompte) { - this.dateValiditeCompte = dateValiditeCompte; + this.dateValiditeCompte = dateValiditeCompte; } /** @@ -112,7 +112,7 @@ * @return estValide */ public Boolean isValide() { - return estValide; + return estValide; } /** @@ -120,7 +120,7 @@ * @param estValide estValide */ public void setValide(Boolean estValide) { - this.estValide = estValide; + this.estValide = estValide; } /** @@ -128,7 +128,7 @@ * @return groupe */ public Groupe getGroupe() { - return groupe; + return groupe; } /** @@ -136,7 +136,7 @@ * @param groupe groupe */ public void setGroupe(Groupe groupe) { - this.groupe = groupe; + this.groupe = groupe; } /** @@ -144,7 +144,7 @@ * @return passwordHash */ public String getPasswordHash() { - return passwordHash; + return passwordHash; } /** @@ -152,7 +152,7 @@ * @param passwordHash passwordHash */ public void setPasswordHash(String passwordHash) { - this.passwordHash = passwordHash; + this.passwordHash = passwordHash; } /** @@ -160,7 +160,7 @@ * @return typeDroit */ public TypeDroit getTypeDroit() { - return typeDroit; + return typeDroit; } /** @@ -168,7 +168,7 @@ * @param typeDroit typeDroit */ public void setTypeDroit(TypeDroit typeDroit) { - this.typeDroit = typeDroit; + this.typeDroit = typeDroit; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/CampagnePersonneDroitsComp.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/CampagnePersonneDroitsComp.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/CampagnePersonneDroitsComp.java 2013-02-18 07:27:17 UTC (rev 119) @@ -43,7 +43,7 @@ /** {@inheritDoc} */ @Override public int compare(CampagnePersonneDroits obj1, CampagnePersonneDroits obj2) { - LOG.debug("compare personnes droit"); - return new BeanComparator("id.pk1").compare(obj1, obj2); + LOG.debug("compare personnes droit"); + return new BeanComparator("id.pk1").compare(obj1, obj2); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ExtraitsOfExtractionComp.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ExtraitsOfExtractionComp.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ExtraitsOfExtractionComp.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,6 +37,6 @@ /** {@inheritDoc} */ @Override public int compare(Extrait obj1, Extrait obj2) { - return new BeanComparator("typeExtrait.initiales").compare(obj1, obj2); + return new BeanComparator("typeExtrait.initiales").compare(obj1, obj2); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/FractionsOfPurificationComp.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/FractionsOfPurificationComp.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/FractionsOfPurificationComp.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,6 +39,6 @@ /** {@inheritDoc} */ @Override public int compare(Fraction obj1, Fraction obj2) { - return new BeanComparator("indice", new IntuitiveStringComparator<String>()).compare(obj1, obj2); + return new BeanComparator("indice", new IntuitiveStringComparator<String>()).compare(obj1, obj2); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/LotPersonneDroitsComp.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/LotPersonneDroitsComp.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/LotPersonneDroitsComp.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,9 +38,9 @@ /** {@inheritDoc} */ @Override public int compare(LotPersonneDroits obj1, LotPersonneDroits obj2) { - ComparatorChain comparatorChain = new ComparatorChain(); - comparatorChain.addComparator(new BeanComparator("id.pk1.campagne")); - comparatorChain.addComparator(new BeanComparator("id.pk1")); - return comparatorChain.compare(obj1, obj2); + ComparatorChain comparatorChain = new ComparatorChain(); + comparatorChain.addComparator(new BeanComparator("id.pk1.campagne")); + comparatorChain.addComparator(new BeanComparator("id.pk1")); + return comparatorChain.compare(obj1, obj2); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ResultatsOfTestBioComp.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ResultatsOfTestBioComp.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/comparators/ResultatsOfTestBioComp.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,6 +39,6 @@ /** {@inheritDoc} */ @Override public int compare(ResultatTestBio obj1, ResultatTestBio obj2) { - return new BeanComparator("repere", new IntuitiveStringComparator<String>()).compare(obj1, obj2); + return new BeanComparator("repere", new IntuitiveStringComparator<String>()).compare(obj1, obj2); } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/ProduitBridge.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/ProduitBridge.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/ProduitBridge.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,89 +48,71 @@ private static final Logger LOG = LoggerFactory.getLogger(ProduitBridge.class); @Override - public void set(String name, Object value, Document document, - LuceneOptions luceneOptions) { + public void set(String name, Object value, Document document, LuceneOptions luceneOptions) { - Produit produit = (Produit) value; - if (LOG.isDebugEnabled()) { - LOG.debug("Custom indexing of Produit entity : " + produit); - } + Produit produit = (Produit) value; + if (LOG.isDebugEnabled()) { + LOG.debug("Custom indexing of Produit entity : " + produit); + } - // commons information for all produit - document.add(new Field("ref", produit.getRef(), luceneOptions - .getStore(), luceneOptions.getIndex(), luceneOptions - .getTermVector())); - if (produit instanceof Extrait) { - if (LOG.isDebugEnabled()) { - LOG.debug("Custom indexing of Extrait entity"); - } - Extrait extrait = (Extrait) produit; - document.add(new Field("extraction.lot.ref", extrait - .getExtraction().getLot().getRef(), luceneOptions - .getStore(), luceneOptions.getIndex(), luceneOptions - .getTermVector())); - document.add(new Field("extraction.lot.specimen.embranchement", - extrait.getExtraction().getLot().getSpecimenRef() - .getEmbranchement(), luceneOptions.getStore(), - luceneOptions.getIndex(), luceneOptions.getTermVector())); - if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getFamille())) { - document.add(new Field("extraction.lot.specimen.famille", extrait - .getExtraction().getLot().getSpecimenRef().getFamille(), - luceneOptions.getStore(), luceneOptions.getIndex(), - luceneOptions.getTermVector())); - } - if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getGenre())) { - document.add(new Field("extraction.lot.specimen.genre", extrait - .getExtraction().getLot().getSpecimenRef().getGenre(), - luceneOptions.getStore(), luceneOptions.getIndex(), - luceneOptions.getTermVector())); - } - if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getEspece())) { - document.add(new Field("extraction.lot.specimen.expece", extrait - .getExtraction().getLot().getSpecimenRef().getEspece(), - luceneOptions.getStore(), luceneOptions.getIndex(), - luceneOptions.getTermVector())); - } - document.add(new Field("extraction.lot.campagne.nom", extrait - .getExtraction().getLot().getCampagne().getNom(), - luceneOptions.getStore(), luceneOptions.getIndex(), - luceneOptions.getTermVector())); - } else if (produit instanceof Fraction) { - if (LOG.isDebugEnabled()) { - LOG.debug("Custom indexing of Fraction entity"); - } - Fraction fraction = (Fraction) produit; - document.add(new Field("purification.lotSource.ref", fraction - .getPurification().getLotSource().getRef(), luceneOptions - .getStore(), luceneOptions.getIndex(), luceneOptions - .getTermVector())); - document.add(new Field( - "purification.lotSource.speciment.embranchement", fraction - .getPurification().getLotSource().getSpecimenRef() - .getEmbranchement(), luceneOptions.getStore(), - luceneOptions.getIndex(), luceneOptions.getTermVector())); - if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getFamille())) { - document.add(new Field("purification.lotSource.speciment.famille", - fraction.getPurification().getLotSource().getSpecimenRef() - .getFamille(), luceneOptions.getStore(), - luceneOptions.getIndex(), luceneOptions.getTermVector())); - } - if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getGenre())) { - document.add(new Field("purification.lotSource.speciment.genre", - fraction.getPurification().getLotSource().getSpecimenRef() - .getGenre(), luceneOptions.getStore(), - luceneOptions.getIndex(), luceneOptions.getTermVector())); - } - if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getEspece())) { - document.add(new Field("purification.lotSource.speciment.expece", - fraction.getPurification().getLotSource().getSpecimenRef() - .getEspece(), luceneOptions.getStore(), - luceneOptions.getIndex(), luceneOptions.getTermVector())); - } - document.add(new Field("purification.lotSource.campagne.nom", - fraction.getPurification().getLotSource().getCampagne() - .getNom(), luceneOptions.getStore(), luceneOptions - .getIndex(), luceneOptions.getTermVector())); - } + // commons information for all produit + document.add(new Field("ref", produit.getRef(), luceneOptions.getStore(), luceneOptions.getIndex(), + luceneOptions.getTermVector())); + if (produit instanceof Extrait) { + if (LOG.isDebugEnabled()) { + LOG.debug("Custom indexing of Extrait entity"); + } + Extrait extrait = (Extrait) produit; + document.add(new Field("extraction.lot.ref", extrait.getExtraction().getLot().getRef(), luceneOptions + .getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector())); + document.add(new Field("extraction.lot.specimen.embranchement", extrait.getExtraction().getLot() + .getSpecimenRef().getEmbranchement(), luceneOptions.getStore(), luceneOptions.getIndex(), + luceneOptions.getTermVector())); + if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getFamille())) { + document.add(new Field("extraction.lot.specimen.famille", extrait.getExtraction().getLot() + .getSpecimenRef().getFamille(), luceneOptions.getStore(), luceneOptions.getIndex(), + luceneOptions.getTermVector())); + } + if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getGenre())) { + document.add(new Field("extraction.lot.specimen.genre", extrait.getExtraction().getLot() + .getSpecimenRef().getGenre(), luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions + .getTermVector())); + } + if (StringUtils.isNotBlank(extrait.getExtraction().getLot().getSpecimenRef().getEspece())) { + document.add(new Field("extraction.lot.specimen.expece", extrait.getExtraction().getLot() + .getSpecimenRef().getEspece(), luceneOptions.getStore(), luceneOptions.getIndex(), + luceneOptions.getTermVector())); + } + document.add(new Field("extraction.lot.campagne.nom", extrait.getExtraction().getLot().getCampagne() + .getNom(), luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector())); + } else if (produit instanceof Fraction) { + if (LOG.isDebugEnabled()) { + LOG.debug("Custom indexing of Fraction entity"); + } + Fraction fraction = (Fraction) produit; + document.add(new Field("purification.lotSource.ref", fraction.getPurification().getLotSource().getRef(), + luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector())); + document.add(new Field("purification.lotSource.speciment.embranchement", fraction.getPurification() + .getLotSource().getSpecimenRef().getEmbranchement(), luceneOptions.getStore(), luceneOptions + .getIndex(), luceneOptions.getTermVector())); + if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getFamille())) { + document.add(new Field("purification.lotSource.speciment.famille", fraction.getPurification() + .getLotSource().getSpecimenRef().getFamille(), luceneOptions.getStore(), luceneOptions + .getIndex(), luceneOptions.getTermVector())); + } + if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getGenre())) { + document.add(new Field("purification.lotSource.speciment.genre", fraction.getPurification() + .getLotSource().getSpecimenRef().getGenre(), luceneOptions.getStore(), + luceneOptions.getIndex(), luceneOptions.getTermVector())); + } + if (StringUtils.isNotBlank(fraction.getPurification().getLotSource().getSpecimenRef().getEspece())) { + document.add(new Field("purification.lotSource.speciment.expece", fraction.getPurification() + .getLotSource().getSpecimenRef().getEspece(), luceneOptions.getStore(), luceneOptions + .getIndex(), luceneOptions.getTermVector())); + } + document.add(new Field("purification.lotSource.campagne.nom", fraction.getPurification().getLotSource() + .getCampagne().getNom(), luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions + .getTermVector())); + } } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/UtilisateurSearchFilter.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/UtilisateurSearchFilter.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/UtilisateurSearchFilter.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,46 +57,46 @@ protected Utilisateur utilisateur; public Utilisateur getUtilisateur() { - return utilisateur; + return utilisateur; } public void setUtilisateur(Utilisateur utilisateur) { - this.utilisateur = utilisateur; + this.utilisateur = utilisateur; } @Key public FilterKey getKey() { - StandardFilterKey key = new StandardFilterKey(); - key.addParameter( utilisateur ); - return key; + StandardFilterKey key = new StandardFilterKey(); + key.addParameter(utilisateur); + return key; } @Override public DocIdSet getDocIdSet(IndexReader reader) throws IOException { - OpenBitSet bitSet = new OpenBitSet(reader.maxDoc()); - - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - if (LOG.isDebugEnabled()) { - LOG.debug("Filtering term docs for administrator"); - } - // all docs - for (int idx=0; idx < bitSet.length(); idx++) { - if (!reader.isDeleted(idx)) { - bitSet.set(idx); - } - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Filtering term docs for utilisateur"); - } - // only docs matching terms - TermDocs termDocs = reader.termDocs(new Term("createur.idPersonne", String - .valueOf(utilisateur.getIdPersonne()))); - while (termDocs.next()) { - bitSet.set(termDocs.doc()); - } - } - - return bitSet; + OpenBitSet bitSet = new OpenBitSet(reader.maxDoc()); + + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + if (LOG.isDebugEnabled()) { + LOG.debug("Filtering term docs for administrator"); + } + // all docs + for (int idx = 0; idx < bitSet.length(); idx++) { + if (!reader.isDeleted(idx)) { + bitSet.set(idx); + } + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("Filtering term docs for utilisateur"); + } + // only docs matching terms + TermDocs termDocs = reader.termDocs(new Term("createur.idPersonne", String.valueOf(utilisateur + .getIdPersonne()))); + while (termDocs.next()) { + bitSet.set(termDocs.doc()); + } + } + + return bitSet; } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/AbstractModel.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/AbstractModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/AbstractModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -73,7 +73,7 @@ * @throws UnexpectedException If it does not exist */ public final Field getIdField() { - return getIdField(this.getClass()); + return getIdField(this.getClass()); } /** @@ -84,22 +84,22 @@ */ @SuppressWarnings("unchecked") public final static Field getIdField(final Class<? extends AbstractModel> clazz) { - AssertTools.assertNotNull(clazz); - Field field = null; - String modelClassName = clazz.getName(); - field = ID_FIELDS.get(modelClassName); + AssertTools.assertNotNull(clazz); + Field field = null; + String modelClassName = clazz.getName(); + field = ID_FIELDS.get(modelClassName); - if (field == null) { - try { - field = BeanTools.getAnnotatedPrivateField(clazz, Id.class, EmbeddedId.class); - } catch (NoSuchFieldException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - ID_FIELDS.put(modelClassName, field); - } + if (field == null) { + try { + field = BeanTools.getAnnotatedPrivateField(clazz, Id.class, EmbeddedId.class); + } catch (NoSuchFieldException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + ID_FIELDS.put(modelClassName, field); + } - return field; + return field; } /** @@ -108,7 +108,7 @@ * @throws UnexpectedException If the field does not exist */ public final Serializable getIdValue() { - return (Serializable) BeanTools.getValue(this, AccessType.GETTER, getIdField().getName()); + return (Serializable) BeanTools.getValue(this, AccessType.GETTER, getIdField().getName()); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/CompositeId.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/CompositeId.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/utils/CompositeId.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,22 +52,22 @@ /** {@inheritDoc} */ @Override public CompositeId<PK1, PK2> clone() throws CloneNotSupportedException { - CompositeId<PK1, PK2> clone = GenericsTools.cast(super.clone()); - clone.pk1 = pk1; - clone.pk2 = pk2; - return clone; + CompositeId<PK1, PK2> clone = GenericsTools.cast(super.clone()); + clone.pk1 = pk1; + clone.pk2 = pk2; + return clone; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { - return BeanTools.equals(this, obj, AccessType.GETTER, "pk1", "pk2"); + return BeanTools.equals(this, obj, AccessType.GETTER, "pk1", "pk2"); } /** {@inheritDoc} */ @Override public int hashCode() { - return BeanTools.hashCode(this, pk1, pk2); + return BeanTools.hashCode(this, pk1, pk2); } /** @@ -75,7 +75,7 @@ * @return pk1 */ public PK1 getPk1() { - return pk1; + return pk1; } /** @@ -83,7 +83,7 @@ * @param pk1 pk1 */ public void setPk1(PK1 pk1) { - this.pk1 = pk1; + this.pk1 = pk1; } /** @@ -91,7 +91,7 @@ * @return pk2 */ public PK2 getPk2() { - return pk2; + return pk2; } /** @@ -99,7 +99,7 @@ * @param pk2 pk2 */ public void setPk2(PK2 pk2) { - this.pk2 = pk2; + this.pk2 = pk2; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueField.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueField.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueField.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * given to this annotation. * @author Adrien Cheype */ -@Target({ ElementType.TYPE }) +@Target( { ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = CollectionUniqueFieldValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueFieldValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueFieldValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CollectionUniqueFieldValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,20 +51,20 @@ /** {@inheritDoc} */ @Override public void initialize(CollectionUniqueField annotation) { - this.fieldName = annotation.fieldName(); - this.pathToCollection = annotation.pathToCollection(); + this.fieldName = annotation.fieldName(); + this.pathToCollection = annotation.pathToCollection(); } /** {@inheritDoc} */ @Override public boolean isValid(Object value, ConstraintValidatorContext constraintContext) { - Collection<Object> collection = GenericsTools.cast(BeanTools.getValueFromPath(value, AccessType.GETTER, - this.pathToCollection)); - Object propertyVal = BeanTools.getValue(value, AccessType.GETTER, fieldName); + Collection<Object> collection = GenericsTools.cast(BeanTools.getValueFromPath(value, AccessType.GETTER, + this.pathToCollection)); + Object propertyVal = BeanTools.getValue(value, AccessType.GETTER, fieldName); - // each value of the field must have one occurrence in the collection - return (propertyVal == null) - || CollectionTools.countWithValue(collection, fieldName, AccessType.GETTER, propertyVal) == 1; + // each value of the field must have one occurrence in the collection + return (propertyVal == null) + || CollectionTools.countWithValue(collection, fieldName, AccessType.GETTER, propertyVal) == 1; } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCode.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCode.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCode.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = CountryCodeValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCodeValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCodeValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/CountryCodeValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,12 +37,12 @@ /** {@inheritDoc} */ @Override public void initialize(CountryCode annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(String countryCode, ConstraintValidatorContext constraintContext) { - return countryCode == null || DataContext.COUNTRY_CODES.contains(countryCode); + return countryCode == null || DataContext.COUNTRY_CODES.contains(countryCode); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueField.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueField.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueField.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,7 +38,7 @@ * given to this annotation. * @author Adrien Cheype */ -@Target({ ElementType.TYPE }) +@Target( { ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = DbUniqueFieldValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueFieldValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueFieldValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/DbUniqueFieldValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -59,31 +59,31 @@ /** {@inheritDoc} */ @Override public void initialize(DbUniqueField annotation) { - this.fieldName = annotation.fieldName(); - this.entity = annotation.entity(); + this.fieldName = annotation.fieldName(); + this.entity = annotation.entity(); } /** {@inheritDoc} */ @Override public boolean isValid(Object value, ConstraintValidatorContext constraintContext) { - AssertTools.assertNotNull(value); - Serializable fieldVal = (Serializable) BeanTools.getValue(value, AccessType.GETTER, fieldName); - if (fieldVal == null) { - return false; - } + AssertTools.assertNotNull(value); + Serializable fieldVal = (Serializable) BeanTools.getValue(value, AccessType.GETTER, fieldName); + if (fieldVal == null) { + return false; + } - // valid if it doesn't exist different value or if it exists but with the same id (so same row in the db) - if (!dao.exists(entity, fieldName, fieldVal)) { - return true; - } - AbstractModel modelForm = (AbstractModel) value; - AbstractModel modelWithSameVal; - try { - modelWithSameVal = dao.read(entity, fieldName, fieldVal); - } catch (DataNotFoundException e) { - return true; // never call, cover by dao.exists... - } - return modelForm.getIdValue().equals(modelWithSameVal.getIdValue()); + // valid if it doesn't exist different value or if it exists but with the same id (so same row in the db) + if (!dao.exists(entity, fieldName, fieldVal)) { + return true; + } + AbstractModel modelForm = (AbstractModel) value; + AbstractModel modelWithSameVal; + try { + modelWithSameVal = dao.read(entity, fieldName, fieldVal); + } catch (DataNotFoundException e) { + return true; // never call, cover by dao.exists... + } + return modelForm.getIdValue().equals(modelWithSameVal.getIdValue()); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Latitude.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Latitude.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Latitude.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = LatitudeValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientation.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientation.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientation.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = LatitudeOrientationValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientationValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientationValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeOrientationValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -40,13 +40,13 @@ /** {@inheritDoc} */ @Override public void initialize(LatitudeOrientation annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(Character latitudeOrientation, ConstraintValidatorContext constraintContext) { - return latitudeOrientation == null - || Arrays.asList(CoordTools.LATITUDE_ORIENTATIONS).contains(latitudeOrientation); + return latitudeOrientation == null + || Arrays.asList(CoordTools.LATITUDE_ORIENTATIONS).contains(latitudeOrientation); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LatitudeValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,12 +38,12 @@ /** {@inheritDoc} */ @Override public void initialize(Latitude annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(String latitude, ConstraintValidatorContext constraintContext) { - return latitude == null || CoordTools.validateLatitude(latitude); + return latitude == null || CoordTools.validateLatitude(latitude); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Longitude.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Longitude.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Longitude.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = LongitudeValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientation.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientation.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientation.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = LongitudeOrientationValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientationValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientationValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeOrientationValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -40,13 +40,13 @@ /** {@inheritDoc} */ @Override public void initialize(LongitudeOrientation annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(Character longitudeOrientation, ConstraintValidatorContext constraintContext) { - return longitudeOrientation == null - || Arrays.asList(CoordTools.LONGITUDE_ORIENTATIONS).contains(longitudeOrientation); + return longitudeOrientation == null + || Arrays.asList(CoordTools.LONGITUDE_ORIENTATIONS).contains(longitudeOrientation); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/LongitudeValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,12 +38,12 @@ /** {@inheritDoc} */ @Override public void initialize(Longitude annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(String longitude, ConstraintValidatorContext constraintContext) { - return longitude == null || CoordTools.validateLongitude(longitude); + return longitude == null || CoordTools.validateLongitude(longitude); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/QueryConstraintValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/QueryConstraintValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/QueryConstraintValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -30,7 +30,6 @@ import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.Query; @@ -54,6 +53,7 @@ /** Hql query to request */ private String hql; + /** The collection of named parameters in the HQL statement */ private String[] params; @@ -66,8 +66,8 @@ */ @Override public void initialize(QueryConstraint queryConstraint) { - this.hql = queryConstraint.hql(); - this.params = createParameterList(this.hql); + this.hql = queryConstraint.hql(); + this.params = createParameterList(this.hql); } /** @@ -75,30 +75,30 @@ */ @Override public boolean isValid(String domainObject, ConstraintValidatorContext context) { - BeanWrapper beanWrapper = new BeanWrapperImpl(domainObject); + BeanWrapper beanWrapper = new BeanWrapperImpl(domainObject); - if (sessionFactory != null) { - LOG.debug("Enabled - Validating constraint with: "); - LOG.debug(hql); + if (sessionFactory != null) { + LOG.debug("Enabled - Validating constraint with: "); + LOG.debug(hql); - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - Query query = session.createQuery(this.hql); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + Query query = session.createQuery(this.hql); - for (String parameterName : this.params) { - query.setParameter(parameterName, beanWrapper.getPropertyValue(parameterName)); - } + for (String parameterName : this.params) { + query.setParameter(parameterName, beanWrapper.getPropertyValue(parameterName)); + } - boolean result = (Long) query.uniqueResult() == 0; - // boolean result = query.list().size() == 0; + boolean result = (Long) query.uniqueResult() == 0; + // boolean result = query.list().size() == 0; - tx.commit(); - session.close(); + tx.commit(); + session.close(); - return result; - } + return result; + } - return true; + return true; } /** @@ -107,13 +107,13 @@ * @return an array of all the named parameters (of the form :name) found in the provided string */ private String[] createParameterList(final String query) { - final Matcher matcher = Pattern.compile(":[^\\s]*").matcher(query); - List<String> paramList = new ArrayList<String>(); - while (matcher.find()) { - paramList.add(this.hql.substring(matcher.start() + 1, matcher.end())); - } + final Matcher matcher = Pattern.compile(":[^\\s]*").matcher(query); + List<String> paramList = new ArrayList<String>(); + while (matcher.find()) { + paramList.add(this.hql.substring(matcher.start() + 1, matcher.end())); + } - return paramList.toArray(new String[paramList.size()]); + return paramList.toArray(new String[paramList.size()]); } // public boolean isValid(String domainObject) { Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Referentiel.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Referentiel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/Referentiel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = ReferentielValidator.class) @Documented Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/ReferentielValidator.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/ReferentielValidator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/ReferentielValidator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,12 +37,12 @@ /** {@inheritDoc} */ @Override public void initialize(Referentiel annotation) { - // + // } /** {@inheritDoc} */ @Override public boolean isValid(Integer referentiel, ConstraintValidatorContext constraintContext) { - return referentiel == null || DataContext.REFERENTIELS.keySet().contains(referentiel); + return referentiel == null || DataContext.REFERENTIELS.keySet().contains(referentiel); } } \ No newline at end of file Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorEventListener.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorEventListener.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorEventListener.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,10 +52,10 @@ * Operation */ private enum Operation { - /** Insert */ - INSERT, - /** Update */ - UPDATE; + /** Insert */ + INSERT, + /** Update */ + UPDATE; } /** Logger */ @@ -69,22 +69,22 @@ * @param factory Validator factory */ public ModelValidatorEventListener(ValidatorFactory factory) { - AssertTools.assertNotNull(factory); - validator = factory.getValidator(); + AssertTools.assertNotNull(factory); + validator = factory.getValidator(); } /** {@inheritDoc} */ @Override public boolean onPreInsert(PreInsertEvent event) { - validate(event, Operation.INSERT); - return false; + validate(event, Operation.INSERT); + return false; } /** {@inheritDoc} */ @Override public boolean onPreUpdate(PreUpdateEvent event) { - validate(event, Operation.UPDATE); - return false; + validate(event, Operation.UPDATE); + return false; } /** @@ -93,17 +93,17 @@ * @param operation Operation */ private void validate(AbstractPreDatabaseOperationEvent event, Operation operation) { - Object o = event.getEntity(); - if (event.getEntity() != null && event.getPersister().getEntityMode() == EntityMode.POJO) { - Set<ConstraintViolation<Object>> violations = validator.validate(o); - if (!violations.isEmpty()) { - LOG.error("Validation before " + operation.name() + " " + o.getClass().getName() + ":"); - for (ConstraintViolation<Object> violation : violations) { - LOG.error("- " + violation.getPropertyPath() + ": " + violation.getMessage()); - } - throw new ConstraintViolationException("Validation failed before " + operation.name() + " " - + o.getClass().getName(), new HashSet<ConstraintViolation<?>>(violations)); - } - } + Object o = event.getEntity(); + if (event.getEntity() != null && event.getPersister().getEntityMode() == EntityMode.POJO) { + Set<ConstraintViolation<Object>> violations = validator.validate(o); + if (!violations.isEmpty()) { + LOG.error("Validation before " + operation.name() + " " + o.getClass().getName() + ":"); + for (ConstraintViolation<Object> violation : violations) { + LOG.error("- " + violation.getPropertyPath() + ": " + violation.getMessage()); + } + throw new ConstraintViolationException("Validation failed before " + operation.name() + " " + + o.getClass().getName(), new HashSet<ConstraintViolation<?>>(violations)); + } + } } } Modified: trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorImpl.java =================================================================== --- trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/validation/utils/ModelValidatorImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -75,81 +75,80 @@ * @param messageSourceAccessor Message source accessor */ public ModelValidatorImpl(ValidatorFactory validatorFactory, MessageSourceAccessor... messageSourceAccessor) { - AssertTools.assertNotNull(validatorFactory); - messageInterpolator = validatorFactory.getMessageInterpolator(); - validator = validatorFactory.getValidator(); - messageSources = messageSourceAccessor; + AssertTools.assertNotNull(validatorFactory); + messageInterpolator = validatorFactory.getMessageInterpolator(); + validator = validatorFactory.getValidator(); + messageSources = messageSourceAccessor; } /** {@inheritDoc} */ @Override public <M extends AbstractModel> void debug(Class<M> modelClass, M model) { - if (LOG.isDebugEnabled()) { - for (ConstraintViolation<M> violation : validator.validate(model)) { - LOG.debug(violation.getMessage()); - } - } + if (LOG.isDebugEnabled()) { + for (ConstraintViolation<M> violation : validator.validate(model)) { + LOG.debug(violation.getMessage()); + } + } } /** {@inheritDoc} */ @Override public <M> List<String> validate(M model, Locale locale, String... properties) { - Set<ConstraintViolation<M>> violations = validate(model, properties); - List<String> violationMessages = new ArrayList<String>(violations.size()); - for (final ConstraintViolation<M> violation : violations) { - // Lookup in the bean class - Class<?> clazz = violation.getRootBeanClass(); - // LOG.debug("clazz :" + clazz); - String label = null; - String labelDefault; - // LOG.debug("getPropertyPath :" + violation.getPropertyPath().toString()); - if (StringUtils.isEmpty(violation.getPropertyPath().toString())) { - labelDefault = getMessage(clazz.getSimpleName(), locale); - } else { - labelDefault = String - .format(PATTERN_ERROR_PROPERTY, clazz.getSimpleName(), violation.getPropertyPath()); - } - // LOG.debug("labelDefault :" + labelDefault); - try { - label = getMessage(labelDefault, locale); - } catch (NoSuchMessageException e) { - // - } - // LOG.debug("label :" + label); - // Lookup in the bean superclasses - while (label == null && !Object.class.equals(clazz)) { - clazz = clazz.getSuperclass(); - try { - if (StringUtils.isEmpty(violation.getPropertyPath().toString())) { - getMessage(clazz.getSimpleName(), locale); - } else { - getMessage( - String.format(PATTERN_ERROR_PROPERTY, clazz.getSimpleName(), - violation.getPropertyPath()), locale); - } - } catch (NoSuchMessageException e) { - // - } - } - if (label == null) { - label = labelDefault; - } + Set<ConstraintViolation<M>> violations = validate(model, properties); + List<String> violationMessages = new ArrayList<String>(violations.size()); + for (final ConstraintViolation<M> violation : violations) { + // Lookup in the bean class + Class<?> clazz = violation.getRootBeanClass(); + // LOG.debug("clazz :" + clazz); + String label = null; + String labelDefault; + // LOG.debug("getPropertyPath :" + violation.getPropertyPath().toString()); + if (StringUtils.isEmpty(violation.getPropertyPath().toString())) { + labelDefault = getMessage(clazz.getSimpleName(), locale); + } else { + labelDefault = String + .format(PATTERN_ERROR_PROPERTY, clazz.getSimpleName(), violation.getPropertyPath()); + } + // LOG.debug("labelDefault :" + labelDefault); + try { + label = getMessage(labelDefault, locale); + } catch (NoSuchMessageException e) { + // + } + // LOG.debug("label :" + label); + // Lookup in the bean superclasses + while (label == null && !Object.class.equals(clazz)) { + clazz = clazz.getSuperclass(); + try { + if (StringUtils.isEmpty(violation.getPropertyPath().toString())) { + getMessage(clazz.getSimpleName(), locale); + } else { + getMessage(String.format(PATTERN_ERROR_PROPERTY, clazz.getSimpleName(), violation + .getPropertyPath()), locale); + } + } catch (NoSuchMessageException e) { + // + } + } + if (label == null) { + label = labelDefault; + } - violationMessages.add(String.format(PATTERN_ERROR_MESSAGE, label, - messageInterpolator.interpolate(violation.getMessageTemplate(), new Context() { - @Override - public ConstraintDescriptor<?> getConstraintDescriptor() { - return violation.getConstraintDescriptor(); - } + violationMessages.add(String.format(PATTERN_ERROR_MESSAGE, label, messageInterpolator.interpolate(violation + .getMessageTemplate(), new Context() { + @Override + public ConstraintDescriptor<?> getConstraintDescriptor() { + return violation.getConstraintDescriptor(); + } - @Override - public Object getValidatedValue() { - return violation.getInvalidValue(); - } - }, locale))); - } + @Override + public Object getValidatedValue() { + return violation.getInvalidValue(); + } + }, locale))); + } - return violationMessages; + return violationMessages; } /** @@ -160,14 +159,14 @@ * @return Constraint violations (not null) */ private <M> Set<ConstraintViolation<M>> validate(M model, String... properties) { - if (properties == null || properties.length == 0) { - return validator.validate(model); - } - Set<ConstraintViolation<M>> violations = new HashSet<ConstraintViolation<M>>(); - for (String property : properties) { - violations.addAll(validator.validateProperty(model, property)); - } - return violations; + if (properties == null || properties.length == 0) { + return validator.validate(model); + } + Set<ConstraintViolation<M>> violations = new HashSet<ConstraintViolation<M>>(); + for (String property : properties) { + violations.addAll(validator.validateProperty(model, property)); + } + return violations; } /** @@ -177,13 +176,13 @@ * @return The corresponding msg, null if no such key */ private String getMessage(String key, Locale locale) { - String msg = null; - int i = 0; - while (msg == null && i < messageSources.length) { - MessageSourceAccessor curMsgSource = messageSources[i]; - msg = curMsgSource.getMessage(key, null, null, locale); - i++; - } - return msg; + String msg = null; + int i = 0; + while (msg == null && i < messageSources.length) { + MessageSourceAccessor curMsgSource = messageSources[i]; + msg = curMsgSource.getMessage(key, null, null, locale); + i++; + } + return msg; } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/AbstractDataTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/AbstractDataTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/AbstractDataTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -50,6 +50,6 @@ */ @Before public void setUp() { - applicationContext.getAutowireCapableBeanFactory().autowireBean(this); + applicationContext.getAutowireCapableBeanFactory().autowireBean(this); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/DataContextTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/DataContextTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/DataContextTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,6 +44,6 @@ */ @Test public void serviceMessageSource() { - Assert.assertEquals("Prénom", serviceMessageSource.getMessage("Personne.prenom")); + Assert.assertEquals("Prénom", serviceMessageSource.getMessage("Personne.prenom")); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/SchemaExporter.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/SchemaExporter.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/SchemaExporter.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,16 +37,16 @@ @Test public void exportSchema() throws IOException { - LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); - sessionFactoryBean.setPackagesToScan(new String[] { "nc.ird.cantharella.data.model" }); - Properties hibernateProperties = new Properties(); - // Hibernate: basic - hibernateProperties.setProperty(Environment.DIALECT, PostgreSQL82Dialect.class.getName()); - hibernateProperties.setProperty(Environment.SHOW_SQL, "false"); - sessionFactoryBean.setHibernateProperties(hibernateProperties); - sessionFactoryBean.afterPropertiesSet(); - Configuration configuration = sessionFactoryBean.getConfiguration(); - SchemaExport schemaExport = new SchemaExport(configuration); - schemaExport.create(true, false); + LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); + sessionFactoryBean.setPackagesToScan(new String[] { "nc.ird.cantharella.data.model" }); + Properties hibernateProperties = new Properties(); + // Hibernate: basic + hibernateProperties.setProperty(Environment.DIALECT, PostgreSQL82Dialect.class.getName()); + hibernateProperties.setProperty(Environment.SHOW_SQL, "false"); + sessionFactoryBean.setHibernateProperties(hibernateProperties); + sessionFactoryBean.afterPropertiesSet(); + Configuration configuration = sessionFactoryBean.getConfiguration(); + SchemaExport schemaExport = new SchemaExport(configuration); + schemaExport.create(true, false); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/GenericDaoTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/GenericDaoTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/GenericDaoTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -46,7 +46,7 @@ */ @Test(expected = SQLGrammarException.class) public void execute() throws DataConstraintException { - dao.execute("SELECT * FROM Foo"); + dao.execute("SELECT * FROM Foo"); } /** @@ -54,6 +54,6 @@ */ @Test public void test() { - Assert.assertNotNull(dao); + Assert.assertNotNull(dao); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/SpringTransactionTestAppender.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/SpringTransactionTestAppender.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/SpringTransactionTestAppender.java 2013-02-18 07:27:17 UTC (rev 119) @@ -34,7 +34,7 @@ * Constructor */ public SpringTransactionTestAppender() { - super(TransactionInterceptor.class); + super(TransactionInterceptor.class); } /** @@ -43,7 +43,7 @@ * @return - */ public boolean isTransactionOpened(@SuppressWarnings("rawtypes") Class forClass, String forMethod) { - return containsExactSingleLogRecord("Getting transaction for [" + forClass.getName() + "." + forMethod + "]"); + return containsExactSingleLogRecord("Getting transaction for [" + forClass.getName() + "." + forMethod + "]"); } /** @@ -52,7 +52,7 @@ * @return - */ public boolean isTransactionCompleted(@SuppressWarnings("rawtypes") Class forClass, String forMethod) { - return containsExactSingleLogRecord("Completing transaction for [" + forClass.getName() + "." + forMethod + "]"); + return containsExactSingleLogRecord("Completing transaction for [" + forClass.getName() + "." + forMethod + "]"); } /** @@ -61,8 +61,8 @@ * @return - */ public boolean isTransactionRollbacked(@SuppressWarnings("rawtypes") Class forClass, String forMethod) { - return containsSingleLogRecord("Completing transaction for [" + forClass.getName() + "." + forMethod - + "] after exception"); + return containsSingleLogRecord("Completing transaction for [" + forClass.getName() + "." + forMethod + + "] after exception"); } } \ No newline at end of file Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/TestAppender.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/TestAppender.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/dao/utils/TestAppender.java 2013-02-18 07:27:17 UTC (rev 119) @@ -40,11 +40,14 @@ public class TestAppender extends AppenderSkeleton { /** Logger */ private static org.slf4j.Logger log = LoggerFactory.getLogger(TestAppender.class); + /** */ @SuppressWarnings("rawtypes") private final Class[] monitoredClasses; + /** */ private final LoggerInfo[] backedUpLoggers; + /** */ private final List<LoggingEvent> events = new ArrayList<LoggingEvent>(); @@ -53,7 +56,7 @@ * @param monitoredClass - */ public TestAppender(@SuppressWarnings("rawtypes") Class monitoredClass) { - this(new Class[] { monitoredClass }); + this(new Class[] { monitoredClass }); } /** @@ -61,51 +64,51 @@ * @param monitoredClasses - */ public TestAppender(@SuppressWarnings("rawtypes") Class[] monitoredClasses) { - super(); - this.monitoredClasses = monitoredClasses; - if (log.isInfoEnabled()) { - log.info("***************************************************************"); - log.info(" APPENDING TEST CONTROLLED LOGGING ENVIRONMENT "); - log.info("***************************************************************"); - } - backedUpLoggers = new LoggerInfo[monitoredClasses.length]; - for (int i = 0; i < monitoredClasses.length; i++) { - @SuppressWarnings("rawtypes") - Class monitoredClass = monitoredClasses[i]; - Logger logger = LogManager.getLogger(monitoredClass); - backedUpLoggers[i] = new LoggerInfo(logger.getLevel(), logger.getAdditivity()); - logger.setLevel(Level.TRACE); - logger.addAppender(this); - logger.setAdditivity(true); - } + super(); + this.monitoredClasses = monitoredClasses; + if (log.isInfoEnabled()) { + log.info("***************************************************************"); + log.info(" APPENDING TEST CONTROLLED LOGGING ENVIRONMENT "); + log.info("***************************************************************"); + } + backedUpLoggers = new LoggerInfo[monitoredClasses.length]; + for (int i = 0; i < monitoredClasses.length; i++) { + @SuppressWarnings("rawtypes") + Class monitoredClass = monitoredClasses[i]; + Logger logger = LogManager.getLogger(monitoredClass); + backedUpLoggers[i] = new LoggerInfo(logger.getLevel(), logger.getAdditivity()); + logger.setLevel(Level.TRACE); + logger.addAppender(this); + logger.setAdditivity(true); + } } /** * */ public void clearLogChanges() { - for (int i = 0; i < monitoredClasses.length; i++) { - @SuppressWarnings("rawtypes") - Class monitoredClass = monitoredClasses[i]; - Logger logger = LogManager.getLogger(monitoredClass); - logger.setLevel(backedUpLoggers[i].getOriginalLevel()); - logger.setAdditivity(backedUpLoggers[i].isOriginalAdditivity()); - logger.removeAppender(this); - } - if (log.isInfoEnabled()) { - log.info("***************************************************************"); - log.info(" REMOVED TEST CONTROLLED LOGGING ENVIRONMENT "); - log.info("***************************************************************"); - } + for (int i = 0; i < monitoredClasses.length; i++) { + @SuppressWarnings("rawtypes") + Class monitoredClass = monitoredClasses[i]; + Logger logger = LogManager.getLogger(monitoredClass); + logger.setLevel(backedUpLoggers[i].getOriginalLevel()); + logger.setAdditivity(backedUpLoggers[i].isOriginalAdditivity()); + logger.removeAppender(this); + } + if (log.isInfoEnabled()) { + log.info("***************************************************************"); + log.info(" REMOVED TEST CONTROLLED LOGGING ENVIRONMENT "); + log.info("***************************************************************"); + } } /** {@inheritDoc} */ @Override protected void append(LoggingEvent event) { - synchronized (events) { - events.add(event); - System.out.println(">>> Capturing : " + event.getMessage()); - } + synchronized (events) { + events.add(event); + System.out.println(">>> Capturing : " + event.getMessage()); + } } /** @@ -113,14 +116,14 @@ * @return - */ public int countLogRecord(String messagePart) { - int counter = 0; - for (LoggingEvent event : events) { - String message = (String) event.getMessage(); - if (message != null && message.indexOf(messagePart) > -1) { - counter++; - } - } - return counter; + int counter = 0; + for (LoggingEvent event : events) { + String message = (String) event.getMessage(); + if (message != null && message.indexOf(messagePart) > -1) { + counter++; + } + } + return counter; } /** @@ -128,14 +131,14 @@ * @return - */ public int countExactLogRecord(String comparedMessage) { - int counter = 0; - for (LoggingEvent event : events) { - String message = (String) event.getMessage(); - if (message != null && message.equals(comparedMessage)) { - counter++; - } - } - return counter; + int counter = 0; + for (LoggingEvent event : events) { + String message = (String) event.getMessage(); + if (message != null && message.equals(comparedMessage)) { + counter++; + } + } + return counter; } /** @@ -143,7 +146,7 @@ * @return - */ public boolean containsLogRecord(String messagePart) { - return countLogRecord(messagePart) > 0; + return countLogRecord(messagePart) > 0; } /** @@ -151,7 +154,7 @@ * @return - */ public boolean containsSingleLogRecord(String messagePart) { - return countLogRecord(messagePart) == 1; + return countLogRecord(messagePart) == 1; } /** @@ -159,7 +162,7 @@ * @return - */ public boolean containsExactLogRecord(String completeMessage) { - return countExactLogRecord(completeMessage) > 0; + return countExactLogRecord(completeMessage) > 0; } /** @@ -167,54 +170,55 @@ * @return - */ public boolean containsExactSingleLogRecord(String completeMessage) { - return countExactLogRecord(completeMessage) == 1; + return countExactLogRecord(completeMessage) == 1; } /** {@inheritDoc} */ @Override public void close() { - events.clear(); - clearLogChanges(); + events.clear(); + clearLogChanges(); } /** {@inheritDoc} */ @Override public boolean requiresLayout() { - return false; + return false; } /** * @author Jan Novotný */ private class LoggerInfo { - /** */ - Level originalLevel; - /** */ - boolean originalAdditivity; + /** */ + Level originalLevel; - /** - * Constructor - * @param originalLevel - - * @param originalAdditivity - - */ - public LoggerInfo(Level originalLevel, boolean originalAdditivity) { - this.originalLevel = originalLevel; - this.originalAdditivity = originalAdditivity; - } + /** */ + boolean originalAdditivity; - /** - * @return - - */ - public Level getOriginalLevel() { - return originalLevel; - } + /** + * Constructor + * @param originalLevel - + * @param originalAdditivity - + */ + public LoggerInfo(Level originalLevel, boolean originalAdditivity) { + this.originalLevel = originalLevel; + this.originalAdditivity = originalAdditivity; + } - /** - * @return - - */ - public boolean isOriginalAdditivity() { - return originalAdditivity; - } + /** + * @return - + */ + public Level getOriginalLevel() { + return originalLevel; + } + + /** + * @return - + */ + public boolean isOriginalAdditivity() { + return originalAdditivity; + } } } \ No newline at end of file Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,7 +44,7 @@ */ @Test public void read() { - Assert.assertNotNull(dao); - Assert.assertNotNull(dao.readList(Groupe.class)); + Assert.assertNotNull(dao); + Assert.assertNotNull(dao.readList(Groupe.class)); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTransactionTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTransactionTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/GroupeTransactionTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -47,7 +47,7 @@ */ @Before public void initLogger() { - transactionTestAppender = new SpringTransactionTestAppender(); + transactionTestAppender = new SpringTransactionTestAppender(); } /** @@ -55,7 +55,7 @@ */ @After public void closeLogger() { - transactionTestAppender.close(); + transactionTestAppender.close(); } /** @@ -64,14 +64,14 @@ */ @Test public void testReadGroupesTransaction() throws Exception { - // again we run our integration test - super.read(); + // again we run our integration test + super.read(); - // and now we verify, that opening and closing transaction operations were made by the TransactionInterceptor - String methodName = "readList"; - assertTrue(transactionTestAppender.isTransactionOpened(HibernateTemplateDao.class, methodName)); - assertTrue(transactionTestAppender.isTransactionCompleted(HibernateTemplateDao.class, methodName)); - assertFalse(transactionTestAppender.isTransactionRollbacked(HibernateTemplateDao.class, methodName)); + // and now we verify, that opening and closing transaction operations were made by the TransactionInterceptor + String methodName = "readList"; + assertTrue(transactionTestAppender.isTransactionOpened(HibernateTemplateDao.class, methodName)); + assertTrue(transactionTestAppender.isTransactionCompleted(HibernateTemplateDao.class, methodName)); + assertFalse(transactionTestAppender.isTransactionRollbacked(HibernateTemplateDao.class, methodName)); } } \ No newline at end of file Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/ModelValidatorTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/ModelValidatorTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/ModelValidatorTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,7 +48,7 @@ */ @Test public void validateModel() { - Assert.assertFalse(validator.validate(new Utilisateur(), Locale.getDefault()).isEmpty()); + Assert.assertFalse(validator.validate(new Utilisateur(), Locale.getDefault()).isEmpty()); } /** @@ -57,6 +57,6 @@ */ @Test public void validateModelProperty() throws ValidationException { - Assert.assertFalse(validator.validate(new Utilisateur(), Locale.getDefault(), "courriel").isEmpty()); + Assert.assertFalse(validator.validate(new Utilisateur(), Locale.getDefault(), "courriel").isEmpty()); } } Modified: trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/PersonneTest.java =================================================================== --- trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/PersonneTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.data/src/test/java/nc/ird/cantharella/data/model/PersonneTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -46,7 +46,7 @@ // @Test(expected = DataNotFoundException.class) @Test public void readFail() { // throws DataNotFoundException { - // dao.read(Personne.class, 999999999); + // dao.read(Personne.class, 999999999); } } \ No newline at end of file Modified: trunk/cantharella.service/pom.xml =================================================================== --- trunk/cantharella.service/pom.xml 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/pom.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -11,7 +11,21 @@ <artifactId>cantharella.service</artifactId> <name>Cantharella :: Service</name> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + <plugin> + <groupId>com.googlecode.maven-java-formatter-plugin</groupId> + <artifactId>maven-java-formatter-plugin</artifactId> + </plugin> + </plugins> + </build> + <dependencies> <dependency> <groupId>${project.groupId}</groupId> @@ -43,7 +57,6 @@ <artifactId>h2</artifactId> <scope>test</scope> </dependency> - <!-- ??? --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/config/ServiceContext.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/config/ServiceContext.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/config/ServiceContext.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,7 +67,7 @@ * Logger */ private static final Logger LOG = LoggerFactory.getLogger(ServiceContext.class); - + /** Mail SMTP: port */ private static final int MAIL_SMTP_PORT = 25; @@ -102,7 +102,7 @@ * @return mailActivated */ public static boolean isMailActivated() { - return mailActivated; + return mailActivated; } /** @@ -110,7 +110,7 @@ * @param mailActivated mailActivated */ public static void setMailActivated(boolean mailActivated) { - ServiceContext.mailActivated = mailActivated; + ServiceContext.mailActivated = mailActivated; } /** @@ -118,19 +118,19 @@ */ @Bean public Utilisateur defaultAdmin() { - Utilisateur admin = new Utilisateur(); - admin.setTypeDroit(TypeDroit.ADMINISTRATEUR); - admin.setAdressePostale("BP A5"); - admin.setCodePostal("98848"); - admin.setCourriel(adminCourrielProperty); - admin.setNom("ADMIN"); - admin.setOrganisme("IRD"); - admin.setPasswordHash(PasswordTools.sha1(adminPasswordProperty)); - admin.setCodePays("FR"); - admin.setPrenom("Admin"); - admin.setVille("Nouméa"); - Normalizer.normalize(PersonneNormalizer.class, admin); - return admin; + Utilisateur admin = new Utilisateur(); + admin.setTypeDroit(TypeDroit.ADMINISTRATEUR); + admin.setAdressePostale("BP A5"); + admin.setCodePostal("98848"); + admin.setCourriel(adminCourrielProperty); + admin.setNom("ADMIN"); + admin.setOrganisme("IRD"); + admin.setPasswordHash(PasswordTools.sha1(adminPasswordProperty)); + admin.setCodePays("FR"); + admin.setPrenom("Admin"); + admin.setVille("Nouméa"); + Normalizer.normalize(PersonneNormalizer.class, admin); + return admin; } /** @@ -138,9 +138,9 @@ */ @Bean public SimpleMailMessage mailMessage() { - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setFrom(mailFromProperty); - return mailMessage; + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setFrom(mailFromProperty); + return mailMessage; } /** @@ -148,18 +148,18 @@ */ @Bean public MailSender mailSender() { - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - Properties properties = new Properties(); - properties.put("mail.debug", mailDebugProperty); - properties.put("mail.smtp.connectiontimeout", MAIL_SMTP_TIMEOUT); - properties.put("mail.smtp.timeout", MAIL_SMTP_TIMEOUT); - properties.put("mail.smtp.reportsuccess", Boolean.TRUE); - mailSender.setJavaMailProperties(properties); - mailSender.setHost(mailHostProperty); - mailSender.setPort(MAIL_SMTP_PORT); - mailSender.setDefaultEncoding(DataContext.ENCODING); - mailSender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL); - return mailSender; + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + Properties properties = new Properties(); + properties.put("mail.debug", mailDebugProperty); + properties.put("mail.smtp.connectiontimeout", MAIL_SMTP_TIMEOUT); + properties.put("mail.smtp.timeout", MAIL_SMTP_TIMEOUT); + properties.put("mail.smtp.reportsuccess", Boolean.TRUE); + mailSender.setJavaMailProperties(properties); + mailSender.setHost(mailHostProperty); + mailSender.setPort(MAIL_SMTP_PORT); + mailSender.setDefaultEncoding(DataContext.ENCODING); + mailSender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL); + return mailSender; } /** @@ -167,29 +167,28 @@ */ @Bean public MessageSourceAccessor serviceMessageSource() { - // The ResourceBundleMessageSource does not handle UTF-8, so we use the Reloadable one - ReloadableResourceBundleMessageSource serviceMessageSource = new ReloadableResourceBundleMessageSource(); - serviceMessageSource.setBasename("service"); - serviceMessageSource.setDefaultEncoding(DataContext.ENCODING); - serviceMessageSource.setCacheSeconds(-1); - return new MessageSourceAccessor(serviceMessageSource); + // The ResourceBundleMessageSource does not handle UTF-8, so we use the Reloadable one + ReloadableResourceBundleMessageSource serviceMessageSource = new ReloadableResourceBundleMessageSource(); + serviceMessageSource.setBasename("service"); + serviceMessageSource.setDefaultEncoding(DataContext.ENCODING); + serviceMessageSource.setCacheSeconds(-1); + return new MessageSourceAccessor(serviceMessageSource); } - + /** * Set the service layer properties for the cantharella configuration * @return The placeholder configurer which get the service layer properties */ @Bean public static PropertySourcesPlaceholderConfigurer properties() { - PropertySourcesPlaceholderConfigurer pspc = - new PropertySourcesPlaceholderConfigurer(); - try { - pspc.setProperties(CantharellaConfig.getProperties()); - } catch (ArgumentsParserException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - pspc.setIgnoreUnresolvablePlaceholders(true); - return pspc; + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + try { + pspc.setProperties(CantharellaConfig.getProperties()); + } catch (ArgumentsParserException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/exceptions/EmailException.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/exceptions/EmailException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/exceptions/EmailException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,6 +35,6 @@ * @param cause Cause */ public EmailException(Exception cause) { - super(cause); + super(cause); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/MoleculeProvenanceBean.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/MoleculeProvenanceBean.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/MoleculeProvenanceBean.java 2013-02-18 07:27:17 UTC (rev 119) @@ -55,40 +55,39 @@ protected MoleculeProvenance provenance; public MoleculeProvenanceBean(Molecule molecule) { - this.molecule = molecule; + this.molecule = molecule; } public MoleculeProvenanceBean(MoleculeProvenance provenance) { - this(provenance.getMolecule()); - this.provenance = provenance; + this(provenance.getMolecule()); + this.provenance = provenance; } - public Integer getIdMolecule() { - return molecule.getIdMolecule(); + return molecule.getIdMolecule(); } public Molecule getMolecule() { - return molecule; + return molecule; } public MoleculeProvenance getMoleculeProvenance() { - return provenance; + return provenance; } public Lot getLot() { - Lot result = null; - if (provenance != null) { - Produit produit = provenance.getProduit(); - if (produit instanceof Fraction) { - Fraction fraction = (Fraction)produit; - result = fraction.getPurification().getLotSource(); - } else { - Extrait extrait = (Extrait)produit; - result = extrait.getExtraction().getLot(); - } - } - return result; + Lot result = null; + if (provenance != null) { + Produit produit = provenance.getProduit(); + if (produit instanceof Fraction) { + Fraction fraction = (Fraction) produit; + result = fraction.getPurification().getLotSource(); + } else { + Extrait extrait = (Extrait) produit; + result = extrait.getExtraction().getLot(); + } + } + return result; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/SearchResult.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/SearchResult.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/model/SearchResult.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,72 +44,72 @@ private static final long serialVersionUID = -283841649665446890L; protected List<Specimen> specimens; - + protected List<Lot> lots; - + protected List<Extraction> extractions; - + protected List<Purification> purifications; - + protected List<ResultatTestBio> resultatTestBios; - + protected List<Station> stations; - + protected List<Molecule> molecules; public List<Specimen> getSpecimens() { - return specimens; + return specimens; } public void setSpecimens(List<Specimen> specimens) { - this.specimens = specimens; + this.specimens = specimens; } public List<Lot> getLots() { - return lots; + return lots; } public void setLots(List<Lot> lots) { - this.lots = lots; + this.lots = lots; } public List<Extraction> getExtractions() { - return extractions; + return extractions; } public void setExtractions(List<Extraction> extractions) { - this.extractions = extractions; + this.extractions = extractions; } public List<Purification> getPurifications() { - return purifications; + return purifications; } public void setPurifications(List<Purification> purifications) { - this.purifications = purifications; + this.purifications = purifications; } public List<ResultatTestBio> getResultatTestBios() { - return resultatTestBios; + return resultatTestBios; } public void setResultatTestBios(List<ResultatTestBio> resultatTestBios) { - this.resultatTestBios = resultatTestBios; + this.resultatTestBios = resultatTestBios; } public List<Station> getStations() { - return stations; + return stations; } public void setStations(List<Station> stations) { - this.stations = stations; + this.stations = stations; } public List<Molecule> getMolecules() { - return molecules; + return molecules; } public void setMolecules(List<Molecule> molecules) { - this.molecules = molecules; + this.molecules = molecules; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/DocumentService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/DocumentService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/DocumentService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,7 +54,7 @@ * @throws DataConstraintException If the document type already exists (unique constraints) */ void createTypeDocument(@Normalize(TypeDocumentNormalizer.class) TypeDocument typeDocument) - throws DataConstraintException; + throws DataConstraintException; /** * Load a document type @@ -78,7 +78,7 @@ * @throws DataConstraintException If an unique constraint is broken with another document type */ void updateTypeDocument(@Normalize(TypeDocumentNormalizer.class) TypeDocument typeDocument) - throws DataConstraintException; + throws DataConstraintException; /** * Delete a document type Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/ExtractionService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/ExtractionService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/ExtractionService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -124,7 +124,7 @@ * @throws DataConstraintException Si la méthode (nom) existe déjà */ void createMethodeExtraction(@Normalize(MethodeExtractionNormalizer.class) MethodeExtraction methode) - throws DataConstraintException; + throws DataConstraintException; /** * Supprime une méthode pour une extraction @@ -154,7 +154,7 @@ * @throws DataNotFoundException Si non trouvée */ MethodeExtraction loadMethodeExtraction(@Normalize(UniqueFieldNormalizer.class) String nom) - throws DataNotFoundException; + throws DataNotFoundException; /** * Met à jour une méthode pour une extraction @@ -162,7 +162,7 @@ * @throws DataConstraintException En cas de doublons (champs uniques) */ void updateMethodeExtraction(@Normalize(MethodeExtractionNormalizer.class) MethodeExtraction methode) - throws DataConstraintException; + throws DataConstraintException; /** * Rafraichit une méthode d'extraction (pour éviter des LazyLoadingException) Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/MailService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/MailService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/MailService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,7 +53,7 @@ * @throws EmailException When an e-mail error occurs */ void sendMail(Collection<Utilisateur> recipients, String subject, String text, String replyTo) - throws EmailException; + throws EmailException; /** * Send an e-mail Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PersonneService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PersonneService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PersonneService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -185,7 +185,7 @@ * @throws EmailException En cas d'erreur dans l'envoi d'e-mail */ void resetPasswordUtilisateur(@Normalize(EmailNormalizer.class) String courriel) throws DataNotFoundException, - EmailException; + EmailException; /** * Envoie un e-mail aux administrateurs @@ -205,7 +205,7 @@ * @throws DataConstraintException Si la personne existe déjà (champs uniques) */ Utilisateur updateAndCreateUtilisateur(@Normalize(PersonneNormalizer.class) Personne personne) - throws EmailException, DataConstraintException; + throws EmailException, DataConstraintException; /** * Met à jour une personne @@ -221,7 +221,7 @@ * @throws DataConstraintException Si l'utilisateur existe déjà (champs uniques) */ void updateUtilisateur(@Normalize(PersonneNormalizer.class) Utilisateur utilisateur, boolean admin) - throws DataConstraintException; + throws DataConstraintException; /** * Valide et met à jour un utilisateur, et le prévient par e-mail @@ -229,7 +229,7 @@ * @throws DataConstraintException Si l'utilisateur existe déjà (champs uniques) */ void validAndUpdateUtilisateur(@Normalize(PersonneNormalizer.class) Utilisateur utilisateur) - throws DataConstraintException; + throws DataConstraintException; /** * Test de droits pour la modification ou suppression d'une personne (ou par héritage d'un utilisateur) Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PurificationService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PurificationService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/PurificationService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -57,7 +57,7 @@ * @throws DataConstraintException Si la manipulation (réf) existe déjà */ void createPurification(@Normalize(PurificationNormalizer.class) Purification purification) - throws DataConstraintException; + throws DataConstraintException; /** * Initialise les paramètres de la méthode avec des valeurs vides. Si certains paramètres existent déjà, aucune @@ -118,7 +118,7 @@ * @throws DataConstraintException En cas de doublons (champs uniques) */ void updatePurification(@Normalize(PurificationNormalizer.class) Purification purification) - throws DataConstraintException; + throws DataConstraintException; /** * Rafraichit une purification (pour éviter des LazyLoadingException) @@ -140,7 +140,7 @@ * @throws DataConstraintException Si la méthode (nom) existe déjà */ void createMethodePurification(@Normalize(MethodePurificationNormalizer.class) MethodePurification methode) - throws DataConstraintException; + throws DataConstraintException; /** * Supprime une méthode pour une purification @@ -171,7 +171,7 @@ * @throws DataNotFoundException Si non trouvée */ MethodePurification loadMethodePurification(@Normalize(UniqueFieldNormalizer.class) String nom) - throws DataNotFoundException; + throws DataNotFoundException; /** * Met à jour une méthode pour une purification @@ -179,7 +179,7 @@ * @throws DataConstraintException En cas de doublons (champs uniques) */ void updateMethodePurification(@Normalize(MethodePurificationNormalizer.class) MethodePurification methode) - throws DataConstraintException; + throws DataConstraintException; /** * Rafraichit une méthode de purification (pour éviter des LazyLoadingException) Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/TestBioService.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/TestBioService.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/TestBioService.java 2013-02-18 07:27:17 UTC (rev 119) @@ -158,7 +158,7 @@ * @throws DataConstraintException Si la méthode (nom) existe déjà */ void createMethodeTestBio(@Normalize(MethodeTestBioNormalizer.class) MethodeTestBio methode) - throws DataConstraintException; + throws DataConstraintException; /** * Supprime une méthode pour un test biologique @@ -210,7 +210,7 @@ * @throws DataConstraintException En cas de doublons (champs uniques) */ void updateMethodeTest(@Normalize(MethodeTestBioNormalizer.class) MethodeTestBio methode) - throws DataConstraintException; + throws DataConstraintException; /** * Rafraichit une méthode de testBio (pour éviter des LazyLoadingException) @@ -224,7 +224,7 @@ * @throws DataConstraintException Si l'erreur (nom) existe déjà */ void createErreurTest(@Normalize(ErreurTestNormalizer.class) ErreurTestBio erreurTest) - throws DataConstraintException; + throws DataConstraintException; /** * Supprime une erreur pour un test biologique @@ -261,6 +261,6 @@ * @throws DataConstraintException En cas de doublons (champs uniques) */ void updateErreurTestBio(@Normalize(ErreurTestNormalizer.class) ErreurTestBio erreurTest) - throws DataConstraintException; + throws DataConstraintException; } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/CampagneServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/CampagneServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/CampagneServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,103 +62,103 @@ /** {@inheritDoc} */ @Override public long countCampagnes() { - return dao.count(Campagne.class); + return dao.count(Campagne.class); } /** {@inheritDoc} */ @Override public void createCampagne(Campagne campagne) throws DataConstraintException { - LOG.info("createCampagne " + campagne.getNom()); - dao.create(campagne); + LOG.info("createCampagne " + campagne.getNom()); + dao.create(campagne); } /** {@inheritDoc} */ @Override public void deleteCampagne(Campagne campagne) throws DataConstraintException { - AssertTools.assertNotNull(campagne); - LOG.info("deleteCampagne " + campagne.getIdCampagne()); - try { - dao.delete(campagne); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(campagne); + LOG.info("deleteCampagne " + campagne.getIdCampagne()); + try { + dao.delete(campagne); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listCampagneProgrammes() { - return (List<String>) dao.list(CampagneDao.CRITERIA_DISTINCT_CAMPAGNE_PROGRAMMES); + return (List<String>) dao.list(CampagneDao.CRITERIA_DISTINCT_CAMPAGNE_PROGRAMMES); } /** {@inheritDoc} */ @Override public List<Campagne> listCampagnes(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - return dao.readList(Campagne.class, "nom"); - } - SortedSet<Campagne> campagnes = listCampagnesForUser(utilisateur); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + return dao.readList(Campagne.class, "nom"); + } + SortedSet<Campagne> campagnes = listCampagnesForUser(utilisateur); - return new ArrayList<Campagne>(campagnes); + return new ArrayList<Campagne>(campagnes); } /** {@inheritDoc} */ @Override public SortedSet<Campagne> listCampagnesForUser(Utilisateur utilisateur) { - // gestion des droits en plus pour les utilisateurs - SortedSet<Campagne> campagnes = new TreeSet<Campagne>(); - campagnes.addAll(utilisateur.getCampagnesCreees()); - campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); + // gestion des droits en plus pour les utilisateurs + SortedSet<Campagne> campagnes = new TreeSet<Campagne>(); + campagnes.addAll(utilisateur.getCampagnesCreees()); + campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); - // accès aux campagnes des lots pour lesquels l'utilisateur a les droits - for (Lot lot : utilisateur.getLotsCrees()) { - campagnes.add(lot.getCampagne()); - } - for (Lot lot : utilisateur.getLotsDroits().keySet()) { - campagnes.add(lot.getCampagne()); - } - return campagnes; + // accès aux campagnes des lots pour lesquels l'utilisateur a les droits + for (Lot lot : utilisateur.getLotsCrees()) { + campagnes.add(lot.getCampagne()); + } + for (Lot lot : utilisateur.getLotsDroits().keySet()) { + campagnes.add(lot.getCampagne()); + } + return campagnes; } /** {@inheritDoc} */ @Override public Campagne loadCampagne(Integer idCampagne) throws DataNotFoundException { - AssertTools.assertNotNull(idCampagne); - return dao.read(Campagne.class, idCampagne); + AssertTools.assertNotNull(idCampagne); + return dao.read(Campagne.class, idCampagne); } /** {@inheritDoc} */ @Override public Campagne loadCampagne(String nom) throws DataNotFoundException { - AssertTools.assertNotEmpty(nom); - return dao.read(Campagne.class, "nom", nom); + AssertTools.assertNotEmpty(nom); + return dao.read(Campagne.class, "nom", nom); } /** {@inheritDoc} */ @Override public void refreshCampagne(Campagne campagne) { - AssertTools.assertNotNull(campagne); - dao.refresh(campagne); + AssertTools.assertNotNull(campagne); + dao.refresh(campagne); } /** {@inheritDoc} */ @Override public void updateCampagne(Campagne campagne) throws DataConstraintException { - LOG.info("updateCampagne " + campagne.getIdCampagne()); - try { - dao.update(campagne); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateCampagne " + campagne.getIdCampagne()); + try { + dao.update(campagne); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public boolean updateOrdeleteCampagneEnabled(Campagne campagne, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == campagne.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == campagne.getCreateur().getIdPersonne(); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/DocumentServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/DocumentServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/DocumentServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,63 +56,63 @@ /** {@inheritDoc} */ @Override public List<TypeDocument> listTypeDocuments() { - return dao.readList(TypeDocument.class, "nom"); + return dao.readList(TypeDocument.class, "nom"); } /** {@inheritDoc} */ @Override public void createTypeDocument(TypeDocument typeDocument) throws DataConstraintException { - LOG.info("createTypeDocument: " + typeDocument.getNom()); - dao.create(typeDocument); + LOG.info("createTypeDocument: " + typeDocument.getNom()); + dao.create(typeDocument); } /** {@inheritDoc} */ @Override public TypeDocument loadTypeDocument(Integer idTypeDocument) throws DataNotFoundException { - return dao.read(TypeDocument.class, idTypeDocument); + return dao.read(TypeDocument.class, idTypeDocument); } /** {@inheritDoc} */ @Override public TypeDocument loadTypeDocument(String nom) throws DataNotFoundException { - return dao.read(TypeDocument.class, "nom", nom); + return dao.read(TypeDocument.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateTypeDocument(TypeDocument typeDocument) throws DataConstraintException { - LOG.info("updateTypeDocument: " + typeDocument.getNom()); - try { - dao.update(typeDocument); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateTypeDocument: " + typeDocument.getNom()); + try { + dao.update(typeDocument); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void deleteTypeDocument(TypeDocument typeDocument) throws DataConstraintException { - AssertTools.assertNotNull(typeDocument); - LOG.info("deleteTypeDocument: " + typeDocument.getNom()); - try { - dao.delete(typeDocument); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(typeDocument); + LOG.info("deleteTypeDocument: " + typeDocument.getNom()); + try { + dao.delete(typeDocument); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public Document loadDocument(Integer idDocument) throws DataNotFoundException { - return null; + return null; } /** {@inheritDoc} */ @Override public boolean updateOrdeleteDocumentEnabled(Document document, Utilisateur utilisateur) { - return false; + return false; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ExtractionServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ExtractionServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ExtractionServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -70,198 +70,198 @@ /** {@inheritDoc} */ @Override public long countExtractions() { - return dao.count(Extraction.class); + return dao.count(Extraction.class); } /** {@inheritDoc} */ @Override public void createExtraction(Extraction extraction) throws DataConstraintException { - LOG.info("createExtraction: " + extraction.getRef()); - dao.create(extraction); + LOG.info("createExtraction: " + extraction.getRef()); + dao.create(extraction); } /** {@inheritDoc} */ @Override public void deleteExtraction(Extraction extraction) throws DataConstraintException { - AssertTools.assertNotNull(extraction); - LOG.info("deleteExtraction: " + extraction.getRef()); - try { - dao.delete(extraction); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(extraction); + LOG.info("deleteExtraction: " + extraction.getRef()); + try { + dao.delete(extraction); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<Extraction> listExtractions(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - // si admin, on ajoute toutes les extractions de la base + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + // si admin, on ajoute toutes les extractions de la base - // SortedSet pour garder une liste "DISTINCT", sinon une ligne par extrait (OUTER JOIN avec Fetch=EAGER) - SortedSet<Extraction> extractions = new TreeSet<Extraction>(dao.readList(Extraction.class)); - return new ArrayList<Extraction>(extractions); - } - // gestion des droits en plus pour les utilisateurs - return new ArrayList<Extraction>(listExtractionsForUser(utilisateur)); + // SortedSet pour garder une liste "DISTINCT", sinon une ligne par extrait (OUTER JOIN avec Fetch=EAGER) + SortedSet<Extraction> extractions = new TreeSet<Extraction>(dao.readList(Extraction.class)); + return new ArrayList<Extraction>(extractions); + } + // gestion des droits en plus pour les utilisateurs + return new ArrayList<Extraction>(listExtractionsForUser(utilisateur)); } /** {@inheritDoc} */ @Override public SortedSet<Extraction> listExtractionsForUser(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - SortedSet<Extraction> extractions = new TreeSet<Extraction>(); + AssertTools.assertNotNull(utilisateur); + SortedSet<Extraction> extractions = new TreeSet<Extraction>(); - extractions.addAll(utilisateur.getExtractionsCrees()); - SortedSet<Lot> lotsAllowed = lotService.listLotsForUser(utilisateur); - for (Lot l : lotsAllowed) { - extractions.addAll(l.getExtractions()); - } - return extractions; + extractions.addAll(utilisateur.getExtractionsCrees()); + SortedSet<Lot> lotsAllowed = lotService.listLotsForUser(utilisateur); + for (Lot l : lotsAllowed) { + extractions.addAll(l.getExtractions()); + } + return extractions; } /** {@inheritDoc} */ @Override public boolean isExtractionUnique(Extraction extraction) { - AssertTools.assertNotNull(extraction); + AssertTools.assertNotNull(extraction); - // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) - if (!dao.exists(Extraction.class, "ref", extraction.getRef())) { - return true; - } + // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) + if (!dao.exists(Extraction.class, "ref", extraction.getRef())) { + return true; + } - Extraction extrWithSameVal; - try { - extrWithSameVal = dao.read(Extraction.class, "ref", extraction.getRef()); - dao.evict(extrWithSameVal); - } catch (DataNotFoundException e) { - return true; // never call, cover by dao.exists... - } - // in case of new record, id is null - return extraction.getIdExtraction() != null - && extraction.getIdExtraction().equals(extrWithSameVal.getIdExtraction()); + Extraction extrWithSameVal; + try { + extrWithSameVal = dao.read(Extraction.class, "ref", extraction.getRef()); + dao.evict(extrWithSameVal); + } catch (DataNotFoundException e) { + return true; // never call, cover by dao.exists... + } + // in case of new record, id is null + return extraction.getIdExtraction() != null + && extraction.getIdExtraction().equals(extrWithSameVal.getIdExtraction()); } /** {@inheritDoc} */ @Override public Extraction loadExtraction(Integer idExtraction) throws DataNotFoundException { - LOG.debug("read Extraction"); - return dao.read(Extraction.class, idExtraction); + LOG.debug("read Extraction"); + return dao.read(Extraction.class, idExtraction); } /** {@inheritDoc} */ @Override public Extraction loadExtraction(String ref) throws DataNotFoundException { - return dao.read(Extraction.class, "ref", ref); + return dao.read(Extraction.class, "ref", ref); } /** {@inheritDoc} */ @Override public void updateExtraction(Extraction extraction) throws DataConstraintException { - LOG.info("updateExtraction: " + extraction.getRef()); - try { - dao.update(extraction); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateExtraction: " + extraction.getRef()); + try { + dao.update(extraction); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public boolean updateOrdeleteExtractionEnabled(Extraction extraction, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == extraction.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == extraction.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public void createMethodeExtraction(MethodeExtraction methode) throws DataConstraintException { - LOG.info("createMethodeExtraction: " + methode.getNom()); - dao.create(methode); + LOG.info("createMethodeExtraction: " + methode.getNom()); + dao.create(methode); } /** {@inheritDoc} */ @Override public void deleteMethodeExtraction(MethodeExtraction methode) throws DataConstraintException { - AssertTools.assertNotNull(methode); - LOG.info("deleteMethodeExtraction: " + methode.getNom()); - try { - dao.delete(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(methode); + LOG.info("deleteMethodeExtraction: " + methode.getNom()); + try { + dao.delete(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<MethodeExtraction> listMethodesExtraction() { - return dao.readList(MethodeExtraction.class, "nom"); + return dao.readList(MethodeExtraction.class, "nom"); } /** {@inheritDoc} */ @Override public MethodeExtraction loadMethodeExtraction(Integer idMethode) throws DataNotFoundException { - return dao.read(MethodeExtraction.class, idMethode); + return dao.read(MethodeExtraction.class, idMethode); } /** {@inheritDoc} */ @Override public MethodeExtraction loadMethodeExtraction(String nom) throws DataNotFoundException { - return dao.read(MethodeExtraction.class, "nom", nom); + return dao.read(MethodeExtraction.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateMethodeExtraction(MethodeExtraction methode) throws DataConstraintException { - LOG.info("updateMethodeExtraction: " + methode.getNom()); - try { - dao.update(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateMethodeExtraction: " + methode.getNom()); + try { + dao.update(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void refreshMethodeExtraction(MethodeExtraction methode) { - AssertTools.assertNotNull(methode); - dao.refresh(methode); + AssertTools.assertNotNull(methode); + dao.refresh(methode); } /** {@inheritDoc} */ @Override public boolean isTypeExtraitReferenced(TypeExtrait typeExtrait) { - AssertTools.assertNotNull(typeExtrait); - AssertTools.assertNotNull(typeExtrait.getIdTypeExtrait()); - return dao.count(ExtractionDao.getCriteriaCountExtraitOfTypeExtrait(typeExtrait.getIdTypeExtrait())) > 0; + AssertTools.assertNotNull(typeExtrait); + AssertTools.assertNotNull(typeExtrait.getIdTypeExtrait()); + return dao.count(ExtractionDao.getCriteriaCountExtraitOfTypeExtrait(typeExtrait.getIdTypeExtrait())) > 0; } /** {@inheritDoc} */ @Override public boolean isExtraitUnique(Extrait extrait) { - AssertTools.assertNotNull(extrait); + AssertTools.assertNotNull(extrait); - // unique if it doesn't exist different value or if it exists with the same id (so same row in the db) - if (!dao.exists(Extrait.class, "ref", extrait.getRef())) { - return true; - } - Extrait extrWithSameVal; - try { - extrWithSameVal = dao.read(Extrait.class, "ref", extrait.getRef()); - dao.evict(extrWithSameVal); - } catch (DataNotFoundException e) { - return true; // never call, covers by dao.exists... - } - // in case of new record, id is null - return extrait.getId() != null && extrait.getId().equals(extrWithSameVal.getId()); + // unique if it doesn't exist different value or if it exists with the same id (so same row in the db) + if (!dao.exists(Extrait.class, "ref", extrait.getRef())) { + return true; + } + Extrait extrWithSameVal; + try { + extrWithSameVal = dao.read(Extrait.class, "ref", extrait.getRef()); + dao.evict(extrWithSameVal); + } catch (DataNotFoundException e) { + return true; // never call, covers by dao.exists... + } + // in case of new record, id is null + return extrait.getId() != null && extrait.getId().equals(extrWithSameVal.getId()); } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/LotServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/LotServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/LotServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,159 +62,159 @@ /** {@inheritDoc} */ @Override public long countLots() { - return dao.count(Lot.class); + return dao.count(Lot.class); } /** {@inheritDoc} */ @Override public void createLot(Lot lot) throws DataConstraintException { - LOG.info("createLot " + lot.getRef()); - dao.create(lot); + LOG.info("createLot " + lot.getRef()); + dao.create(lot); } /** {@inheritDoc} */ @Override public void createPartie(Partie partie) throws DataConstraintException { - LOG.info("createPartie: " + partie.getNom()); - dao.create(partie); + LOG.info("createPartie: " + partie.getNom()); + dao.create(partie); } /** {@inheritDoc} */ @Override public void deleteLot(Lot lot) throws DataConstraintException { - AssertTools.assertNotNull(lot); - LOG.info("deleteLot " + lot.getRef()); - try { - dao.delete(lot); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(lot); + LOG.info("deleteLot " + lot.getRef()); + try { + dao.delete(lot); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void deletePartie(Partie partie) throws DataConstraintException { - AssertTools.assertNotNull(partie); - LOG.info("deletePartie: " + partie.getNom()); - try { - dao.delete(partie); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(partie); + LOG.info("deletePartie: " + partie.getNom()); + try { + dao.delete(partie); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<Lot> listLots(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - return dao.readList(Lot.class, "ref"); - } - // gestion des droits en plus pour les utilisateurs - return new ArrayList<Lot>(listLotsForUser(utilisateur)); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + return dao.readList(Lot.class, "ref"); + } + // gestion des droits en plus pour les utilisateurs + return new ArrayList<Lot>(listLotsForUser(utilisateur)); } /** {@inheritDoc} */ @Override public SortedSet<Lot> listLotsForUser(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - SortedSet<Lot> lots = new TreeSet<Lot>(); - for (Campagne c : utilisateur.getCampagnesCreees()) { - lots.addAll(c.getLots()); - } - for (Campagne c : utilisateur.getCampagnesDroits().keySet()) { - lots.addAll(c.getLots()); - } - lots.addAll(utilisateur.getLotsCrees()); - lots.addAll(utilisateur.getLotsDroits().keySet()); - return lots; + AssertTools.assertNotNull(utilisateur); + SortedSet<Lot> lots = new TreeSet<Lot>(); + for (Campagne c : utilisateur.getCampagnesCreees()) { + lots.addAll(c.getLots()); + } + for (Campagne c : utilisateur.getCampagnesDroits().keySet()) { + lots.addAll(c.getLots()); + } + lots.addAll(utilisateur.getLotsCrees()); + lots.addAll(utilisateur.getLotsDroits().keySet()); + return lots; } /** {@inheritDoc} */ @Override public boolean updateOrdeleteLotEnabled(Lot lot, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == lot.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == lot.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public boolean isLotAccessibleByUser(Lot lot, Utilisateur utilisateur) { - // si administrateur ou créateur, accès ok - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR || utilisateur.equals(lot.getCreateur())) { - return true; - } - // accessible si l'utilisateur - if (utilisateur.getCampagnesCreees().contains(lot.getCampagne())) { - return true; - } - // accessible si l'utilisateur a le droit à la campagne - if (utilisateur.getCampagnesDroits().containsKey(lot.getCampagne())) { - return true; - } - // accessible si l'utilisateur a le droit au lot - if (utilisateur.getLotsDroits().containsKey(lot)) { - return true; - } - // pas d'accès sinon - return false; + // si administrateur ou créateur, accès ok + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR || utilisateur.equals(lot.getCreateur())) { + return true; + } + // accessible si l'utilisateur + if (utilisateur.getCampagnesCreees().contains(lot.getCampagne())) { + return true; + } + // accessible si l'utilisateur a le droit à la campagne + if (utilisateur.getCampagnesDroits().containsKey(lot.getCampagne())) { + return true; + } + // accessible si l'utilisateur a le droit au lot + if (utilisateur.getLotsDroits().containsKey(lot)) { + return true; + } + // pas d'accès sinon + return false; } /** {@inheritDoc} */ @Override public List<Partie> listParties() { - return dao.readList(Partie.class, "nom"); + return dao.readList(Partie.class, "nom"); } /** {@inheritDoc} */ @Override public Lot loadLot(Integer idLot) throws DataNotFoundException { - return dao.read(Lot.class, idLot); + return dao.read(Lot.class, idLot); } /** {@inheritDoc} */ @Override public Lot loadLot(String ref) throws DataNotFoundException { - AssertTools.assertNotEmpty(ref); - return dao.read(Lot.class, "ref", ref); + AssertTools.assertNotEmpty(ref); + return dao.read(Lot.class, "ref", ref); } /** {@inheritDoc} */ @Override public Partie loadPartie(Integer idPartie) throws DataNotFoundException { - return dao.read(Partie.class, idPartie); + return dao.read(Partie.class, idPartie); } /** {@inheritDoc} */ @Override public Partie loadPartie(String nom) throws DataNotFoundException { - return dao.read(Partie.class, "nom", nom); + return dao.read(Partie.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateLot(Lot lot) throws DataConstraintException { - LOG.info("updateLot " + lot.getRef()); - try { - dao.update(lot); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateLot " + lot.getRef()); + try { + dao.update(lot); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void updatePartie(Partie partie) throws DataConstraintException { - LOG.info("updatePartie: " + partie.getNom()); - try { - dao.update(partie); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updatePartie: " + partie.getNom()); + try { + dao.update(partie); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MailServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MailServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MailServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,27 +62,27 @@ /** {@inheritDoc} */ @Override public void sendMail(Collection<Utilisateur> recipients, String subject, String text) throws EmailException { - sendMail(recipients, subject, text, null); + sendMail(recipients, subject, text, null); } /** {@inheritDoc} */ @Override public void sendMail(Collection<Utilisateur> recipients, String subject, String text, String replyTo) - throws EmailException { - AssertTools.assertCollectionNotNull(recipients); - String[] courriels = new String[recipients.size()]; - int i = 0; - for (Utilisateur recipient : recipients) { - courriels[i++] = recipient.getCourriel(); - } - sendMail(subject, text, replyTo, courriels); + throws EmailException { + AssertTools.assertCollectionNotNull(recipients); + String[] courriels = new String[recipients.size()]; + int i = 0; + for (Utilisateur recipient : recipients) { + courriels[i++] = recipient.getCourriel(); + } + sendMail(subject, text, replyTo, courriels); } /** {@inheritDoc} */ @Override public void sendMail(Personne recipient, String subject, String text) throws EmailException { - AssertTools.assertNotNull(recipient); - sendMail(subject, text, null, recipient.getCourriel()); + AssertTools.assertNotNull(recipient); + sendMail(subject, text, null, recipient.getCourriel()); } /** @@ -94,44 +94,44 @@ * @throws EmailException In case of error while sending an e-mail */ private void sendMail(String subject, String text, String replyTo, String... recipients) throws EmailException { - LOG.info("sendMail " + subject + " [to] " + Arrays.toString(recipients)); - if (ServiceContext.isMailActivated()) { - AssertTools.assertNotEmpty(subject); - AssertTools.assertNotEmpty(text); - AssertTools.assertNotEmpty(recipients); - AssertTools.assertArrayNotEmpty(recipients); - // Validate e-mail - mailMessage.setTo(recipients); - mailMessage.setSubject(subject); - mailMessage.setText(text); - if (!StringUtils.isEmpty(replyTo)) { - mailMessage.setReplyTo(replyTo); - } - try { - mailSender.send(mailMessage); - } catch (Exception e) { - throw new EmailException(e); - } - } + LOG.info("sendMail " + subject + " [to] " + Arrays.toString(recipients)); + if (ServiceContext.isMailActivated()) { + AssertTools.assertNotEmpty(subject); + AssertTools.assertNotEmpty(text); + AssertTools.assertNotEmpty(recipients); + AssertTools.assertArrayNotEmpty(recipients); + // Validate e-mail + mailMessage.setTo(recipients); + mailMessage.setSubject(subject); + mailMessage.setText(text); + if (!StringUtils.isEmpty(replyTo)) { + mailMessage.setReplyTo(replyTo); + } + try { + mailSender.send(mailMessage); + } catch (Exception e) { + throw new EmailException(e); + } + } } /** {@inheritDoc} */ @Override public void sendMailQuietly(Collection<Utilisateur> recipients, String subject, String text) { - try { - sendMail(recipients, subject, text); - } catch (EmailException e) { - LOG.warn(e.toString()); - } + try { + sendMail(recipients, subject, text); + } catch (EmailException e) { + LOG.warn(e.toString()); + } } /** {@inheritDoc} */ @Override public void sendMailQuietly(Personne recipient, String subject, String text) { - try { - sendMail(recipient, subject, text); - } catch (EmailException e) { - LOG.warn(e.toString()); - } + try { + sendMail(recipient, subject, text); + } catch (EmailException e) { + LOG.warn(e.toString()); + } } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MoleculeServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MoleculeServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/MoleculeServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -74,118 +74,115 @@ /** {@inheritDoc} */ @Override public long countMolecules() { - return dao.count(Molecule.class); + return dao.count(Molecule.class); } /** {@inheritDoc} */ @Override - public void createMolecule(Molecule molecule) - throws DataConstraintException { - LOG.info("createMolecule " + molecule.getFormuleBrute()); - dao.create(molecule); + public void createMolecule(Molecule molecule) throws DataConstraintException { + LOG.info("createMolecule " + molecule.getFormuleBrute()); + dao.create(molecule); } /** {@inheritDoc} */ @Override - public void deleteMolecule(Molecule molecule) - throws DataConstraintException { - AssertTools.assertNotNull(molecule); - LOG.info("deleteMolecule " + molecule.getIdMolecule()); - try { - dao.delete(molecule); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + public void deleteMolecule(Molecule molecule) throws DataConstraintException { + AssertTools.assertNotNull(molecule); + LOG.info("deleteMolecule " + molecule.getIdMolecule()); + try { + dao.delete(molecule); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<Molecule> listMolecules() { - return dao.readList(Molecule.class, "idMolecule"); + return dao.readList(Molecule.class, "idMolecule"); } - + /** {@inheritDoc} */ @Override public List<MoleculeProvenanceBean> listMoleculeProvenances(Utilisateur utilisateur) { - List<Molecule> molecules = listMolecules(); - List<MoleculeProvenanceBean> result = listMoleculeProvenances(molecules, utilisateur); - return result; + List<Molecule> molecules = listMolecules(); + List<MoleculeProvenanceBean> result = listMoleculeProvenances(molecules, utilisateur); + return result; } /** {@inheritDoc} */ @Override public List<MoleculeProvenanceBean> listMoleculeProvenances(List<Molecule> molecules, Utilisateur utilisateur) { - List<MoleculeProvenanceBean> result = new ArrayList<MoleculeProvenanceBean>(); + List<MoleculeProvenanceBean> result = new ArrayList<MoleculeProvenanceBean>(); - for (Molecule molecule : molecules) { - boolean isOneProductVisible = false; - - List<MoleculeProvenance> moleculeProvenances = molecule.getProvenances(); - for (MoleculeProvenance moleculeProvenance : moleculeProvenances) { - if (isMoleculeProvenanceAccessibleByUser(moleculeProvenance, utilisateur)) { - result.add(new MoleculeProvenanceBean(moleculeProvenance)); - isOneProductVisible = true; - } - } - - if (!isOneProductVisible) { - result.add(new MoleculeProvenanceBean(molecule)); - } - } + for (Molecule molecule : molecules) { + boolean isOneProductVisible = false; - return result; + List<MoleculeProvenance> moleculeProvenances = molecule.getProvenances(); + for (MoleculeProvenance moleculeProvenance : moleculeProvenances) { + if (isMoleculeProvenanceAccessibleByUser(moleculeProvenance, utilisateur)) { + result.add(new MoleculeProvenanceBean(moleculeProvenance)); + isOneProductVisible = true; + } + } + + if (!isOneProductVisible) { + result.add(new MoleculeProvenanceBean(molecule)); + } + } + + return result; } /** {@inheritDoc} */ @Override public Molecule loadMolecule(Integer numero) throws DataNotFoundException { - return dao.read(Molecule.class, numero); + return dao.read(Molecule.class, numero); } /** {@inheritDoc} */ @Override - public void updateMolecule(Molecule molecule) - throws DataConstraintException { - LOG.info("updateMolecule: " + molecule.getIdMolecule()); - try { - dao.update(molecule); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + public void updateMolecule(Molecule molecule) throws DataConstraintException { + LOG.info("updateMolecule: " + molecule.getIdMolecule()); + try { + dao.update(molecule); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public boolean updateOrdeleteMoleculeEnabled(Molecule molecule, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == molecule.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == molecule.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listMoleculeOrganisme() { - Set<String> organismes = new HashSet<String>(); - organismes.addAll((List<String>)dao.list(MoleculeDao.CRITERIA_DISTINCT_MOLECULE_ORGANISMES)); - organismes.addAll((List<String>)dao.list(PersonneDao.CRITERIA_DISTINCT_PERSONNE_ORGANISMES)); - List<String> result = new ArrayList<String>(organismes); - result.remove(null); // fix NPE on sort - Collections.sort(result); - return result; + Set<String> organismes = new HashSet<String>(); + organismes.addAll((List<String>) dao.list(MoleculeDao.CRITERIA_DISTINCT_MOLECULE_ORGANISMES)); + organismes.addAll((List<String>) dao.list(PersonneDao.CRITERIA_DISTINCT_PERSONNE_ORGANISMES)); + List<String> result = new ArrayList<String>(organismes); + result.remove(null); // fix NPE on sort + Collections.sort(result); + return result; } /** {@inheritDoc} */ @Override public boolean isMoleculeProvenanceAccessibleByUser(MoleculeProvenance moleculeProvenance, Utilisateur utilisateur) { - Lot lot; - Produit produit = moleculeProvenance.getProduit(); - if (produit instanceof Extrait) { - lot = ((Extrait)produit).getExtraction().getLot(); - } else { - lot = ((Fraction)produit).getPurification().getLotSource(); - } - return lotService.isLotAccessibleByUser(lot, utilisateur); + Lot lot; + Produit produit = moleculeProvenance.getProduit(); + if (produit instanceof Extrait) { + lot = ((Extrait) produit).getExtraction().getLot(); + } else { + lot = ((Fraction) produit).getPurification().getLotSource(); + } + return lotService.isLotAccessibleByUser(lot, utilisateur); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PersonneServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PersonneServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PersonneServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -83,11 +83,11 @@ /** {@inheritDoc} */ @Override public void checkOrCreateAdmin() throws DataConstraintException { - if (countAdmins() == 0L) { - defaultAdmin.setTypeDroit(TypeDroit.ADMINISTRATEUR); - defaultAdmin.setValide(Boolean.TRUE); - plainCreateUtilisateur(defaultAdmin); - } + if (countAdmins() == 0L) { + defaultAdmin.setTypeDroit(TypeDroit.ADMINISTRATEUR); + defaultAdmin.setValide(Boolean.TRUE); + plainCreateUtilisateur(defaultAdmin); + } } /** @@ -95,61 +95,59 @@ * @return Nombre d'administrateurs */ private Long countAdmins() { - return dao.count(PersonneDao.CRITERIA_COUNT_ADMINS); + return dao.count(PersonneDao.CRITERIA_COUNT_ADMINS); } /** {@inheritDoc} */ @Override public long countPersonnes() { - return dao.count(Personne.class); + return dao.count(Personne.class); } /** {@inheritDoc} */ @Override public void createPersonne(Personne personne) throws DataConstraintException { - LOG.info("createPersonne " + personne.getCourriel()); - try { - dao.create(personne); - } catch (DataIntegrityViolationException e) { - throw new DataConstraintException(e); - } + LOG.info("createPersonne " + personne.getCourriel()); + try { + dao.create(personne); + } catch (DataIntegrityViolationException e) { + throw new DataConstraintException(e); + } } /** {@inheritDoc} */ @Override public void createUtilisateur(Utilisateur utilisateur) throws DataConstraintException { - try { - plainCreateUtilisateur(utilisateur); - } catch (DataIntegrityViolationException e) { - throw new DataConstraintException(e); - } - mailService.sendMailQuietly(utilisateur, messages.getMessage("register.subject"), - messages.getMessage("register.text")); - mailService.sendMailQuietly( - listAdmins(), - messages.getMessage("register.subject.admin"), - messages.getMessage("register.text.admin", new Object[] { utilisateur.getPrenom(), - utilisateur.getNom(), utilisateur.getCourriel() })); + try { + plainCreateUtilisateur(utilisateur); + } catch (DataIntegrityViolationException e) { + throw new DataConstraintException(e); + } + mailService.sendMailQuietly(utilisateur, messages.getMessage("register.subject"), messages + .getMessage("register.text")); + mailService.sendMailQuietly(listAdmins(), messages.getMessage("register.subject.admin"), messages.getMessage( + "register.text.admin", new Object[] { utilisateur.getPrenom(), utilisateur.getNom(), + utilisateur.getCourriel() })); } /** {@inheritDoc} */ @Override public void deletePersonne(Personne personne) throws DataConstraintException { - AssertTools.assertNotNull(personne); - LOG.info("deletePersonne " + personne.getIdPersonne()); - AssertTools.assertNotNull(personne.getIdPersonne()); - try { - dao.delete(personne); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(personne); + LOG.info("deletePersonne " + personne.getIdPersonne()); + AssertTools.assertNotNull(personne.getIdPersonne()); + try { + dao.delete(personne); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void deleteUtilisateur(Utilisateur utilisateur) throws DataConstraintException, EmailException { - deleteUtilisateur(utilisateur, messages.getMessage("delete.subject"), messages.getMessage("delete.text")); + deleteUtilisateur(utilisateur, messages.getMessage("delete.subject"), messages.getMessage("delete.text")); } /** @@ -169,26 +167,26 @@ */ @Transactional(rollbackFor = EmailException.class) public void deleteUtilisateur(Utilisateur utilisateur, String mailSubject, String mailText) throws EmailException, - DataConstraintException { - AssertTools.assertNotNull(utilisateur); - LOG.info("deleteUtilisateur " + utilisateur.getIdPersonne()); - AssertTools.assertNotNull(utilisateur.getIdPersonne()); - try { - dao.delete(utilisateur); - } catch (DataConstraintException e) { - dao.execute(PersonneDao.SQL_DELETE_UTILISATEUR, utilisateur.getIdPersonne()); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - mailService.sendMail(utilisateur, mailSubject, mailText); + DataConstraintException { + AssertTools.assertNotNull(utilisateur); + LOG.info("deleteUtilisateur " + utilisateur.getIdPersonne()); + AssertTools.assertNotNull(utilisateur.getIdPersonne()); + try { + dao.delete(utilisateur); + } catch (DataConstraintException e) { + dao.execute(PersonneDao.SQL_DELETE_UTILISATEUR, utilisateur.getIdPersonne()); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + mailService.sendMail(utilisateur, mailSubject, mailText); } /** {@inheritDoc} */ @Override public String hashPassword(String password) { - AssertTools.assertNotEmpty(password); - return PasswordTools.sha1(password); + AssertTools.assertNotEmpty(password); + return PasswordTools.sha1(password); } /** @@ -197,90 +195,90 @@ */ @SuppressWarnings("unchecked") private List<Utilisateur> listAdmins() { - return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_ADMINS); + return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_ADMINS); } /** {@inheritDoc} */ @Override public List<Personne> listPersonnes() { - List<Personne> allPersonnes = dao.readList(Personne.class, "nom", "prenom"); - allPersonnes.removeAll(listUtilisateursInvalid()); - return allPersonnes; + List<Personne> allPersonnes = dao.readList(Personne.class, "nom", "prenom"); + allPersonnes.removeAll(listUtilisateursInvalid()); + return allPersonnes; } /** {@inheritDoc} */ @Override public List<Personne> listPersonnesWithInvalidUsers() { - return dao.readList(Personne.class, new String[] { "nom", "prenom" }); + return dao.readList(Personne.class, new String[] { "nom", "prenom" }); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listPersonneOrganismes() { - return (List<String>) dao.list(PersonneDao.CRITERIA_DISTINCT_PERSONNE_ORGANISMES); + return (List<String>) dao.list(PersonneDao.CRITERIA_DISTINCT_PERSONNE_ORGANISMES); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<Utilisateur> listUtilisateursInvalid() { - return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_UTILISATEURS_INVALID); + return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_UTILISATEURS_INVALID); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<Utilisateur> listUtilisateursValid() { - return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_UTILISATEURS_VALID); + return (List<Utilisateur>) dao.list(PersonneDao.CRITERIA_LIST_UTILISATEURS_VALID); } /** {@inheritDoc} */ @Override public Personne loadPersonne(Integer idPersonne) throws DataNotFoundException { - AssertTools.assertNotNull(idPersonne); - try { - return dao.read(Personne.class, idPersonne); - } catch (DataRetrievalFailureException e) { - throw new DataNotFoundException(e); - } + AssertTools.assertNotNull(idPersonne); + try { + return dao.read(Personne.class, idPersonne); + } catch (DataRetrievalFailureException e) { + throw new DataNotFoundException(e); + } } /** {@inheritDoc} */ @Override public Personne loadPersonne(String courriel) throws DataNotFoundException { - AssertTools.assertNotNull(courriel); - return dao.read(Personne.class, "courriel", courriel); + AssertTools.assertNotNull(courriel); + return dao.read(Personne.class, "courriel", courriel); } /** {@inheritDoc} */ @Override public Utilisateur loadUtilisateur(Integer idPersonne) throws DataNotFoundException { - AssertTools.assertNotNull(idPersonne); - try { - return dao.read(Utilisateur.class, idPersonne); - } catch (DataRetrievalFailureException e) { - throw new DataNotFoundException(e); - } + AssertTools.assertNotNull(idPersonne); + try { + return dao.read(Utilisateur.class, idPersonne); + } catch (DataRetrievalFailureException e) { + throw new DataNotFoundException(e); + } } /** {@inheritDoc} */ @Override public Utilisateur loadUtilisateur(String courriel) throws DataNotFoundException { - AssertTools.assertNotEmpty(courriel); - Personne personne = loadPersonne(courriel); - if (!(personne instanceof Utilisateur)) { - throw new DataNotFoundException(new ObjectRetrievalFailureException(Utilisateur.class, courriel)); - } - return (Utilisateur) personne; + AssertTools.assertNotEmpty(courriel); + Personne personne = loadPersonne(courriel); + if (!(personne instanceof Utilisateur)) { + throw new DataNotFoundException(new ObjectRetrievalFailureException(Utilisateur.class, courriel)); + } + return (Utilisateur) personne; } /** {@inheritDoc} */ @Override public boolean authenticateUtilisateur(@Normalize(EmailNormalizer.class) String courriel, String passwordHash) { - AssertTools.assertNotEmpty(courriel); - AssertTools.assertNotEmpty(passwordHash); - return dao.exists(PersonneDao.getCriteriaAuthenticateUser(courriel, passwordHash)); + AssertTools.assertNotEmpty(courriel); + AssertTools.assertNotEmpty(passwordHash); + return dao.exists(PersonneDao.getCriteriaAuthenticateUser(courriel, passwordHash)); } /** @@ -289,22 +287,22 @@ * @throws DataConstraintException Si l'utilisateur existe déjà */ private void plainCreateUtilisateur(Utilisateur utilisateur) throws DataConstraintException { - AssertTools.assertNotNull(utilisateur); - LOG.info("createUtilisateur " + utilisateur.getCourriel()); - if (utilisateur.getTypeDroit() == null) { - utilisateur.setTypeDroit(TypeDroit.UTILISATEUR); - } - if (utilisateur.isValide() == null) { - utilisateur.setValide(Boolean.FALSE); - } - dao.create(utilisateur); + AssertTools.assertNotNull(utilisateur); + LOG.info("createUtilisateur " + utilisateur.getCourriel()); + if (utilisateur.getTypeDroit() == null) { + utilisateur.setTypeDroit(TypeDroit.UTILISATEUR); + } + if (utilisateur.isValide() == null) { + utilisateur.setValide(Boolean.FALSE); + } + dao.create(utilisateur); } /** {@inheritDoc} */ @Override public void refreshPersonne(Personne personne) { - AssertTools.assertNotNull(personne); - dao.refresh(personne); + AssertTools.assertNotNull(personne); + dao.refresh(personne); } /** @@ -312,85 +310,85 @@ */ @Override public void rejectUtilisateur(Utilisateur utilisateur) { - try { - deleteUtilisateur(utilisateur, messages.getMessage("reject.subject"), messages.getMessage("reject.text")); - } catch (EmailException e) { - // Quiet - } catch (DataConstraintException e) { - LOG.error(e.getMessage()); - // cas impossible normalement car un utilisateur non validé ne peut avoir créé des entités - } + try { + deleteUtilisateur(utilisateur, messages.getMessage("reject.subject"), messages.getMessage("reject.text")); + } catch (EmailException e) { + // Quiet + } catch (DataConstraintException e) { + LOG.error(e.getMessage()); + // cas impossible normalement car un utilisateur non validé ne peut avoir créé des entités + } } /** {@inheritDoc} */ @Override @Transactional(rollbackFor = { DataNotFoundException.class, EmailException.class }) public void resetPasswordUtilisateur(String courriel) throws DataNotFoundException, EmailException { - LOG.info("reListPasswordUtilisateur " + courriel); - Utilisateur utilisateur; - try { - utilisateur = loadUtilisateur(courriel); - } catch (DataNotFoundException e) { - LOG.warn("Unknown e-mail: " + courriel); - throw e; - } + LOG.info("reListPasswordUtilisateur " + courriel); + Utilisateur utilisateur; + try { + utilisateur = loadUtilisateur(courriel); + } catch (DataNotFoundException e) { + LOG.warn("Unknown e-mail: " + courriel); + throw e; + } - String newPassword = PasswordTools.random(); - utilisateur.setPasswordHash(hashPassword(newPassword)); - try { - dao.update(utilisateur); - } catch (DataConstraintException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - mailService.sendMail(utilisateur, messages.getMessage("updatePassword.subject"), - messages.getMessage("updatePassword.text", new Object[] { newPassword })); + String newPassword = PasswordTools.random(); + utilisateur.setPasswordHash(hashPassword(newPassword)); + try { + dao.update(utilisateur); + } catch (DataConstraintException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + mailService.sendMail(utilisateur, messages.getMessage("updatePassword.subject"), messages.getMessage( + "updatePassword.text", new Object[] { newPassword })); } /** {@inheritDoc} */ @Override public void sendMailAdmins(String subject, String message, String replyTo) throws EmailException { - LOG.info("sendMailAdmins " + subject + " [reply to] " + replyTo); - mailService.sendMail(listAdmins(), messages.getMessage("contact.subject", new String[] { subject }), - messages.getMessage("contact.body", new String[] { replyTo, message }), replyTo); + LOG.info("sendMailAdmins " + subject + " [reply to] " + replyTo); + mailService.sendMail(listAdmins(), messages.getMessage("contact.subject", new String[] { subject }), messages + .getMessage("contact.body", new String[] { replyTo, message }), replyTo); } /** {@inheritDoc} */ @Override @Transactional(rollbackFor = { EmailException.class, DataAccessException.class, UnexpectedException.class }) public Utilisateur updateAndCreateUtilisateur(Personne personne) throws EmailException, DataConstraintException { - LOG.info("updateAndCreateUtilisateur " + personne.getIdPersonne()); - String password = PasswordTools.random(); - try { - dao.update(personne); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - dao.execute(PersonneDao.SQL_CREATE_UTILISATEUR_FROM_PERSONNE, Boolean.TRUE, hashPassword(password), - TypeDroit.UTILISATEUR.ordinal(), personne.getIdPersonne()); - Utilisateur utilisateur; - try { - utilisateur = dao.read(Utilisateur.class, personne.getIdPersonne()); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - mailService.sendMail(utilisateur, messages.getMessage("create.subject"), - messages.getMessage("create.text", new Object[] { password })); - return utilisateur; + LOG.info("updateAndCreateUtilisateur " + personne.getIdPersonne()); + String password = PasswordTools.random(); + try { + dao.update(personne); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + dao.execute(PersonneDao.SQL_CREATE_UTILISATEUR_FROM_PERSONNE, Boolean.TRUE, hashPassword(password), + TypeDroit.UTILISATEUR.ordinal(), personne.getIdPersonne()); + Utilisateur utilisateur; + try { + utilisateur = dao.read(Utilisateur.class, personne.getIdPersonne()); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + mailService.sendMail(utilisateur, messages.getMessage("create.subject"), messages.getMessage("create.text", + new Object[] { password })); + return utilisateur; } /** {@inheritDoc} */ @Override public void updatePersonne(Personne personne) throws DataConstraintException { - LOG.info("updatePersonne " + personne.getIdPersonne()); - try { - dao.update(personne); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updatePersonne " + personne.getIdPersonne()); + try { + dao.update(personne); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** @@ -399,40 +397,40 @@ * @throws DataConstraintException Si l'utilisateur existe déjà (champs uniques) */ private void updateUtilisateur(Utilisateur utilisateur) throws DataConstraintException { - AssertTools.assertNotNull(utilisateur); - LOG.info("updateUtilisateur " + utilisateur.getCourriel()); - try { - dao.update(utilisateur); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(utilisateur); + LOG.info("updateUtilisateur " + utilisateur.getCourriel()); + try { + dao.update(utilisateur); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void updateUtilisateur(Utilisateur utilisateur, boolean admin) throws DataConstraintException { - updateUtilisateur(utilisateur); - if (admin) { - mailService.sendMailQuietly(utilisateur, messages.getMessage("update.subject"), - messages.getMessage("update.text")); - } + updateUtilisateur(utilisateur); + if (admin) { + mailService.sendMailQuietly(utilisateur, messages.getMessage("update.subject"), messages + .getMessage("update.text")); + } } /** {@inheritDoc} */ @Override public void validAndUpdateUtilisateur(Utilisateur utilisateur) throws DataConstraintException { - utilisateur.setValide(true); - updateUtilisateur(utilisateur); - mailService.sendMailQuietly(utilisateur, messages.getMessage("valid.subject"), - messages.getMessage("valid.text")); + utilisateur.setValide(true); + updateUtilisateur(utilisateur); + mailService.sendMailQuietly(utilisateur, messages.getMessage("valid.subject"), messages + .getMessage("valid.text")); } /** {@inheritDoc} */ @Override public boolean updateOrDeletePersonneEnabled(Personne personne, Utilisateur modifieur) { - AssertTools.assertNotNull(personne); - AssertTools.assertNotNull(modifieur); - return !(personne instanceof Utilisateur) || modifieur.getTypeDroit() == TypeDroit.ADMINISTRATEUR; + AssertTools.assertNotNull(personne); + AssertTools.assertNotNull(modifieur); + return !(personne instanceof Utilisateur) || modifieur.getTypeDroit() == TypeDroit.ADMINISTRATEUR; } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ProduitServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ProduitServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/ProduitServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,61 +67,61 @@ /** {@inheritDoc} */ @Override public List<Produit> listProduits(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); + AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - SortedSet<Produit> produits = new TreeSet<Produit>(); - produits.addAll(dao.readList(Extrait.class, "ref")); - produits.addAll(dao.readList(Fraction.class, "ref")); - return new ArrayList<Produit>(produits); - } - // gestion des droits en plus pour les utilisateurs - return new ArrayList<Produit>(listProduitsForUser(utilisateur)); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + SortedSet<Produit> produits = new TreeSet<Produit>(); + produits.addAll(dao.readList(Extrait.class, "ref")); + produits.addAll(dao.readList(Fraction.class, "ref")); + return new ArrayList<Produit>(produits); + } + // gestion des droits en plus pour les utilisateurs + return new ArrayList<Produit>(listProduitsForUser(utilisateur)); } /** {@inheritDoc} */ @Override public SortedSet<Produit> listProduitsForUser(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - SortedSet<Produit> produits = new TreeSet<Produit>(); + AssertTools.assertNotNull(utilisateur); + SortedSet<Produit> produits = new TreeSet<Produit>(); - for (Extraction curExtraction : extractionService.listExtractionsForUser(utilisateur)) { - produits.addAll(curExtraction.getExtraits()); - } - for (Purification curPurification : purificationService.listPurificationsForUser(utilisateur)) { - produits.addAll(curPurification.getFractions()); - } + for (Extraction curExtraction : extractionService.listExtractionsForUser(utilisateur)) { + produits.addAll(curExtraction.getExtraits()); + } + for (Purification curPurification : purificationService.listPurificationsForUser(utilisateur)) { + produits.addAll(curPurification.getFractions()); + } - return produits; + return produits; } /** {@inheritDoc} */ @Override public List<Produit> listProduitsWithoutChildrenOfPuri(Utilisateur utilisateur, Purification purification) { - AssertTools.assertNotNull(utilisateur); - AssertTools.assertNotNull(purification); + AssertTools.assertNotNull(utilisateur); + AssertTools.assertNotNull(purification); - List<Produit> produits = listProduits(utilisateur); + List<Produit> produits = listProduits(utilisateur); - // version itérative (dérécursification) - LinkedList<Fraction> fractionsQueue = new LinkedList<Fraction>(purification.getFractions()); - while (!fractionsQueue.isEmpty()) { - Fraction curFraction = fractionsQueue.remove(); - produits.remove(curFraction); - // LOG.debug("-removeFraction : " + curFraction); + // version itérative (dérécursification) + LinkedList<Fraction> fractionsQueue = new LinkedList<Fraction>(purification.getFractions()); + while (!fractionsQueue.isEmpty()) { + Fraction curFraction = fractionsQueue.remove(); + produits.remove(curFraction); + // LOG.debug("-removeFraction : " + curFraction); - for (Purification curPuriFromFraction : curFraction.getPurificationsSuivantes()) { - fractionsQueue.addAll(curPuriFromFraction.getFractions()); - } - } - return produits; + for (Purification curPuriFromFraction : curFraction.getPurificationsSuivantes()) { + fractionsQueue.addAll(curPuriFromFraction.getFractions()); + } + } + return produits; } /** {@inheritDoc} */ @Override public boolean isProduitReferenced(Produit produit) { - return dao.count(ProduitDao.getCriteriaCountPurifFromProduit(produit.getRef())) > 0 - || dao.count(ProduitDao.getCriteriaCountTestBioFromProduit(produit.getRef())) > 0 - || dao.count(ProduitDao.getCriteriaCountMoleculeFromProduit(produit.getRef())) > 0; + return dao.count(ProduitDao.getCriteriaCountPurifFromProduit(produit.getRef())) > 0 + || dao.count(ProduitDao.getCriteriaCountTestBioFromProduit(produit.getRef())) > 0 + || dao.count(ProduitDao.getCriteriaCountMoleculeFromProduit(produit.getRef())) > 0; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PurificationServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PurificationServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/PurificationServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -73,74 +73,74 @@ /** {@inheritDoc} */ @Override public long countPurifications() { - return dao.count(Purification.class); + return dao.count(Purification.class); } /** {@inheritDoc} */ @Override public void createPurification(Purification purification) throws DataConstraintException { - LOG.info("createPurification: " + purification.getRef()); - dao.create(purification); + LOG.info("createPurification: " + purification.getRef()); + dao.create(purification); } /** {@inheritDoc} */ @Override public void initParamsMethoPuriEffectif(Purification purification) { - AssertTools.assertNotNull(purification); - if (purification.getMethode() != null) { - // rafraichi la méthode pour pouvoir accéder aux paramètres accédés en LAZY - refreshMethodePurification(purification.getMethode()); + AssertTools.assertNotNull(purification); + if (purification.getMethode() != null) { + // rafraichi la méthode pour pouvoir accéder aux paramètres accédés en LAZY + refreshMethodePurification(purification.getMethode()); - refreshMethodePurification(purification.getMethode()); - purification.getParamsMetho().clear(); - for (int paramInd = 0; paramInd < purification.getMethode().getParametres().size(); paramInd++) { - ParamMethoPuri paramMetho = purification.getMethode().getParametres().get(paramInd); + refreshMethodePurification(purification.getMethode()); + purification.getParamsMetho().clear(); + for (int paramInd = 0; paramInd < purification.getMethode().getParametres().size(); paramInd++) { + ParamMethoPuri paramMetho = purification.getMethode().getParametres().get(paramInd); - ParamMethoPuriEffectif effectifParam = new ParamMethoPuriEffectif(); - effectifParam.setParam(paramMetho); - effectifParam.setPurification(purification); + ParamMethoPuriEffectif effectifParam = new ParamMethoPuriEffectif(); + effectifParam.setParam(paramMetho); + effectifParam.setPurification(purification); - // effectifParam.valeur is null - purification.getParamsMetho().add(effectifParam); - // LOG.debug("ajout param : " + paramMetho.getNom()); - } - } + // effectifParam.valeur is null + purification.getParamsMetho().add(effectifParam); + // LOG.debug("ajout param : " + paramMetho.getNom()); + } + } } /** {@inheritDoc} */ @Override public void deletePurification(Purification purification) throws DataConstraintException { - AssertTools.assertNotNull(purification); - LOG.info("deletePurification: " + purification.getRef()); - try { - dao.delete(purification); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(purification); + LOG.info("deletePurification: " + purification.getRef()); + try { + dao.delete(purification); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<Purification> listPurifications(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - // si admin, on ajoute toutes les purifications de la base - return dao.readList(Purification.class, "produit", "ref"); - } - // gestion des droits en plus pour les utilisateurs - return new ArrayList<Purification>(listPurificationsForUser(utilisateur)); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + // si admin, on ajoute toutes les purifications de la base + return dao.readList(Purification.class, "produit", "ref"); + } + // gestion des droits en plus pour les utilisateurs + return new ArrayList<Purification>(listPurificationsForUser(utilisateur)); } /** {@inheritDoc} */ @Override public SortedSet<Purification> listPurificationsForUser(Utilisateur utilisateur) { - SortedSet<Purification> purifications = new TreeSet<Purification>(); - purifications.addAll(utilisateur.getPurificationsCrees()); - addAllPurificationsOfExtractions(purifications, extractionService.listExtractionsForUser(utilisateur)); + SortedSet<Purification> purifications = new TreeSet<Purification>(); + purifications.addAll(utilisateur.getPurificationsCrees()); + addAllPurificationsOfExtractions(purifications, extractionService.listExtractionsForUser(utilisateur)); - return purifications; + return purifications; } /** @@ -149,168 +149,168 @@ * @param extractions l'ensemble des extractions sources */ private void addAllPurificationsOfExtractions(Set<Purification> purifications, Set<Extraction> extractions) { - for (Extraction curExtraction : extractions) { - for (Extrait curExtrait : curExtraction.getExtraits()) { - for (Purification curPurification : curExtrait.getPurificationsSuivantes()) { - purifications.add(curPurification); + for (Extraction curExtraction : extractions) { + for (Extrait curExtrait : curExtraction.getExtraits()) { + for (Purification curPurification : curExtrait.getPurificationsSuivantes()) { + purifications.add(curPurification); - // version itérative (dérécursification) - LinkedList<Fraction> fractionsQueue = new LinkedList<Fraction>(curPurification.getFractions()); - while (!fractionsQueue.isEmpty()) { - Fraction curFraction = fractionsQueue.remove(); - for (Purification curPuriFromFraction : curFraction.getPurificationsSuivantes()) { - purifications.add(curPuriFromFraction); - fractionsQueue.addAll(curPuriFromFraction.getFractions()); - } - } - } - } - } + // version itérative (dérécursification) + LinkedList<Fraction> fractionsQueue = new LinkedList<Fraction>(curPurification.getFractions()); + while (!fractionsQueue.isEmpty()) { + Fraction curFraction = fractionsQueue.remove(); + for (Purification curPuriFromFraction : curFraction.getPurificationsSuivantes()) { + purifications.add(curPuriFromFraction); + fractionsQueue.addAll(curPuriFromFraction.getFractions()); + } + } + } + } + } } /** {@inheritDoc} */ @Override public boolean isPurificationUnique(Purification purification) { - AssertTools.assertNotNull(purification); + AssertTools.assertNotNull(purification); - // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) - if (!dao.exists(Purification.class, "ref", purification.getRef())) { - return true; - } + // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) + if (!dao.exists(Purification.class, "ref", purification.getRef())) { + return true; + } - Purification puriWithSameVal; - try { - puriWithSameVal = dao.read(Purification.class, "ref", purification.getRef()); - dao.evict(puriWithSameVal); - } catch (DataNotFoundException e) { - return true; // never call, cover by dao.exists... - } - // in case of new record, id is null - return purification.getIdPurification() != null - && purification.getIdPurification().equals(puriWithSameVal.getIdPurification()); + Purification puriWithSameVal; + try { + puriWithSameVal = dao.read(Purification.class, "ref", purification.getRef()); + dao.evict(puriWithSameVal); + } catch (DataNotFoundException e) { + return true; // never call, cover by dao.exists... + } + // in case of new record, id is null + return purification.getIdPurification() != null + && purification.getIdPurification().equals(puriWithSameVal.getIdPurification()); } /** {@inheritDoc} */ @Override public Purification loadPurification(Integer idPurification) throws DataNotFoundException { - return dao.read(Purification.class, idPurification); + return dao.read(Purification.class, idPurification); } /** {@inheritDoc} */ @Override public Purification loadPurification(String nom) throws DataNotFoundException { - return dao.read(Purification.class, "nom", nom); + return dao.read(Purification.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updatePurification(Purification purification) throws DataConstraintException { - LOG.info("updatePurification: " + purification.getRef()); - try { - dao.update(purification); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updatePurification: " + purification.getRef()); + try { + dao.update(purification); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void refreshPurification(Purification purification) { - dao.refresh(purification); + dao.refresh(purification); } /** {@inheritDoc} */ @Override public boolean updateOrdeletePurificationEnabled(Purification purification, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == purification.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == purification.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public void createMethodePurification(MethodePurification methode) throws DataConstraintException { - LOG.info("createMethodePurification: " + methode.getNom()); - dao.create(methode); + LOG.info("createMethodePurification: " + methode.getNom()); + dao.create(methode); } /** {@inheritDoc} */ @Override public void deleteMethodePurification(MethodePurification methode) throws DataConstraintException { - AssertTools.assertNotNull(methode); - LOG.info("deleteMethodePurification: " + methode.getNom()); - try { - dao.delete(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(methode); + LOG.info("deleteMethodePurification: " + methode.getNom()); + try { + dao.delete(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<MethodePurification> listMethodesPurification() { - return dao.readList(MethodePurification.class, "nom"); + return dao.readList(MethodePurification.class, "nom"); } /** {@inheritDoc} */ @Override public MethodePurification loadMethodePurification(Integer idMethode) throws DataNotFoundException { - return dao.read(MethodePurification.class, idMethode); + return dao.read(MethodePurification.class, idMethode); } /** {@inheritDoc} */ @Override public MethodePurification loadMethodePurification(String nom) throws DataNotFoundException { - return dao.read(MethodePurification.class, "nom", nom); + return dao.read(MethodePurification.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateMethodePurification(MethodePurification methode) throws DataConstraintException { - LOG.info("updateMethodePurification: " + methode.getNom()); - try { - dao.update(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateMethodePurification: " + methode.getNom()); + try { + dao.update(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void refreshMethodePurification(MethodePurification methode) { - AssertTools.assertNotNull(methode); - dao.refresh(methode); + AssertTools.assertNotNull(methode); + dao.refresh(methode); } /** {@inheritDoc} */ @Override public boolean isParamMethoPuriReferenced(ParamMethoPuri paramMetho) { - AssertTools.assertNotNull(paramMetho); - AssertTools.assertNotNull(paramMetho.getIdParamMethoPuri()); - return dao.count(PurificationDao.COUNT_PURIF_WITH_PARAM_METHO, paramMetho.getIdParamMethoPuri()) > 0; + AssertTools.assertNotNull(paramMetho); + AssertTools.assertNotNull(paramMetho.getIdParamMethoPuri()); + return dao.count(PurificationDao.COUNT_PURIF_WITH_PARAM_METHO, paramMetho.getIdParamMethoPuri()) > 0; } /** {@inheritDoc} */ @Override public boolean isFractionUnique(Fraction fraction) { - AssertTools.assertNotNull(fraction); + AssertTools.assertNotNull(fraction); - // unique if it doesn't exist different value or if it exists with the same id (so same row in the db) - if (!dao.exists(Fraction.class, "ref", fraction.getRef())) { - return true; - } - Fraction fractWithSameVal; - try { - fractWithSameVal = dao.read(Fraction.class, "ref", fraction.getRef()); - dao.evict(fractWithSameVal); - } catch (DataNotFoundException e) { - return true; // never call, covers by dao.exists... - } - // in case of new record, id is null - return fraction.getId() != null && fraction.getId().equals(fractWithSameVal.getId()); + // unique if it doesn't exist different value or if it exists with the same id (so same row in the db) + if (!dao.exists(Fraction.class, "ref", fraction.getRef())) { + return true; + } + Fraction fractWithSameVal; + try { + fractWithSameVal = dao.read(Fraction.class, "ref", fraction.getRef()); + dao.evict(fractWithSameVal); + } catch (DataNotFoundException e) { + return true; // never call, covers by dao.exists... + } + // in case of new record, id is null + return fraction.getId() != null && fraction.getId().equals(fractWithSameVal.getId()); } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SearchServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SearchServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SearchServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -77,79 +77,80 @@ /** {@inheritDoc} */ @Override public void reIndex() { - long before = System.currentTimeMillis(); - if (LOG.isInfoEnabled()) { - LOG.info("Starting full rebuild on lucene index"); - } - // get hibernate search session - Session session = sessionFactory.getCurrentSession(); - FullTextSession fullTextSession = Search.getFullTextSession(session); - try { - MassIndexer indexer = fullTextSession.createIndexer(); - indexer.threadsForSubsequentFetching(1); - indexer.startAndWait(); + long before = System.currentTimeMillis(); + if (LOG.isInfoEnabled()) { + LOG.info("Starting full rebuild on lucene index"); + } + // get hibernate search session + Session session = sessionFactory.getCurrentSession(); + FullTextSession fullTextSession = Search.getFullTextSession(session); + try { + MassIndexer indexer = fullTextSession.createIndexer(); + indexer.threadsForSubsequentFetching(1); + indexer.startAndWait(); - if (LOG.isInfoEnabled()) { - long after = System.currentTimeMillis(); - LOG.info("Lucene index rebuilded in " + (after-before) + " ms"); - } - } catch (InterruptedException ex) { - throw new UnexpectedException("Can't rebuild index", ex); - } + if (LOG.isInfoEnabled()) { + long after = System.currentTimeMillis(); + LOG.info("Lucene index rebuilded in " + (after - before) + " ms"); + } + } catch (InterruptedException ex) { + throw new UnexpectedException("Can't rebuild index", ex); + } } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public SearchResult search(String strQuery, Utilisateur utilisateur) { - SearchResult result = new SearchResult(); + SearchResult result = new SearchResult(); - // get hibernate search session - Session session = sessionFactory.getCurrentSession(); - FullTextSession fullTextSession = Search.getFullTextSession(session); + // get hibernate search session + Session session = sessionFactory.getCurrentSession(); + FullTextSession fullTextSession = Search.getFullTextSession(session); - // le flushToIndexes n'est pas correct ici, il sert juste a faire - // passer les tests pour que les indexes lucene contiennent des données - // nécéssaire car il ne sont écrits que lorsque Spring commmit la - // transaction (c'est à dire jamais dans les tests) - fullTextSession.flushToIndexes(); - //fullTextSession.setFlushMode(FlushMode.MANUAL); - //fullTextSession.setCacheMode(CacheMode.IGNORE); + // le flushToIndexes n'est pas correct ici, il sert juste a faire + // passer les tests pour que les indexes lucene contiennent des données + // nécéssaire car il ne sont écrits que lorsque Spring commmit la + // transaction (c'est à dire jamais dans les tests) + fullTextSession.flushToIndexes(); + //fullTextSession.setFlushMode(FlushMode.MANUAL); + //fullTextSession.setCacheMode(CacheMode.IGNORE); - try { - // wrap Lucene query in a org.hibernate.Query - org.hibernate.Query hibSpecimen = getQuery(fullTextSession, Specimen.class, strQuery, utilisateur); - org.hibernate.Query hibLot = getQuery(fullTextSession, Lot.class, strQuery, utilisateur); - org.hibernate.Query hibExtraction = getQuery(fullTextSession, Extraction.class, strQuery, utilisateur); - org.hibernate.Query hibPurification = getQuery(fullTextSession, Purification.class, strQuery, utilisateur); - org.hibernate.Query hibResultatTestBio = getQuery(fullTextSession, ResultatTestBio.class, strQuery, utilisateur); - org.hibernate.Query hibStation = getQuery(fullTextSession, Station.class, strQuery, utilisateur); - org.hibernate.Query hibMolecule = getQuery(fullTextSession, Molecule.class, strQuery, utilisateur); + try { + // wrap Lucene query in a org.hibernate.Query + org.hibernate.Query hibSpecimen = getQuery(fullTextSession, Specimen.class, strQuery, utilisateur); + org.hibernate.Query hibLot = getQuery(fullTextSession, Lot.class, strQuery, utilisateur); + org.hibernate.Query hibExtraction = getQuery(fullTextSession, Extraction.class, strQuery, utilisateur); + org.hibernate.Query hibPurification = getQuery(fullTextSession, Purification.class, strQuery, utilisateur); + org.hibernate.Query hibResultatTestBio = getQuery(fullTextSession, ResultatTestBio.class, strQuery, + utilisateur); + org.hibernate.Query hibStation = getQuery(fullTextSession, Station.class, strQuery, utilisateur); + org.hibernate.Query hibMolecule = getQuery(fullTextSession, Molecule.class, strQuery, utilisateur); - // execute search - List<Specimen> specimens = hibSpecimen.list(); - List<Lot> lots = hibLot.list(); - List<Extraction> extractions = hibExtraction.list(); - List<Purification> purifications = hibPurification.list(); - List<ResultatTestBio> resultatTestBios = hibResultatTestBio.list(); - List<Station> resultatStations = hibStation.list(); - List<Molecule> resultatMolecules = hibMolecule.list(); - - result.setSpecimens(specimens); - result.setLots(lots); - result.setExtractions(extractions); - result.setPurifications(purifications); - result.setResultatTestBios(resultatTestBios); - result.setStations(resultatStations); - result.setMolecules(resultatMolecules); + // execute search + List<Specimen> specimens = hibSpecimen.list(); + List<Lot> lots = hibLot.list(); + List<Extraction> extractions = hibExtraction.list(); + List<Purification> purifications = hibPurification.list(); + List<ResultatTestBio> resultatTestBios = hibResultatTestBio.list(); + List<Station> resultatStations = hibStation.list(); + List<Molecule> resultatMolecules = hibMolecule.list(); - } catch (ParseException ex) { - throw new UnexpectedException("Can't parse query", ex); - } + result.setSpecimens(specimens); + result.setLots(lots); + result.setExtractions(extractions); + result.setPurifications(purifications); + result.setResultatTestBios(resultatTestBios); + result.setStations(resultatStations); + result.setMolecules(resultatMolecules); - //tx.commit(); - //session.close(); - return result; + } catch (ParseException ex) { + throw new UnexpectedException("Can't parse query", ex); + } + + //tx.commit(); + //session.close(); + return result; } /** @@ -163,36 +164,36 @@ * @return hibernate query implemented by lucene query * @throws ParseException */ - protected org.hibernate.Query getQuery(FullTextSession fullTextSession, - Class<?> clazz, String strQuery, Utilisateur utilisateur) throws ParseException { + protected org.hibernate.Query getQuery(FullTextSession fullTextSession, Class<?> clazz, String strQuery, + Utilisateur utilisateur) throws ParseException { - // get search factory - SearchFactory searchFactory = fullTextSession.getSearchFactory(); + // get search factory + SearchFactory searchFactory = fullTextSession.getSearchFactory(); - // build a multi field query parser to search in all fields - IndexReader reader = searchFactory.getIndexReaderAccessor().open(clazz); - FieldInfos fieldInfos = ReaderUtil.getMergedFieldInfos(reader); - String[] fieldArray = new String[fieldInfos.size()]; - for (int i = 0 ; i < fieldInfos.size(); i++) { - fieldArray[i] = fieldInfos.fieldName(i); - } - QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_36, fieldArray, searchFactory.getAnalyzer(clazz)); - searchFactory.getIndexReaderAccessor().close(reader); + // build a multi field query parser to search in all fields + IndexReader reader = searchFactory.getIndexReaderAccessor().open(clazz); + FieldInfos fieldInfos = ReaderUtil.getMergedFieldInfos(reader); + String[] fieldArray = new String[fieldInfos.size()]; + for (int i = 0; i < fieldInfos.size(); i++) { + fieldArray[i] = fieldInfos.fieldName(i); + } + QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_36, fieldArray, searchFactory.getAnalyzer(clazz)); + searchFactory.getIndexReaderAccessor().close(reader); - // autorisation de "*" en premier caractere - parser.setAllowLeadingWildcard(true); - // change default operator to AND - parser.setDefaultOperator(Operator.AND); - // create lucene query - Query query = parser.parse(strQuery); + // autorisation de "*" en premier caractere + parser.setAllowLeadingWildcard(true); + // change default operator to AND + parser.setDefaultOperator(Operator.AND); + // create lucene query + Query query = parser.parse(strQuery); - // convert lucene query to hibernate query - FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, clazz); + // convert lucene query to hibernate query + FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, clazz); - // add security filter - FullTextFilter filter = hibQuery.enableFullTextFilter("utilisateur-" + clazz.getSimpleName()); - filter.setParameter("utilisateur", utilisateur); + // add security filter + FullTextFilter filter = hibQuery.enableFullTextFilter("utilisateur-" + clazz.getSimpleName()); + filter.setParameter("utilisateur", utilisateur); - return hibQuery; + return hibQuery; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SpecimenServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SpecimenServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/SpecimenServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -64,153 +64,153 @@ /** {@inheritDoc} */ @Override public long countSpecimens() { - return dao.count(Specimen.class); + return dao.count(Specimen.class); } /** {@inheritDoc} */ @Override public void createSpecimen(Specimen specimen) throws DataConstraintException { - LOG.info("createSpecimen: " + specimen.getRef()); - dao.create(specimen); + LOG.info("createSpecimen: " + specimen.getRef()); + dao.create(specimen); } /** {@inheritDoc} */ @Override public void deleteSpecimen(Specimen specimen) throws DataConstraintException { - AssertTools.assertNotNull(specimen); - LOG.info("deleteSpecimen " + specimen.getRef()); - try { - dao.delete(specimen); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(specimen); + LOG.info("deleteSpecimen " + specimen.getRef()); + try { + dao.delete(specimen); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<Specimen> listSpecimens(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - return dao.readList(Specimen.class, "ref"); - } - SortedSet<Specimen> specimens = listSpecimensForUser(utilisateur); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + return dao.readList(Specimen.class, "ref"); + } + SortedSet<Specimen> specimens = listSpecimensForUser(utilisateur); - return new ArrayList<Specimen>(specimens); + return new ArrayList<Specimen>(specimens); } /** {@inheritDoc} */ @Override public SortedSet<Specimen> listSpecimensForUser(Utilisateur utilisateur) { - // gestion des droits en plus pour les utilisateurs - SortedSet<Specimen> specimens = new TreeSet<Specimen>(); + // gestion des droits en plus pour les utilisateurs + SortedSet<Specimen> specimens = new TreeSet<Specimen>(); - // droits donnés pour les spécimens créés par l'utilisateur - specimens.addAll(utilisateur.getSpecimensCrees()); + // droits donnés pour les spécimens créés par l'utilisateur + specimens.addAll(utilisateur.getSpecimensCrees()); - // droits donnés pour l'ensemble des spécimens qui a pour station une station prospectée par les campagnes dont - // l'utilisateur a les droits - List<Campagne> campagnes = new ArrayList<Campagne>(); - campagnes.addAll(utilisateur.getCampagnesCreees()); - campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); - for (Campagne c : campagnes) { - for (Station st : c.getStations()) { - specimens.addAll(st.getSpecimensRattaches()); - } - } - // droits donnés également pour le spécimen de référence de chaque lot dont l'utilisateur a les droits - List<Lot> lots = new ArrayList<Lot>(); - lots.addAll(utilisateur.getLotsCrees()); - lots.addAll(utilisateur.getLotsDroits().keySet()); - for (Lot l : lots) { - // droit sur le spécimen de référence du lot - if (l.getSpecimenRef().getStation() != null) { - specimens.add(l.getSpecimenRef()); - } - } - return specimens; + // droits donnés pour l'ensemble des spécimens qui a pour station une station prospectée par les campagnes dont + // l'utilisateur a les droits + List<Campagne> campagnes = new ArrayList<Campagne>(); + campagnes.addAll(utilisateur.getCampagnesCreees()); + campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); + for (Campagne c : campagnes) { + for (Station st : c.getStations()) { + specimens.addAll(st.getSpecimensRattaches()); + } + } + // droits donnés également pour le spécimen de référence de chaque lot dont l'utilisateur a les droits + List<Lot> lots = new ArrayList<Lot>(); + lots.addAll(utilisateur.getLotsCrees()); + lots.addAll(utilisateur.getLotsDroits().keySet()); + for (Lot l : lots) { + // droit sur le spécimen de référence du lot + if (l.getSpecimenRef().getStation() != null) { + specimens.add(l.getSpecimenRef()); + } + } + return specimens; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listSpecimenEmbranchements() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_EMBRANCHEMENTS); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_EMBRANCHEMENTS); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listSpecimenFamilles() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_FAMILLES); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_FAMILLES); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> listSpecimenGenres() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_GENRES); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_GENRES); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listSpecimenEspeces() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_ESPECES); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_ESPECES); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> listSpecimenSousEspeces() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_SOUSESPECES); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_SOUSESPECES); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> listSpecimenVarietes() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_VARIETES); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_SPECIMEN_VARIETES); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> listLieuxDepot() { - return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_LIEUX_DEPOT); + return (List<String>) dao.list(SpecimenDao.CRITERIA_DISTINCT_LIEUX_DEPOT); } /** {@inheritDoc} */ @Override public Specimen loadSpecimen(Integer idSpecimen) throws DataNotFoundException { - AssertTools.assertNotNull(idSpecimen); - return dao.read(Specimen.class, idSpecimen); + AssertTools.assertNotNull(idSpecimen); + return dao.read(Specimen.class, idSpecimen); } /** {@inheritDoc} */ @Override public Specimen loadSpecimen(String ref) throws DataNotFoundException { - AssertTools.assertNotEmpty(ref); - return dao.read(Specimen.class, "ref", ref); + AssertTools.assertNotEmpty(ref); + return dao.read(Specimen.class, "ref", ref); } /** {@inheritDoc} */ @Override public boolean updateOrdeleteSpecimenEnabled(Specimen specimen, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == specimen.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == specimen.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public void updateSpecimen(Specimen specimen) throws DataConstraintException { - LOG.info("updateSpecimen " + specimen.getIdSpecimen()); - try { - dao.update(specimen); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateSpecimen " + specimen.getIdSpecimen()); + try { + dao.update(specimen); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/StationServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/StationServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/StationServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -63,109 +63,109 @@ /** {@inheritDoc} */ @Override public long countStations() { - return dao.count(Station.class); + return dao.count(Station.class); } /** {@inheritDoc} */ @Override public void createStation(Station station) throws DataConstraintException { - LOG.info("createStation " + station.getNom()); - dao.create(station); + LOG.info("createStation " + station.getNom()); + dao.create(station); } /** {@inheritDoc} */ @Override public void deleteStation(Station station) throws DataConstraintException { - LOG.info("deleteStation " + station.getIdStation()); - try { - dao.delete(station); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("deleteStation " + station.getIdStation()); + try { + dao.delete(station); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listStationLocalites() { - return (List<String>) dao.list(StationDao.CRITERIA_DISTINCT_STATION_LOCALITES); + return (List<String>) dao.list(StationDao.CRITERIA_DISTINCT_STATION_LOCALITES); } /** {@inheritDoc} */ @Override public List<Station> listStations(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - return dao.readList(Station.class, "nom"); - } - SortedSet<Station> stations = listStationsForUser(utilisateur); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + return dao.readList(Station.class, "nom"); + } + SortedSet<Station> stations = listStationsForUser(utilisateur); - return new ArrayList<Station>(stations); + return new ArrayList<Station>(stations); } /** {@inheritDoc} */ @Override public SortedSet<Station> listStationsForUser(Utilisateur utilisateur) { - // gestion des droits en plus pour les utilisateurs - SortedSet<Station> stations = new TreeSet<Station>(); + // gestion des droits en plus pour les utilisateurs + SortedSet<Station> stations = new TreeSet<Station>(); - // droits donnés pour les stations crées par l'utilisateur - stations.addAll(utilisateur.getStationsCrees()); + // droits donnés pour les stations crées par l'utilisateur + stations.addAll(utilisateur.getStationsCrees()); - // droits donnés pour l'ensemble des stations prospectées des campagnes où l'utilisateur a les droits sur la - // campagne complète - List<Campagne> campagnes = new ArrayList<Campagne>(); - campagnes.addAll(utilisateur.getCampagnesCreees()); - campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); - for (Campagne c : campagnes) { - stations.addAll(c.getStations()); - } - // droits donnés également pour chaque lot qui a des droits particuliers - List<Lot> lots = new ArrayList<Lot>(); - lots.addAll(utilisateur.getLotsCrees()); - lots.addAll(utilisateur.getLotsDroits().keySet()); - for (Lot l : lots) { - // droit sur la station du lot - stations.add(l.getStation()); - // droit sur la station de provenance du spécimen rattaché - if (l.getSpecimenRef().getStation() != null) { - stations.add(l.getSpecimenRef().getStation()); - } - } - return stations; + // droits donnés pour l'ensemble des stations prospectées des campagnes où l'utilisateur a les droits sur la + // campagne complète + List<Campagne> campagnes = new ArrayList<Campagne>(); + campagnes.addAll(utilisateur.getCampagnesCreees()); + campagnes.addAll(utilisateur.getCampagnesDroits().keySet()); + for (Campagne c : campagnes) { + stations.addAll(c.getStations()); + } + // droits donnés également pour chaque lot qui a des droits particuliers + List<Lot> lots = new ArrayList<Lot>(); + lots.addAll(utilisateur.getLotsCrees()); + lots.addAll(utilisateur.getLotsDroits().keySet()); + for (Lot l : lots) { + // droit sur la station du lot + stations.add(l.getStation()); + // droit sur la station de provenance du spécimen rattaché + if (l.getSpecimenRef().getStation() != null) { + stations.add(l.getSpecimenRef().getStation()); + } + } + return stations; } /** {@inheritDoc} */ @Override public Station loadStation(Integer idStation) throws DataNotFoundException { - AssertTools.assertNotNull(idStation); - return dao.read(Station.class, idStation); + AssertTools.assertNotNull(idStation); + return dao.read(Station.class, idStation); } /** {@inheritDoc} */ @Override public Station loadStation(String nom) throws DataNotFoundException { - AssertTools.assertNotEmpty(nom); - return dao.read(Station.class, "nom", nom); + AssertTools.assertNotEmpty(nom); + return dao.read(Station.class, "nom", nom); } /** {@inheritDoc} */ @Override public boolean updateOrdeleteStationEnabled(Station station, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == station.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == station.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public void updateStation(Station station) throws DataConstraintException { - LOG.info("updateStation " + station.getNom()); - try { - dao.update(station); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateStation " + station.getNom()); + try { + dao.update(station); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/TestBioServiceImpl.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/TestBioServiceImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/services/impl/TestBioServiceImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -69,27 +69,27 @@ /** {@inheritDoc} */ @Override public long countResultatsTestsBio() { - return dao.count(TestBioDao.CRITERIA_COUNT_RESULTATS_TYPE_PRODUIT); + return dao.count(TestBioDao.CRITERIA_COUNT_RESULTATS_TYPE_PRODUIT); } /** {@inheritDoc} */ @Override public void createTestBio(TestBio testBio) throws DataConstraintException { - LOG.info("createTestBio: " + testBio.getRef()); - dao.create(testBio); + LOG.info("createTestBio: " + testBio.getRef()); + dao.create(testBio); } /** {@inheritDoc} */ @Override public void deleteTestBio(TestBio testBio) throws DataConstraintException { - AssertTools.assertNotNull(testBio); - LOG.info("deleteTestBio: " + testBio.getRef()); - try { - dao.delete(testBio); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(testBio); + LOG.info("deleteTestBio: " + testBio.getRef()); + try { + dao.delete(testBio); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } @@ -97,250 +97,250 @@ @SuppressWarnings("unchecked") @Override public List<ResultatTestBio> listResultatsTestBio(Utilisateur utilisateur) { - AssertTools.assertNotNull(utilisateur); - if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - // si admin, on ajoute toutes les testBios de la base - return (List<ResultatTestBio>) dao.list(TestBioDao.CRITERIA_LIST_RESULTATS_TYPE_PRODUIT); - } - // gestion des droits en plus pour les utilisateurs - return new ArrayList<ResultatTestBio>(listResultatsTestBioForUser(utilisateur)); + AssertTools.assertNotNull(utilisateur); + if (utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + // si admin, on ajoute toutes les testBios de la base + return (List<ResultatTestBio>) dao.list(TestBioDao.CRITERIA_LIST_RESULTATS_TYPE_PRODUIT); + } + // gestion des droits en plus pour les utilisateurs + return new ArrayList<ResultatTestBio>(listResultatsTestBioForUser(utilisateur)); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public SortedSet<ResultatTestBio> listResultatsTestBioForUser(Utilisateur utilisateur) { - SortedSet<ResultatTestBio> resultats = new TreeSet<ResultatTestBio>(); + SortedSet<ResultatTestBio> resultats = new TreeSet<ResultatTestBio>(); - // liste triée par produit afin d'optimiser - List<ResultatTestBio> allResultTests = (List<ResultatTestBio>) dao - .list(TestBioDao.CRITERIA_LIST_RESULTATS_TYPE_PRODUIT); - for (ResultatTestBio curRes : allResultTests) { - if (lotService.isLotAccessibleByUser(curRes.getLotSource(), utilisateur)) { - resultats.add(curRes); - } - } + // liste triée par produit afin d'optimiser + List<ResultatTestBio> allResultTests = (List<ResultatTestBio>) dao + .list(TestBioDao.CRITERIA_LIST_RESULTATS_TYPE_PRODUIT); + for (ResultatTestBio curRes : allResultTests) { + if (lotService.isLotAccessibleByUser(curRes.getLotSource(), utilisateur)) { + resultats.add(curRes); + } + } - return resultats; + return resultats; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listProduitsTemoins() { - return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_PRODUITS_TEMOINS); + return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_PRODUITS_TEMOINS); } /** {@inheritDoc} */ @Override public boolean isResultatTestBioAccessibleByUser(ResultatTestBio resultatTestBio, Utilisateur utilisateur) { - return lotService.isLotAccessibleByUser(resultatTestBio.getLotSource(), utilisateur); + return lotService.isLotAccessibleByUser(resultatTestBio.getLotSource(), utilisateur); } /** {@inheritDoc} */ @Override public boolean isResultatTestBioUniqueInList(final ResultatTestBio resultatTestBio, final List<ResultatTestBio> list) { - AssertTools.assertNotNull(resultatTestBio.getTypeResultat()); - AssertTools.assertNotNull(resultatTestBio.getRepere()); - // as resultatTestBio is already in list, detect if more of one elements satisfy these conditions - int count = 0; - for (ResultatTestBio curRes : list) { - if (resultatTestBio.getTypeResultat() == TypeResultat.BLANC - && resultatTestBio.getRepere().equals(curRes.getRepere())) { - count++; - } else if (resultatTestBio.getTypeResultat() == TypeResultat.TEMOIN - && resultatTestBio.getRepere().equals(curRes.getRepere()) - && resultatTestBio.getProduitTemoin().equals(curRes.getProduitTemoin())) { - count++; - } else if (resultatTestBio.getTypeResultat() == TypeResultat.PRODUIT - && resultatTestBio.getRepere().equals(curRes.getRepere()) - && resultatTestBio.getProduit().getRef().equals(curRes.getProduit().getRef())) { - count++; - } - } - return count <= 1; + AssertTools.assertNotNull(resultatTestBio.getTypeResultat()); + AssertTools.assertNotNull(resultatTestBio.getRepere()); + // as resultatTestBio is already in list, detect if more of one elements satisfy these conditions + int count = 0; + for (ResultatTestBio curRes : list) { + if (resultatTestBio.getTypeResultat() == TypeResultat.BLANC + && resultatTestBio.getRepere().equals(curRes.getRepere())) { + count++; + } else if (resultatTestBio.getTypeResultat() == TypeResultat.TEMOIN + && resultatTestBio.getRepere().equals(curRes.getRepere()) + && resultatTestBio.getProduitTemoin().equals(curRes.getProduitTemoin())) { + count++; + } else if (resultatTestBio.getTypeResultat() == TypeResultat.PRODUIT + && resultatTestBio.getRepere().equals(curRes.getRepere()) + && resultatTestBio.getProduit().getRef().equals(curRes.getProduit().getRef())) { + count++; + } + } + return count <= 1; } /** {@inheritDoc} */ @Override public boolean isTestBioUnique(TestBio testBio) { - AssertTools.assertNotNull(testBio); + AssertTools.assertNotNull(testBio); - // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) - if (!dao.exists(TestBio.class, "ref", testBio.getRef())) { - return true; - } + // unique if it doesn't exist different value or if it exists but with the same id (so same row in the db) + if (!dao.exists(TestBio.class, "ref", testBio.getRef())) { + return true; + } - TestBio puriWithSameVal; - try { - puriWithSameVal = dao.read(TestBio.class, "ref", testBio.getRef()); - dao.evict(puriWithSameVal); - } catch (DataNotFoundException e) { - return true; // never call, cover by dao.exists... - } - // in case of new record, id is null - return testBio.getIdTestBio() != null && testBio.getIdTestBio().equals(puriWithSameVal.getIdTestBio()); + TestBio puriWithSameVal; + try { + puriWithSameVal = dao.read(TestBio.class, "ref", testBio.getRef()); + dao.evict(puriWithSameVal); + } catch (DataNotFoundException e) { + return true; // never call, cover by dao.exists... + } + // in case of new record, id is null + return testBio.getIdTestBio() != null && testBio.getIdTestBio().equals(puriWithSameVal.getIdTestBio()); } /** {@inheritDoc} */ @Override public TestBio loadTestBio(Integer idTestBio) throws DataNotFoundException { - return dao.read(TestBio.class, idTestBio); + return dao.read(TestBio.class, idTestBio); } /** {@inheritDoc} */ @Override public TestBio loadTestBio(String nom) throws DataNotFoundException { - return dao.read(TestBio.class, "nom", nom); + return dao.read(TestBio.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateTestBio(TestBio testBio) throws DataConstraintException { - LOG.info("updateTestBio: " + testBio.getRef()); - try { - dao.update(testBio); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateTestBio: " + testBio.getRef()); + try { + dao.update(testBio); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void refreshTestBio(TestBio testBio) { - dao.refresh(testBio); + dao.refresh(testBio); } /** {@inheritDoc} */ @Override public boolean updateOrdeleteTestBioEnabled(TestBio testBio, Utilisateur utilisateur) { - return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || utilisateur.getIdPersonne() == testBio.getCreateur().getIdPersonne(); + return utilisateur.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || utilisateur.getIdPersonne() == testBio.getCreateur().getIdPersonne(); } /** {@inheritDoc} */ @Override public void createMethodeTestBio(MethodeTestBio methode) throws DataConstraintException { - LOG.info("createMethodeTest: " + methode.getNom()); - dao.create(methode); + LOG.info("createMethodeTest: " + methode.getNom()); + dao.create(methode); } /** {@inheritDoc} */ @Override public void deleteMethodeTestBio(MethodeTestBio methode) throws DataConstraintException { - AssertTools.assertNotNull(methode); - LOG.info("deleteMethodeTest: " + methode.getNom()); - try { - dao.delete(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(methode); + LOG.info("deleteMethodeTest: " + methode.getNom()); + try { + dao.delete(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<MethodeTestBio> listMethodesTestBio() { - return dao.readList(MethodeTestBio.class, "nom"); + return dao.readList(MethodeTestBio.class, "nom"); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listDomainesMethodes() { - return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_DOMAINES_METHODES); + return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_DOMAINES_METHODES); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<String> listUnitesResultatMethodes() { - return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_UNITES_RESULTAT_METHODES); + return (List<String>) dao.list(TestBioDao.CRITERIA_DISTINCT_UNITES_RESULTAT_METHODES); } /** {@inheritDoc} */ @Override public MethodeTestBio loadMethodeTest(Integer idMethode) throws DataNotFoundException { - return dao.read(MethodeTestBio.class, idMethode); + return dao.read(MethodeTestBio.class, idMethode); } /** {@inheritDoc} */ @Override public MethodeTestBio loadMethodeTest(String nom) throws DataNotFoundException { - return dao.read(MethodeTestBio.class, "nom", nom); + return dao.read(MethodeTestBio.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateMethodeTest(MethodeTestBio methode) throws DataConstraintException { - LOG.info("updateMethodeTest: " + methode.getNom()); - try { - dao.update(methode); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateMethodeTest: " + methode.getNom()); + try { + dao.update(methode); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public void refreshMethodeTestBio(MethodeTestBio methode) { - AssertTools.assertNotNull(methode); - dao.refresh(methode); + AssertTools.assertNotNull(methode); + dao.refresh(methode); } /** {@inheritDoc} */ @Override public void createErreurTest(ErreurTestBio erreurTest) throws DataConstraintException { - LOG.info("createErreurTest: " + erreurTest.getNom()); - dao.create(erreurTest); + LOG.info("createErreurTest: " + erreurTest.getNom()); + dao.create(erreurTest); } /** {@inheritDoc} */ @Override public void deleteErreurTest(ErreurTestBio erreurTest) throws DataConstraintException { - AssertTools.assertNotNull(erreurTest); - LOG.info("deleteErreurTest: " + erreurTest.getNom()); - try { - dao.delete(erreurTest); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + AssertTools.assertNotNull(erreurTest); + LOG.info("deleteErreurTest: " + erreurTest.getNom()); + try { + dao.delete(erreurTest); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } /** {@inheritDoc} */ @Override public List<ErreurTestBio> listErreursTestBio() { - return dao.readList(ErreurTestBio.class, "nom"); + return dao.readList(ErreurTestBio.class, "nom"); } /** {@inheritDoc} */ @Override public ErreurTestBio loadErreurTestBio(Integer idErreurTest) throws DataNotFoundException { - return dao.read(ErreurTestBio.class, idErreurTest); + return dao.read(ErreurTestBio.class, idErreurTest); } /** {@inheritDoc} */ @Override public ErreurTestBio loadErreurTestBio(String nom) throws DataNotFoundException { - return dao.read(ErreurTestBio.class, "nom", nom); + return dao.read(ErreurTestBio.class, "nom", nom); } /** {@inheritDoc} */ @Override public void updateErreurTestBio(ErreurTestBio erreurTest) throws DataConstraintException { - LOG.info("updateErreurTest: " + erreurTest.getNom()); - try { - dao.update(erreurTest); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + LOG.info("updateErreurTest: " + erreurTest.getNom()); + try { + dao.update(erreurTest); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/CampagneNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/CampagneNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/CampagneNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,12 +37,12 @@ /** {@inheritDoc} */ @Override public Campagne normalize(Campagne campagne) { - AssertTools.assertNotNull(campagne); - // Unique fields - campagne.setNom(normalize(UniqueFieldNormalizer.class, campagne.getNom())); - // Autocompleted fields - campagne.setProgramme(new StringTransformer(campagne.getProgramme()).replaceConsecutiveWhitespaces() - .trimToNull().capitalize().toString()); - return campagne; + AssertTools.assertNotNull(campagne); + // Unique fields + campagne.setNom(normalize(UniqueFieldNormalizer.class, campagne.getNom())); + // Autocompleted fields + campagne.setProgramme(new StringTransformer(campagne.getProgramme()).replaceConsecutiveWhitespaces() + .trimToNull().capitalize().toString()); + return campagne; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ConfigNameNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ConfigNameNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ConfigNameNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -34,6 +34,6 @@ /** {@inheritDoc} */ @Override protected String normalize(String uniqueName) { - return new StringTransformer(uniqueName).replaceConsecutiveWhitespaces().trimToNull().toString(); + return new StringTransformer(uniqueName).replaceConsecutiveWhitespaces().trimToNull().toString(); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/DocumentNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/DocumentNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/DocumentNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,9 +35,9 @@ /** {@inheritDoc} */ @Override protected Document normalize(Document document) { - AssertTools.assertNotNull(document); - // Unique field - document.setTitre(Normalizer.normalize(ConfigNameNormalizer.class, document.getTitre())); - return document; + AssertTools.assertNotNull(document); + // Unique field + document.setTitre(Normalizer.normalize(ConfigNameNormalizer.class, document.getTitre())); + return document; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/EmailNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/EmailNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/EmailNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,6 +35,6 @@ /** {@inheritDoc} */ @Override public String normalize(String email) { - return new StringTransformer(email).trimToNull().toLowerCase().toString(); + return new StringTransformer(email).trimToNull().toLowerCase().toString(); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ErreurTestNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ErreurTestNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ErreurTestNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,9 +35,9 @@ /** {@inheritDoc} */ @Override protected ErreurTestBio normalize(ErreurTestBio erreurTest) { - AssertTools.assertNotNull(erreurTest); - // Unique fields - erreurTest.setNom(Normalizer.normalize(ConfigNameNormalizer.class, erreurTest.getNom())); - return erreurTest; + AssertTools.assertNotNull(erreurTest); + // Unique fields + erreurTest.setNom(Normalizer.normalize(ConfigNameNormalizer.class, erreurTest.getNom())); + return erreurTest; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ExtractionNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ExtractionNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/ExtractionNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,13 +36,13 @@ /** {@inheritDoc} */ @Override protected Extraction normalize(Extraction extraction) { - AssertTools.assertNotNull(extraction); - // Unique fields - extraction.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, extraction.getRef())); - for (Extrait curExtrait : extraction.getExtraits()) { - curExtrait.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, curExtrait.getRef())); - } - return extraction; + AssertTools.assertNotNull(extraction); + // Unique fields + extraction.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, extraction.getRef())); + for (Extrait curExtrait : extraction.getExtraits()) { + curExtrait.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, curExtrait.getRef())); + } + return extraction; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/LotNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/LotNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/LotNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,9 +36,9 @@ /** {@inheritDoc} */ @Override protected Lot normalize(Lot lot) { - AssertTools.assertNotNull(lot); - // Unique fields - lot.setRef(normalize(UniqueFieldNormalizer.class, lot.getRef())); - return lot; + AssertTools.assertNotNull(lot); + // Unique fields + lot.setRef(normalize(UniqueFieldNormalizer.class, lot.getRef())); + return lot; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeExtractionNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeExtractionNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeExtractionNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,12 +36,12 @@ /** {@inheritDoc} */ @Override protected MethodeExtraction normalize(MethodeExtraction methodeExtraction) { - AssertTools.assertNotNull(methodeExtraction); - // Unique fields - methodeExtraction.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodeExtraction.getNom())); - for (TypeExtrait curType : methodeExtraction.getTypesEnSortie()) { - curType.setInitiales(Normalizer.normalize(ConfigNameNormalizer.class, curType.getInitiales())); - } - return methodeExtraction; + AssertTools.assertNotNull(methodeExtraction); + // Unique fields + methodeExtraction.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodeExtraction.getNom())); + for (TypeExtrait curType : methodeExtraction.getTypesEnSortie()) { + curType.setInitiales(Normalizer.normalize(ConfigNameNormalizer.class, curType.getInitiales())); + } + return methodeExtraction; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodePurificationNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodePurificationNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodePurificationNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,13 +36,13 @@ /** {@inheritDoc} */ @Override protected MethodePurification normalize(MethodePurification methodePurification) { - AssertTools.assertNotNull(methodePurification); - // Unique fields - methodePurification.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodePurification.getNom())); - for (ParamMethoPuri curParam : methodePurification.getParametres()) { - curParam.setNom(Normalizer.normalize(ConfigNameNormalizer.class, curParam.getNom())); - } - return methodePurification; + AssertTools.assertNotNull(methodePurification); + // Unique fields + methodePurification.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodePurification.getNom())); + for (ParamMethoPuri curParam : methodePurification.getParametres()) { + curParam.setNom(Normalizer.normalize(ConfigNameNormalizer.class, curParam.getNom())); + } + return methodePurification; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeTestBioNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeTestBioNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MethodeTestBioNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,18 +36,18 @@ /** {@inheritDoc} */ @Override protected MethodeTestBio normalize(MethodeTestBio methodeTest) { - AssertTools.assertNotNull(methodeTest); - // Unique field - methodeTest.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodeTest.getNom())); - methodeTest.setCible(Normalizer.normalize(ConfigNameNormalizer.class, methodeTest.getCible())); - methodeTest.setDomaine(new StringTransformer(methodeTest.getDomaine()).trimToNull() - .replaceConsecutiveWhitespaces().toString()); - methodeTest.setValeurMesuree(new StringTransformer(methodeTest.getValeurMesuree()).trimToNull() - .replaceConsecutiveWhitespaces().toString()); - methodeTest.setUniteResultat(new StringTransformer(methodeTest.getUniteResultat()).trimToNull() - .replaceConsecutiveWhitespaces().toString()); - methodeTest.setCritereActivite(new StringTransformer(methodeTest.getCritereActivite()).trimToNull() - .replaceConsecutiveWhitespaces().toString()); - return methodeTest; + AssertTools.assertNotNull(methodeTest); + // Unique field + methodeTest.setNom(Normalizer.normalize(ConfigNameNormalizer.class, methodeTest.getNom())); + methodeTest.setCible(Normalizer.normalize(ConfigNameNormalizer.class, methodeTest.getCible())); + methodeTest.setDomaine(new StringTransformer(methodeTest.getDomaine()).trimToNull() + .replaceConsecutiveWhitespaces().toString()); + methodeTest.setValeurMesuree(new StringTransformer(methodeTest.getValeurMesuree()).trimToNull() + .replaceConsecutiveWhitespaces().toString()); + methodeTest.setUniteResultat(new StringTransformer(methodeTest.getUniteResultat()).trimToNull() + .replaceConsecutiveWhitespaces().toString()); + methodeTest.setCritereActivite(new StringTransformer(methodeTest.getCritereActivite()).trimToNull() + .replaceConsecutiveWhitespaces().toString()); + return methodeTest; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MoleculeNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MoleculeNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/MoleculeNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,7 +35,7 @@ /** {@inheritDoc} */ @Override protected Molecule normalize(Molecule molecule) { - AssertTools.assertNotNull(molecule); - return molecule; + AssertTools.assertNotNull(molecule); + return molecule; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PartieNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PartieNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PartieNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,9 +36,9 @@ /** {@inheritDoc} */ @Override protected Partie normalize(Partie partie) { - AssertTools.assertNotNull(partie); - // Unique fields - partie.setNom(Normalizer.normalize(ConfigNameNormalizer.class, partie.getNom())); - return partie; + AssertTools.assertNotNull(partie); + // Unique fields + partie.setNom(Normalizer.normalize(ConfigNameNormalizer.class, partie.getNom())); + return partie; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PersonneNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PersonneNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PersonneNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,13 +37,13 @@ /** {@inheritDoc} */ @Override public Personne normalize(Personne personne) { - AssertTools.assertNotNull(personne); - // Unique fields - personne.setCourriel(normalize(EmailNormalizer.class, personne.getCourriel())); - personne.setNom(new StringTransformer(personne.getNom()).replaceAccents().replaceNonAlpha() - .replaceConsecutiveWhitespaces().trimToNull().toUpperCase().toString()); - personne.setPrenom(new StringTransformer(personne.getPrenom()).replaceAccents().replaceNonAlpha() - .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); - return personne; + AssertTools.assertNotNull(personne); + // Unique fields + personne.setCourriel(normalize(EmailNormalizer.class, personne.getCourriel())); + personne.setNom(new StringTransformer(personne.getNom()).replaceAccents().replaceNonAlpha() + .replaceConsecutiveWhitespaces().trimToNull().toUpperCase().toString()); + personne.setPrenom(new StringTransformer(personne.getPrenom()).replaceAccents().replaceNonAlpha() + .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); + return personne; } } \ No newline at end of file Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PurificationNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PurificationNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/PurificationNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,18 +38,18 @@ /** {@inheritDoc} */ @Override protected Purification normalize(Purification purification) { - AssertTools.assertNotNull(purification); - // Unique fields - purification.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, purification.getRef())); - for (ParamMethoPuriEffectif param : purification.getParamsMetho()) { - param.setValeur(new StringTransformer(param.getValeur()).trimToNull().replaceConsecutiveWhitespaces() - .toString()); - } - for (Fraction curFraction : purification.getFractions()) { - curFraction.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, curFraction.getRef())); - } + AssertTools.assertNotNull(purification); + // Unique fields + purification.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, purification.getRef())); + for (ParamMethoPuriEffectif param : purification.getParamsMetho()) { + param.setValeur(new StringTransformer(param.getValeur()).trimToNull().replaceConsecutiveWhitespaces() + .toString()); + } + for (Fraction curFraction : purification.getFractions()) { + curFraction.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, curFraction.getRef())); + } - return purification; + return purification; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/SpecimenNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/SpecimenNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/SpecimenNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,25 +37,25 @@ /** {@inheritDoc} */ @Override protected Specimen normalize(Specimen specimen) { - AssertTools.assertNotNull(specimen); - // Unique fields - specimen.setRef(normalize(UniqueFieldNormalizer.class, specimen.getRef())); + AssertTools.assertNotNull(specimen); + // Unique fields + specimen.setRef(normalize(UniqueFieldNormalizer.class, specimen.getRef())); - specimen.setEmbranchement(new StringTransformer(specimen.getEmbranchement()).replaceConsecutiveWhitespaces() - .trimToNull().toLowerCase().capitalize().toString()); - specimen.setFamille(new StringTransformer(specimen.getFamille()).replaceConsecutiveWhitespaces().trimToNull() - .toLowerCase().capitalize().toString()); - specimen.setGenre(new StringTransformer(specimen.getGenre()).replaceConsecutiveWhitespaces().trimToNull() - .toLowerCase().capitalize().toString()); - specimen.setEspece(new StringTransformer(specimen.getEspece()).replaceConsecutiveWhitespaces().trimToNull() - .toLowerCase().toString()); - specimen.setSousEspece(new StringTransformer(specimen.getSousEspece()).replaceConsecutiveWhitespaces() - .trimToNull().toLowerCase().toString()); - specimen.setVariete(new StringTransformer(specimen.getVariete()).replaceConsecutiveWhitespaces().trimToNull() - .toLowerCase().toString()); - specimen.setLieuDepot(new StringTransformer(specimen.getLieuDepot()).trimToNull() - .replaceConsecutiveWhitespaces().toString()); + specimen.setEmbranchement(new StringTransformer(specimen.getEmbranchement()).replaceConsecutiveWhitespaces() + .trimToNull().toLowerCase().capitalize().toString()); + specimen.setFamille(new StringTransformer(specimen.getFamille()).replaceConsecutiveWhitespaces().trimToNull() + .toLowerCase().capitalize().toString()); + specimen.setGenre(new StringTransformer(specimen.getGenre()).replaceConsecutiveWhitespaces().trimToNull() + .toLowerCase().capitalize().toString()); + specimen.setEspece(new StringTransformer(specimen.getEspece()).replaceConsecutiveWhitespaces().trimToNull() + .toLowerCase().toString()); + specimen.setSousEspece(new StringTransformer(specimen.getSousEspece()).replaceConsecutiveWhitespaces() + .trimToNull().toLowerCase().toString()); + specimen.setVariete(new StringTransformer(specimen.getVariete()).replaceConsecutiveWhitespaces().trimToNull() + .toLowerCase().toString()); + specimen.setLieuDepot(new StringTransformer(specimen.getLieuDepot()).trimToNull() + .replaceConsecutiveWhitespaces().toString()); - return specimen; + return specimen; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/StationNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/StationNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/StationNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,12 +37,12 @@ /** {@inheritDoc} */ @Override protected Station normalize(Station station) { - AssertTools.assertNotNull(station); - // Unique fields - station.setNom(normalize(UniqueFieldNormalizer.class, station.getNom())); - // Autocompleted fields - station.setLocalite(new StringTransformer(station.getLocalite()).replaceConsecutiveWhitespaces().trimToNull() - .capitalizeFully().toString()); - return station; + AssertTools.assertNotNull(station); + // Unique fields + station.setNom(normalize(UniqueFieldNormalizer.class, station.getNom())); + // Autocompleted fields + station.setLocalite(new StringTransformer(station.getLocalite()).replaceConsecutiveWhitespaces().trimToNull() + .capitalizeFully().toString()); + return station; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TestBioNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TestBioNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TestBioNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,19 +37,19 @@ /** {@inheritDoc} */ @Override protected TestBio normalize(TestBio testBio) { - AssertTools.assertNotNull(testBio); - // Unique fields - testBio.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, testBio.getRef())); - // Autocomplete field - testBio.setOrganismeTesteur(new StringTransformer(testBio.getOrganismeTesteur()) - .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); - for (ResultatTestBio curResult : testBio.getResultats()) { - curResult.setRepere(Normalizer.normalize(UniqueFieldNormalizer.class, curResult.getRepere())); - // Autocomplete field - curResult.setProduitTemoin(new StringTransformer(curResult.getProduitTemoin()) - .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); - } + AssertTools.assertNotNull(testBio); + // Unique fields + testBio.setRef(Normalizer.normalize(UniqueFieldNormalizer.class, testBio.getRef())); + // Autocomplete field + testBio.setOrganismeTesteur(new StringTransformer(testBio.getOrganismeTesteur()) + .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); + for (ResultatTestBio curResult : testBio.getResultats()) { + curResult.setRepere(Normalizer.normalize(UniqueFieldNormalizer.class, curResult.getRepere())); + // Autocomplete field + curResult.setProduitTemoin(new StringTransformer(curResult.getProduitTemoin()) + .replaceConsecutiveWhitespaces().trimToNull().capitalizeFully().toString()); + } - return testBio; + return testBio; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TypeDocumentNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TypeDocumentNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/TypeDocumentNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,9 +35,9 @@ /** {@inheritDoc} */ @Override protected TypeDocument normalize(TypeDocument typeDocument) { - AssertTools.assertNotNull(typeDocument); - // Unique field - typeDocument.setNom(Normalizer.normalize(ConfigNameNormalizer.class, typeDocument.getNom())); - return typeDocument; + AssertTools.assertNotNull(typeDocument); + // Unique field + typeDocument.setNom(Normalizer.normalize(ConfigNameNormalizer.class, typeDocument.getNom())); + return typeDocument; } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/UniqueFieldNormalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/UniqueFieldNormalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/UniqueFieldNormalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -34,7 +34,7 @@ /** {@inheritDoc} */ @Override protected String normalize(String uniqueName) { - return new StringTransformer(uniqueName).replaceAccents().replaceConsecutiveWhitespacesByUnderscore() - .toUpperCase().trimToNull().toString(); + return new StringTransformer(uniqueName).replaceAccents().replaceConsecutiveWhitespacesByUnderscore() + .toUpperCase().trimToNull().toString(); } } Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/Normalizer.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/Normalizer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/Normalizer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,7 +44,7 @@ /** Normalizers cache: normalizerClass + normalizer */ private static final Map<Class<? extends Normalizer<?>>, Normalizer<?>> NORMALIZERS = Collections - .synchronizedMap(new HashMap<Class<? extends Normalizer<?>>, Normalizer<?>>()); + .synchronizedMap(new HashMap<Class<? extends Normalizer<?>>, Normalizer<?>>()); /** * Normalize data @@ -55,23 +55,23 @@ */ @SuppressWarnings("unchecked") public static <T> T normalize(Class<? extends Normalizer<T>> normalizerClass, T object) { - Normalizer<T> normalizer; - synchronized (NORMALIZERS) { - normalizer = (Normalizer<T>) NORMALIZERS.get(normalizerClass); - if (normalizer == null) { - try { - normalizer = normalizerClass.newInstance(); - } catch (InstantiationException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (IllegalAccessException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - NORMALIZERS.put(normalizerClass, normalizer); - } - } - return normalizer.normalize(object); + Normalizer<T> normalizer; + synchronized (NORMALIZERS) { + normalizer = (Normalizer<T>) NORMALIZERS.get(normalizerClass); + if (normalizer == null) { + try { + normalizer = normalizerClass.newInstance(); + } catch (InstantiationException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (IllegalAccessException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + NORMALIZERS.put(normalizerClass, normalizer); + } + } + return normalizer.normalize(object); } /** Modified: trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/NormalizerAspect.java =================================================================== --- trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/NormalizerAspect.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/main/java/nc/ird/cantharella/service/utils/normalizers/utils/NormalizerAspect.java 2013-02-18 07:27:17 UTC (rev 119) @@ -26,7 +26,6 @@ import java.lang.reflect.Method; import java.util.Arrays; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.aspectj.lang.ProceedingJoinPoint; @@ -56,21 +55,21 @@ @SuppressWarnings("unchecked") @Around("execution(* nc.ird.cantharella.service.services.*Service.*(..,@Normalize (*),..))") public Object normalize(ProceedingJoinPoint joinPoint) throws Throwable { - Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); - // LOG.debug(method.getDeclaringClass().getSimpleName() + "." + method.getName() + "(" - // + Arrays.asList(method.getParameterTypes()) + ")"); - Object[] args = joinPoint.getArgs(); - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - for (int i = 0; i < parameterAnnotations.length; ++i) { - for (Annotation annotation : parameterAnnotations[i]) { - if (annotation instanceof Normalize) { - args[i] = Normalizer.normalize((Class<Normalizer<Object>>) ((Normalize) annotation).value(), - args[i]); - LOG.debug("normalize : '" + args[i] + "' in " + method.getDeclaringClass().getSimpleName() + "." - + method.getName() + "(" + Arrays.asList(method.getParameterTypes()) + ")"); - } - } - } - return joinPoint.proceed(args); + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + // LOG.debug(method.getDeclaringClass().getSimpleName() + "." + method.getName() + "(" + // + Arrays.asList(method.getParameterTypes()) + ")"); + Object[] args = joinPoint.getArgs(); + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + for (int i = 0; i < parameterAnnotations.length; ++i) { + for (Annotation annotation : parameterAnnotations[i]) { + if (annotation instanceof Normalize) { + args[i] = Normalizer.normalize((Class<Normalizer<Object>>) ((Normalize) annotation).value(), + args[i]); + LOG.debug("normalize : '" + args[i] + "' in " + method.getDeclaringClass().getSimpleName() + "." + + method.getName() + "(" + Arrays.asList(method.getParameterTypes()) + ")"); + } + } + } + return joinPoint.proceed(args); } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/AbstractServiceTest.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/AbstractServiceTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/AbstractServiceTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -50,6 +50,6 @@ */ @Before public void setUp() { - applicationContext.getAutowireCapableBeanFactory().autowireBean(this); + applicationContext.getAutowireCapableBeanFactory().autowireBean(this); } } \ No newline at end of file Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/ServiceContextTest.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/ServiceContextTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/ServiceContextTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,6 +35,6 @@ */ @Test public void context() { - // + // } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/exceptions/ExcelImportException.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/exceptions/ExcelImportException.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/exceptions/ExcelImportException.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,7 +35,7 @@ * @param message Message */ public ExcelImportException(String message) { - super(message); + super(message); } /** @@ -44,7 +44,7 @@ * @param cause Cause */ public ExcelImportException(String message, Exception cause) { - super(message, cause); + super(message, cause); } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/PersonneServiceTest.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/PersonneServiceTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/PersonneServiceTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,7 +48,7 @@ */ @Test public void checkOrCreateAdmin() throws DataConstraintException { - personneService.checkOrCreateAdmin(); + personneService.checkOrCreateAdmin(); } /** @@ -58,8 +58,8 @@ */ @Test public void load() throws DataNotFoundException, DataConstraintException { - personneService.checkOrCreateAdmin(); - List<Personne> personnes = personneService.listPersonnes(); - personneService.loadPersonne(personnes.get(0).getCourriel().toUpperCase()); + personneService.checkOrCreateAdmin(); + List<Personne> personnes = personneService.listPersonnes(); + personneService.loadPersonne(personnes.get(0).getCourriel().toUpperCase()); } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/SearchServiceTest.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/SearchServiceTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/services/SearchServiceTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -89,7 +89,7 @@ */ @Before public void clearIndex() { - searchService.reIndex(); + searchService.reIndex(); } /** @@ -99,37 +99,37 @@ @Test public void testSearchSpecimen() throws DataConstraintException { - // fix user creation for test - defaultAdmin.setValide(Boolean.TRUE); - personneService.createPersonne(defaultAdmin); + // fix user creation for test + defaultAdmin.setValide(Boolean.TRUE); + personneService.createPersonne(defaultAdmin); - // create some specimens - Specimen specimen1 = new Specimen(); - specimen1.setRef("P175"); - specimen1.setEmbranchement("embranchement 175"); - specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); - specimen1.setCreateur(defaultAdmin); - specimenService.createSpecimen(specimen1); - - Specimen specimen2 = new Specimen(); - specimen2.setRef("P174"); - specimen2.setEmbranchement("embranchement 174"); - specimen2.setTypeOrganisme(TypeOrganisme.CHAMPIGNON); - specimen2.setCreateur(defaultAdmin); - specimenService.createSpecimen(specimen2); - - // test to create some entity - Assert.assertEquals(2, specimenService.countSpecimens()); - - // search into lucene - List<Specimen> specimens = searchService.search("P175", defaultAdmin).getSpecimens(); - Assert.assertEquals(specimen1, specimens.get(0)); - specimens = searchService.search("P174", defaultAdmin).getSpecimens(); - Assert.assertEquals(specimen2, specimens.get(0)); - specimens = searchService.search("P17?", defaultAdmin).getSpecimens(); - Assert.assertEquals(2, specimens.size()); + // create some specimens + Specimen specimen1 = new Specimen(); + specimen1.setRef("P175"); + specimen1.setEmbranchement("embranchement 175"); + specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); + specimen1.setCreateur(defaultAdmin); + specimenService.createSpecimen(specimen1); + + Specimen specimen2 = new Specimen(); + specimen2.setRef("P174"); + specimen2.setEmbranchement("embranchement 174"); + specimen2.setTypeOrganisme(TypeOrganisme.CHAMPIGNON); + specimen2.setCreateur(defaultAdmin); + specimenService.createSpecimen(specimen2); + + // test to create some entity + Assert.assertEquals(2, specimenService.countSpecimens()); + + // search into lucene + List<Specimen> specimens = searchService.search("P175", defaultAdmin).getSpecimens(); + Assert.assertEquals(specimen1, specimens.get(0)); + specimens = searchService.search("P174", defaultAdmin).getSpecimens(); + Assert.assertEquals(specimen2, specimens.get(0)); + specimens = searchService.search("P17?", defaultAdmin).getSpecimens(); + Assert.assertEquals(2, specimens.size()); } - + /** * Test to create some lot and search for it. * @throws DataConstraintException @@ -137,76 +137,76 @@ @Test public void testSearchLot() throws DataConstraintException { - // fix user creation for test - defaultAdmin.setValide(Boolean.TRUE); - personneService.createPersonne(defaultAdmin); + // fix user creation for test + defaultAdmin.setValide(Boolean.TRUE); + personneService.createPersonne(defaultAdmin); - // station - Station station = new Station(); - station.setNom("MT1"); - station.setCodePays("FR"); - station.setCreateur(defaultAdmin); - stationService.createStation(station); + // station + Station station = new Station(); + station.setNom("MT1"); + station.setCodePays("FR"); + station.setCreateur(defaultAdmin); + stationService.createStation(station); - // campagne - Campagne campagne = new Campagne(); - campagne.setNom("BSM-PF1"); - campagne.setDateDeb(new Date()); - campagne.setDateFin(new Date()); - campagne.setCreateur(defaultAdmin); - campagne.setCodePays("FR"); - campagneService.createCampagne(campagne); + // campagne + Campagne campagne = new Campagne(); + campagne.setNom("BSM-PF1"); + campagne.setDateDeb(new Date()); + campagne.setDateFin(new Date()); + campagne.setCreateur(defaultAdmin); + campagne.setCodePays("FR"); + campagneService.createCampagne(campagne); - // create some specimens - Specimen specimen1 = new Specimen(); - specimen1.setRef("P175"); - specimen1.setEmbranchement("Porifera"); - specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); - specimen1.setCreateur(defaultAdmin); - specimenService.createSpecimen(specimen1); + // create some specimens + Specimen specimen1 = new Specimen(); + specimen1.setRef("P175"); + specimen1.setEmbranchement("Porifera"); + specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); + specimen1.setCreateur(defaultAdmin); + specimenService.createSpecimen(specimen1); - // create some lots - Lot lot1 = new Lot(); - lot1.setRef("P164-MHO4"); - lot1.setStation(station); - lot1.setEchantillonPhylo(false); - lot1.setEchantillonColl(false); - lot1.setEchantillonIdent(true); - lot1.setCampagne(campagne); - lot1.setDateRecolte(new Date()); - lot1.setSpecimenRef(specimen1); - lot1.setCreateur(defaultAdmin); - lotService.createLot(lot1); + // create some lots + Lot lot1 = new Lot(); + lot1.setRef("P164-MHO4"); + lot1.setStation(station); + lot1.setEchantillonPhylo(false); + lot1.setEchantillonColl(false); + lot1.setEchantillonIdent(true); + lot1.setCampagne(campagne); + lot1.setDateRecolte(new Date()); + lot1.setSpecimenRef(specimen1); + lot1.setCreateur(defaultAdmin); + lotService.createLot(lot1); - Assert.assertEquals(1, lotService.countLots()); // force sync + Assert.assertEquals(1, lotService.countLots()); // force sync - // search into lucene - List<Lot> lots = searchService.search("MHO4", defaultAdmin).getLots(); - Assert.assertEquals(lot1, lots.get(0)); - lots = searchService.search("Foo", defaultAdmin).getLots(); - Assert.assertTrue(lots.isEmpty()); + // search into lucene + List<Lot> lots = searchService.search("MHO4", defaultAdmin).getLots(); + Assert.assertEquals(lot1, lots.get(0)); + lots = searchService.search("Foo", defaultAdmin).getLots(); + Assert.assertTrue(lots.isEmpty()); - // test de recherche sur les entités liées - lots = searchService.search("porifera", defaultAdmin).getLots(); - Assert.assertEquals(lot1, lots.get(0)); + // test de recherche sur les entités liées + lots = searchService.search("porifera", defaultAdmin).getLots(); + Assert.assertEquals(lot1, lots.get(0)); - // update associated property - specimen1.setEmbranchement("Niphatidae"); - specimenService.updateSpecimen(specimen1); - Assert.assertEquals(1, lotService.countLots()); // force sync - lots = searchService.search("porifera", defaultAdmin).getLots(); - //Assert.assertTrue(lots.isEmpty()); - lots = searchService.search("niphatidae", defaultAdmin).getLots(); - //Assert.assertEquals(lot1, lots.get(0)); + // update associated property + specimen1.setEmbranchement("Niphatidae"); + specimenService.updateSpecimen(specimen1); + Assert.assertEquals(1, lotService.countLots()); // force sync + lots = searchService.search("porifera", defaultAdmin).getLots(); + //Assert.assertTrue(lots.isEmpty()); + lots = searchService.search("niphatidae", defaultAdmin).getLots(); + //Assert.assertEquals(lot1, lots.get(0)); - // update direct entity - lot1.setRef("P175-MT4+5"); - lotService.updateLot(lot1); - Assert.assertEquals(1, lotService.countLots()); // force sync - lots = searchService.search("porifera", defaultAdmin).getLots(); - Assert.assertTrue(lots.isEmpty()); - lots = searchService.search("niphatidae", defaultAdmin).getLots(); - Assert.assertEquals(lot1, lots.get(0)); + // update direct entity + lot1.setRef("P175-MT4+5"); + lotService.updateLot(lot1); + Assert.assertEquals(1, lotService.countLots()); // force sync + lots = searchService.search("porifera", defaultAdmin).getLots(); + Assert.assertTrue(lots.isEmpty()); + lots = searchService.search("niphatidae", defaultAdmin).getLots(); + Assert.assertEquals(lot1, lots.get(0)); } /** @@ -215,108 +215,108 @@ */ @Test public void testSearchResultatTestBio() throws DataConstraintException { - // fix user creation for test - defaultAdmin.setValide(Boolean.TRUE); - personneService.createPersonne(defaultAdmin); + // fix user creation for test + defaultAdmin.setValide(Boolean.TRUE); + personneService.createPersonne(defaultAdmin); - // station - Station station = new Station(); - station.setNom("MT1"); - station.setCodePays("FR"); - station.setCreateur(defaultAdmin); - stationService.createStation(station); + // station + Station station = new Station(); + station.setNom("MT1"); + station.setCodePays("FR"); + station.setCreateur(defaultAdmin); + stationService.createStation(station); - // campagne - Campagne campagne = new Campagne(); - campagne.setNom("BSM-PF1"); - campagne.setDateDeb(new Date()); - campagne.setDateFin(new Date()); - campagne.setCreateur(defaultAdmin); - campagne.setCodePays("FR"); - campagneService.createCampagne(campagne); + // campagne + Campagne campagne = new Campagne(); + campagne.setNom("BSM-PF1"); + campagne.setDateDeb(new Date()); + campagne.setDateFin(new Date()); + campagne.setCreateur(defaultAdmin); + campagne.setCodePays("FR"); + campagneService.createCampagne(campagne); - // create some specimens - Specimen specimen1 = new Specimen(); - specimen1.setRef("P175"); - specimen1.setEmbranchement("Porifera"); - specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); - specimen1.setCreateur(defaultAdmin); - specimenService.createSpecimen(specimen1); + // create some specimens + Specimen specimen1 = new Specimen(); + specimen1.setRef("P175"); + specimen1.setEmbranchement("Porifera"); + specimen1.setTypeOrganisme(TypeOrganisme.PLANTE); + specimen1.setCreateur(defaultAdmin); + specimenService.createSpecimen(specimen1); - // create some lots - Lot lot1 = new Lot(); - lot1.setRef("P164-MHO4"); - lot1.setStation(station); - lot1.setEchantillonPhylo(false); - lot1.setEchantillonColl(false); - lot1.setEchantillonIdent(true); - lot1.setCampagne(campagne); - lot1.setDateRecolte(new Date()); - lot1.setSpecimenRef(specimen1); - lot1.setCreateur(defaultAdmin); - lotService.createLot(lot1); + // create some lots + Lot lot1 = new Lot(); + lot1.setRef("P164-MHO4"); + lot1.setStation(station); + lot1.setEchantillonPhylo(false); + lot1.setEchantillonColl(false); + lot1.setEchantillonIdent(true); + lot1.setCampagne(campagne); + lot1.setDateRecolte(new Date()); + lot1.setSpecimenRef(specimen1); + lot1.setCreateur(defaultAdmin); + lotService.createLot(lot1); - // type extrait - TypeExtrait typeExtrait1 = new TypeExtrait(); - typeExtrait1.setDescription("Type extrait"); - typeExtrait1.setInitiales("TE"); + // type extrait + TypeExtrait typeExtrait1 = new TypeExtrait(); + typeExtrait1.setDescription("Type extrait"); + typeExtrait1.setInitiales("TE"); - // methode extraction - MethodeExtraction methodeExtraction1 = new MethodeExtraction(); - typeExtrait1.setMethodeExtraction(methodeExtraction1); - methodeExtraction1.setNom("MET-01"); - methodeExtraction1.setDescription("Desc"); - methodeExtraction1.setTypesEnSortie(Collections.singletonList(typeExtrait1)); - extractionService.createMethodeExtraction(methodeExtraction1); + // methode extraction + MethodeExtraction methodeExtraction1 = new MethodeExtraction(); + typeExtrait1.setMethodeExtraction(methodeExtraction1); + methodeExtraction1.setNom("MET-01"); + methodeExtraction1.setDescription("Desc"); + methodeExtraction1.setTypesEnSortie(Collections.singletonList(typeExtrait1)); + extractionService.createMethodeExtraction(methodeExtraction1); - // produit - Extrait extrait1 = new Extrait(); - extrait1.setRef("P175-MT1D"); - extrait1.setTypeExtrait(typeExtrait1); - Extraction extraction1 = new Extraction(); - extraction1.setRef("EXT-01"); - extraction1.setExtraits(Collections.singletonList(extrait1)); - extrait1.setExtraction(extraction1); - extraction1.setDate(new Date()); - extraction1.setCreateur(defaultAdmin); - extraction1.setManipulateur(defaultAdmin); - extraction1.setLot(lot1); - extraction1.setMethode(methodeExtraction1); - extractionService.createExtraction(extraction1); + // produit + Extrait extrait1 = new Extrait(); + extrait1.setRef("P175-MT1D"); + extrait1.setTypeExtrait(typeExtrait1); + Extraction extraction1 = new Extraction(); + extraction1.setRef("EXT-01"); + extraction1.setExtraits(Collections.singletonList(extrait1)); + extrait1.setExtraction(extraction1); + extraction1.setDate(new Date()); + extraction1.setCreateur(defaultAdmin); + extraction1.setManipulateur(defaultAdmin); + extraction1.setLot(lot1); + extraction1.setMethode(methodeExtraction1); + extractionService.createExtraction(extraction1); - // methode - MethodeTestBio methodeTestBio1 = new MethodeTestBio(); - methodeTestBio1.setNom("Test method"); - methodeTestBio1.setCible("KB"); - methodeTestBio1.setValeurMesuree("Temparature"); - methodeTestBio1.setDomaine("domain"); - methodeTestBio1.setDescription("Temperature effective"); - methodeTestBio1.setUniteResultat("°C"); - testBioService.createMethodeTestBio(methodeTestBio1); + // methode + MethodeTestBio methodeTestBio1 = new MethodeTestBio(); + methodeTestBio1.setNom("Test method"); + methodeTestBio1.setCible("KB"); + methodeTestBio1.setValeurMesuree("Temparature"); + methodeTestBio1.setDomaine("domain"); + methodeTestBio1.setDescription("Temperature effective"); + methodeTestBio1.setUniteResultat("°C"); + testBioService.createMethodeTestBio(methodeTestBio1); - // test bio - TestBio testBio1 = new TestBio(); - testBio1.setRef("TC-T2"); - testBio1.setMethode(methodeTestBio1); - testBio1.setCreateur(defaultAdmin); - testBio1.setManipulateur(defaultAdmin); - testBio1.setDate(new Date()); - testBio1.setOrganismeTesteur("IRD"); + // test bio + TestBio testBio1 = new TestBio(); + testBio1.setRef("TC-T2"); + testBio1.setMethode(methodeTestBio1); + testBio1.setCreateur(defaultAdmin); + testBio1.setManipulateur(defaultAdmin); + testBio1.setDate(new Date()); + testBio1.setOrganismeTesteur("IRD"); - // resultatTestBio - ResultatTestBio resultatTestBio1 = new ResultatTestBio(); - resultatTestBio1.setRepere("T2-E2"); - resultatTestBio1.setTypeResultat(TypeResultat.PRODUIT); - resultatTestBio1.setActif(true); - resultatTestBio1.setTestBio(testBio1); - resultatTestBio1.setProduit(extrait1); - testBio1.setResultats(Collections.singletonList(resultatTestBio1)); - testBioService.createTestBio(testBio1); + // resultatTestBio + ResultatTestBio resultatTestBio1 = new ResultatTestBio(); + resultatTestBio1.setRepere("T2-E2"); + resultatTestBio1.setTypeResultat(TypeResultat.PRODUIT); + resultatTestBio1.setActif(true); + resultatTestBio1.setTestBio(testBio1); + resultatTestBio1.setProduit(extrait1); + testBio1.setResultats(Collections.singletonList(resultatTestBio1)); + testBioService.createTestBio(testBio1); - Assert.assertEquals(1, testBioService.countResultatsTestsBio()); // force sync + Assert.assertEquals(1, testBioService.countResultatsTestsBio()); // force sync - // test search resultatbio - List<ResultatTestBio> resultatTestBios = searchService.search("BSM-PF1", defaultAdmin).getResultatTestBios(); - Assert.assertFalse(resultatTestBios.isEmpty()); + // test search resultatbio + List<ResultatTestBio> resultatTestBios = searchService.search("BSM-PF1", defaultAdmin).getResultatTestBios(); + Assert.assertFalse(resultatTestBios.isEmpty()); } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnStructure.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnStructure.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnStructure.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,16 +35,16 @@ * Different type of value used for the importation */ public enum ExcelColumnType { - /** string **/ - STRING, - /** integer **/ - INTEGER, - /** float number **/ - REEL, - /** date **/ - DATE, - /** boolean **/ - BOOLEAN + /** string **/ + STRING, + /** integer **/ + INTEGER, + /** float number **/ + REEL, + /** date **/ + DATE, + /** boolean **/ + BOOLEAN } /** Type of the column **/ @@ -60,9 +60,9 @@ * @param required If a value is required for each row of that column */ public ExcelColumnStructure(String name, ExcelColumnType type, boolean required) { - this.name = name; - this.type = type; - this.required = required; + this.name = name; + this.type = type; + this.required = required; } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnsReader.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnsReader.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelColumnsReader.java 2013-02-18 07:27:17 UTC (rev 119) @@ -80,21 +80,21 @@ * @throws ExcelImportException - */ public ExcelColumnsReader(InputStream inputStream, List<ExcelSheetStructure> fileStructureAsked) - throws IOException, ExcelImportException { - POIFSFileSystem file = new POIFSFileSystem(inputStream); - workbook = new HSSFWorkbook(file); + throws IOException, ExcelImportException { + POIFSFileSystem file = new POIFSFileSystem(inputStream); + workbook = new HSSFWorkbook(file); - if (fileStructureAsked.isEmpty()) { - throw new ExcelImportException("The structure given to the Excel Reader doesn't contain any sheet"); - } - this.excelStructureAsked = fileStructureAsked; + if (fileStructureAsked.isEmpty()) { + throw new ExcelImportException("The structure given to the Excel Reader doesn't contain any sheet"); + } + this.excelStructureAsked = fileStructureAsked; - currentSheetStructure = fileStructureAsked.get(0); - currentNumLine = workbook.getSheet(currentSheetStructure.name).getFirstRowNum(); + currentSheetStructure = fileStructureAsked.get(0); + currentNumLine = workbook.getSheet(currentSheetStructure.name).getFirstRowNum(); - columnsIndexes = new HashMap<String, Map<String, Integer>>(); + columnsIndexes = new HashMap<String, Map<String, Integer>>(); - findIndexesColumns(); + findIndexesColumns(); } /** @@ -102,11 +102,11 @@ * @return this names */ public List<String> getSheetNames() { - List<String> names = new ArrayList<String>(); - for (ExcelSheetStructure curSheetStruct : excelStructureAsked) { - names.add(curSheetStruct.name); - } - return names; + List<String> names = new ArrayList<String>(); + for (ExcelSheetStructure curSheetStruct : excelStructureAsked) { + names.add(curSheetStruct.name); + } + return names; } /** @@ -115,43 +115,43 @@ */ private void findIndexesColumns() throws ExcelImportException { - for (ExcelSheetStructure structAsked : excelStructureAsked) { - HSSFSheet curSheet = workbook.getSheet(structAsked.name); - // verify the existance of the sheet - if (curSheet == null) { - throw new ExcelImportException("'" + structAsked.name + "' sheet not found in the specified Excel file"); - } + for (ExcelSheetStructure structAsked : excelStructureAsked) { + HSSFSheet curSheet = workbook.getSheet(structAsked.name); + // verify the existance of the sheet + if (curSheet == null) { + throw new ExcelImportException("'" + structAsked.name + "' sheet not found in the specified Excel file"); + } - columnsIndexes.put(structAsked.name, new HashMap<String, Integer>()); - // verify the existance of the sheet columns - for (ExcelColumnStructure col : structAsked.columns) { - // get the header line - HSSFRow header = curSheet.getRow(curSheet.getFirstRowNum()); - AssertTools.assertNotNull(header); + columnsIndexes.put(structAsked.name, new HashMap<String, Integer>()); + // verify the existance of the sheet columns + for (ExcelColumnStructure col : structAsked.columns) { + // get the header line + HSSFRow header = curSheet.getRow(curSheet.getFirstRowNum()); + AssertTools.assertNotNull(header); - int i = header.getFirstCellNum(); - HSSFCell curCell = header.getCell(i); + int i = header.getFirstCellNum(); + HSSFCell curCell = header.getCell(i); - boolean columnFinded = false; - // look for the colName in the header (blank cell terminate the header) - while (!columnFinded && curCell != null && curCell.getCellType() != Cell.CELL_TYPE_BLANK) { - if (curCell.getStringCellValue().trim().toLowerCase().equals(col.name.toLowerCase())) { - columnFinded = true; - } else { - i++; - curCell = header.getCell(i); - } - } + boolean columnFinded = false; + // look for the colName in the header (blank cell terminate the header) + while (!columnFinded && curCell != null && curCell.getCellType() != Cell.CELL_TYPE_BLANK) { + if (curCell.getStringCellValue().trim().toLowerCase().equals(col.name.toLowerCase())) { + columnFinded = true; + } else { + i++; + curCell = header.getCell(i); + } + } - if (!columnFinded) { - throw new ExcelImportException("'" + col.name + "' not found in the header of the '" - + structAsked.name + "' sheet"); - } + if (!columnFinded) { + throw new ExcelImportException("'" + col.name + "' not found in the header of the '" + + structAsked.name + "' sheet"); + } - // update of the index in the map - columnsIndexes.get(structAsked.name).put(col.name, i); - } - } + // update of the index in the map + columnsIndexes.get(structAsked.name).put(col.name, i); + } + } } /** @@ -162,20 +162,20 @@ */ public List<ExcelColumnStructure> selectSheet(String sheetName) throws ExcelImportException { - Iterator<ExcelSheetStructure> itStructSheet = excelStructureAsked.iterator(); + Iterator<ExcelSheetStructure> itStructSheet = excelStructureAsked.iterator(); - while (itStructSheet.hasNext()) { - ExcelSheetStructure structSheet = itStructSheet.next(); - if (sheetName != null && sheetName.equals(structSheet.name)) { - currentSheetStructure = structSheet; - // +1 for the second line - currentNumLine = workbook.getSheet(currentSheetStructure.name).getFirstRowNum() + 1; - return structSheet.columns; - } - } + while (itStructSheet.hasNext()) { + ExcelSheetStructure structSheet = itStructSheet.next(); + if (sheetName != null && sheetName.equals(structSheet.name)) { + currentSheetStructure = structSheet; + // +1 for the second line + currentNumLine = workbook.getSheet(currentSheetStructure.name).getFirstRowNum() + 1; + return structSheet.columns; + } + } - throw new ExcelImportException("'" + sheetName - + "' is not autorized according to the structure given to the Excel Reader"); + throw new ExcelImportException("'" + sheetName + + "' is not autorized according to the structure given to the Excel Reader"); } /** @@ -184,30 +184,30 @@ * @throws ExcelImportException If error in retrieving a cell value */ public Map<String, Object> readLine() throws ExcelImportException { - Map<String, Object> line = new HashMap<String, Object>(); + Map<String, Object> line = new HashMap<String, Object>(); - HSSFRow row = workbook.getSheet(currentSheetStructure.name).getRow(currentNumLine); - if (row != null) { - for (ExcelColumnStructure curCol : currentSheetStructure.columns) { - Integer indCol = columnsIndexes.get(currentSheetStructure.name).get(curCol.name); - Object cellVal = null; - try { - cellVal = checkColumnValue(getCellValue(row.getCell(indCol)), curCol); - } catch (ExcelImportException e) { - throw new ExcelImportException("Error in retrieving the cell value : sheet '" - + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" - + curCol.name + "'", e); - } catch (RuntimeException e) { - throw new ExcelImportException("Error in retrieving the cell value : sheet '" - + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" - + curCol.name + "'", e); - } + HSSFRow row = workbook.getSheet(currentSheetStructure.name).getRow(currentNumLine); + if (row != null) { + for (ExcelColumnStructure curCol : currentSheetStructure.columns) { + Integer indCol = columnsIndexes.get(currentSheetStructure.name).get(curCol.name); + Object cellVal = null; + try { + cellVal = checkColumnValue(getCellValue(row.getCell(indCol)), curCol); + } catch (ExcelImportException e) { + throw new ExcelImportException("Error in retrieving the cell value : sheet '" + + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" + + curCol.name + "'", e); + } catch (RuntimeException e) { + throw new ExcelImportException("Error in retrieving the cell value : sheet '" + + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" + + curCol.name + "'", e); + } - line.put(curCol.name, cellVal); - } - currentNumLine++; - } - return line; + line.put(curCol.name, cellVal); + } + currentNumLine++; + } + return line; } /** @@ -219,79 +219,78 @@ * @throws ExcelImportException If the cellValue doesn't respect the expected type */ private Object checkColumnValue(Object cellValue, ExcelColumnStructure curCol) throws ExcelImportException { - // check is it required and no value - if (cellValue == null && curCol.required) { - throw new ExcelImportException("Value required for the cell value : sheet '" + currentSheetStructure.name - + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); - } - // check the good type of value - switch (curCol.type) { - case STRING: - if (cellValue instanceof Double) { - Double doubleVal = (Double) cellValue; - if (new Double(Math.round(doubleVal)) == doubleVal) { - // if no float part - return doubleVal.toString(); - } - // with float part - String strVal = doubleVal.toString(); - return strVal.substring(0, strVal.length() - 2); - } - // if not a numeric - if (cellValue == null) { - return ""; - } - return cellValue.toString(); - case REEL: - if (cellValue instanceof Double) { - return cellValue; - } - // if not a numeric, exception - throw new ExcelImportException("The cell value must be a reel : sheet '" + currentSheetStructure.name - + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); - case INTEGER: - if (cellValue instanceof Double) { - Double doubleVal = (Double) cellValue; - if (new Double(Math.round(doubleVal)) == doubleVal) { - // if it's an integer, ok - return doubleVal.intValue(); - } - // if it's a float - throw new ExcelImportException("The cell value must be a integer : sheet '" - + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" - + curCol.name + "'"); - } - throw new ExcelImportException("The cell value must be a integer : sheet '" - + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" - + curCol.name + "'"); - case DATE: - if (cellValue instanceof Date) { - return cellValue; - } - // is it's not a date - throw new ExcelImportException("The cell value must be a date : sheet '" + currentSheetStructure.name - + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); - case BOOLEAN: - if (cellValue instanceof Boolean) { - return cellValue; - } else if (cellValue instanceof String - && (StringUtils.lowerCase(StringUtils.trim(TRUE_STRING)).equals( - StringUtils.lowerCase(StringUtils.trim((String) cellValue))) || StringUtils.lowerCase( - StringUtils.trim(FALSE_STRING)).equals( - StringUtils.lowerCase(StringUtils.trim((String) cellValue))))) { - // if "true" or "false" are written in string - if (StringUtils.lowerCase(StringUtils.trim(TRUE_STRING)).equals( - StringUtils.lowerCase(StringUtils.trim((String) cellValue)))) { - return true; - } - return false; - } - // is it's not boolean or a string - throw new ExcelImportException("The cell value must be a date : sheet '" + currentSheetStructure.name - + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); - } - // for compiler - return null; + // check is it required and no value + if (cellValue == null && curCol.required) { + throw new ExcelImportException("Value required for the cell value : sheet '" + currentSheetStructure.name + + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); + } + // check the good type of value + switch (curCol.type) { + case STRING: + if (cellValue instanceof Double) { + Double doubleVal = (Double) cellValue; + if (new Double(Math.round(doubleVal)) == doubleVal) { + // if no float part + return doubleVal.toString(); + } + // with float part + String strVal = doubleVal.toString(); + return strVal.substring(0, strVal.length() - 2); + } + // if not a numeric + if (cellValue == null) { + return ""; + } + return cellValue.toString(); + case REEL: + if (cellValue instanceof Double) { + return cellValue; + } + // if not a numeric, exception + throw new ExcelImportException("The cell value must be a reel : sheet '" + currentSheetStructure.name + + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); + case INTEGER: + if (cellValue instanceof Double) { + Double doubleVal = (Double) cellValue; + if (new Double(Math.round(doubleVal)) == doubleVal) { + // if it's an integer, ok + return doubleVal.intValue(); + } + // if it's a float + throw new ExcelImportException("The cell value must be a integer : sheet '" + + currentSheetStructure.name + "', line " + Integer.toString(currentNumLine) + ", column '" + + curCol.name + "'"); + } + throw new ExcelImportException("The cell value must be a integer : sheet '" + currentSheetStructure.name + + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); + case DATE: + if (cellValue instanceof Date) { + return cellValue; + } + // is it's not a date + throw new ExcelImportException("The cell value must be a date : sheet '" + currentSheetStructure.name + + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); + case BOOLEAN: + if (cellValue instanceof Boolean) { + return cellValue; + } else if (cellValue instanceof String + && (StringUtils.lowerCase(StringUtils.trim(TRUE_STRING)).equals( + StringUtils.lowerCase(StringUtils.trim((String) cellValue))) || StringUtils.lowerCase( + StringUtils.trim(FALSE_STRING)).equals( + StringUtils.lowerCase(StringUtils.trim((String) cellValue))))) { + // if "true" or "false" are written in string + if (StringUtils.lowerCase(StringUtils.trim(TRUE_STRING)).equals( + StringUtils.lowerCase(StringUtils.trim((String) cellValue)))) { + return true; + } + return false; + } + // is it's not boolean or a string + throw new ExcelImportException("The cell value must be a date : sheet '" + currentSheetStructure.name + + "', line " + Integer.toString(currentNumLine) + ", column '" + curCol.name + "'"); + } + // for compiler + return null; } /** @@ -302,36 +301,36 @@ * @throws ExcelImportException Exception if error cell or formula don't get a numeric value */ private Object getCellValue(HSSFCell cell) throws ExcelImportException { - if (cell == null) { - return null; - } + if (cell == null) { + return null; + } - switch (cell.getCellType()) { - case Cell.CELL_TYPE_BLANK: - return null; - case Cell.CELL_TYPE_STRING: - return cell.getStringCellValue(); - case Cell.CELL_TYPE_NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - // if it's a date - return DateUtil.getJavaDate(cell.getNumericCellValue()); - } - return cell.getNumericCellValue(); - case Cell.CELL_TYPE_BOOLEAN: - return cell.getBooleanCellValue(); - case Cell.CELL_TYPE_FORMULA: - Double numeric = cell.getNumericCellValue(); + switch (cell.getCellType()) { + case Cell.CELL_TYPE_BLANK: + return null; + case Cell.CELL_TYPE_STRING: + return cell.getStringCellValue(); + case Cell.CELL_TYPE_NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + // if it's a date + return DateUtil.getJavaDate(cell.getNumericCellValue()); + } + return cell.getNumericCellValue(); + case Cell.CELL_TYPE_BOOLEAN: + return cell.getBooleanCellValue(); + case Cell.CELL_TYPE_FORMULA: + Double numeric = cell.getNumericCellValue(); - if (numeric.isNaN()) { - // if it's "Not a Number", exception - throw new ExcelImportException("Impossible to get a numeric value from the formula"); - } - return numeric; - case Cell.CELL_TYPE_ERROR: - throw new ExcelImportException("Error cell detected"); - } - // no case for this return - return null; + if (numeric.isNaN()) { + // if it's "Not a Number", exception + throw new ExcelImportException("Impossible to get a numeric value from the formula"); + } + return numeric; + case Cell.CELL_TYPE_ERROR: + throw new ExcelImportException("Error cell detected"); + } + // no case for this return + return null; } /** @@ -339,7 +338,7 @@ * @return fileStructureAsked */ public List<ExcelSheetStructure> getFileStructureAsked() { - return excelStructureAsked; + return excelStructureAsked; } /** @@ -347,7 +346,7 @@ * @param fileStructureAsked fileStructureAsked */ public void setFileStructureAsked(List<ExcelSheetStructure> fileStructureAsked) { - this.excelStructureAsked = fileStructureAsked; + this.excelStructureAsked = fileStructureAsked; } /** @@ -355,6 +354,6 @@ * @return currentNumLine */ public int getCurrentNumLine() { - return currentNumLine; + return currentNumLine; } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelSheetStructure.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelSheetStructure.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/ExcelSheetStructure.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,7 +42,7 @@ * @param columns The columns asked to the sheet */ public ExcelSheetStructure(String name, List<ExcelColumnStructure> columns) { - this.name = name; - this.columns = columns; + this.name = name; + this.columns = columns; } } Modified: trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/PopulateDB.java =================================================================== --- trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/PopulateDB.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.service/src/test/java/nc/ird/cantharella/service/utils/PopulateDB.java 2013-02-18 07:27:17 UTC (rev 119) @@ -114,8 +114,8 @@ * @throws DataNotFoundException - */ public static void main(String[] args) throws DataConstraintException, ExcelImportException, IOException, - DataNotFoundException { - new PopulateDB(); + DataNotFoundException { + new PopulateDB(); } /** @@ -126,20 +126,20 @@ * @throws DataNotFoundException - */ public PopulateDB() throws DataConstraintException, IOException, ExcelImportException, DataNotFoundException { - ApplicationContext ctx = new AnnotationConfigApplicationContext(ServiceContext.class); - ctx.getAutowireCapableBeanFactory().autowireBean(this); + ApplicationContext ctx = new AnnotationConfigApplicationContext(ServiceContext.class); + ctx.getAutowireCapableBeanFactory().autowireBean(this); - ServiceContext.setMailActivated(false); + ServiceContext.setMailActivated(false); - initExcelFileStructure(); + initExcelFileStructure(); - InputStream excelStream = FileUtils.openInputStream(new File( - "/home/adri/workspace/echange_doc/equipe-is/cantharella/jeu_de_donnees.xls")); + InputStream excelStream = FileUtils.openInputStream(new File( + "/home/adri/workspace/echange_doc/equipe-is/cantharella/jeu_de_donnees.xls")); - ExcelColumnsReader excelReader = new ExcelColumnsReader(excelStream, excelFileStructure); - populateAll(excelReader); + ExcelColumnsReader excelReader = new ExcelColumnsReader(excelStream, excelFileStructure); + populateAll(excelReader); - excelStream.close(); + excelStream.close(); } /** @@ -150,12 +150,12 @@ */ @Transactional public void populateAll(ExcelColumnsReader excelReader) throws ExcelImportException, DataConstraintException, - DataNotFoundException { - populatePersonneUtilisateur(excelReader); - populateCampagne(excelReader); - populateCampagnePersonneDroits(excelReader); - // populateCampagnePersonneParticipants(excelReader); - populateStation(excelReader); + DataNotFoundException { + populatePersonneUtilisateur(excelReader); + populateCampagne(excelReader); + populateCampagnePersonneDroits(excelReader); + // populateCampagnePersonneParticipants(excelReader); + populateStation(excelReader); } /** @@ -163,74 +163,74 @@ */ private void initExcelFileStructure() { - excelFileStructure = new ArrayList<ExcelSheetStructure>(); + excelFileStructure = new ArrayList<ExcelSheetStructure>(); - // structure for the entities 'personne' - ExcelColumnStructure[] personneColsArray = new ExcelColumnStructure[] { - new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), - new ExcelColumnStructure("prenom", ExcelColumnType.STRING, true), - new ExcelColumnStructure("organisme", ExcelColumnType.STRING, true), - new ExcelColumnStructure("fonction", ExcelColumnType.STRING, false), - new ExcelColumnStructure("tel", ExcelColumnType.STRING, false), - new ExcelColumnStructure("fax", ExcelColumnType.STRING, false), - new ExcelColumnStructure("courriel", ExcelColumnType.STRING, true), - new ExcelColumnStructure("adressePostale", ExcelColumnType.STRING, true), - new ExcelColumnStructure("codePostal", ExcelColumnType.STRING, true), - new ExcelColumnStructure("ville", ExcelColumnType.STRING, true), - new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), - new ExcelColumnStructure("typeDroit", ExcelColumnType.STRING, false) }; - ArrayList<ExcelColumnStructure> personneColsList = new ArrayList<ExcelColumnStructure>( - Arrays.asList(personneColsArray)); - excelFileStructure.add(new ExcelSheetStructure("personne", personneColsList)); + // structure for the entities 'personne' + ExcelColumnStructure[] personneColsArray = new ExcelColumnStructure[] { + new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), + new ExcelColumnStructure("prenom", ExcelColumnType.STRING, true), + new ExcelColumnStructure("organisme", ExcelColumnType.STRING, true), + new ExcelColumnStructure("fonction", ExcelColumnType.STRING, false), + new ExcelColumnStructure("tel", ExcelColumnType.STRING, false), + new ExcelColumnStructure("fax", ExcelColumnType.STRING, false), + new ExcelColumnStructure("courriel", ExcelColumnType.STRING, true), + new ExcelColumnStructure("adressePostale", ExcelColumnType.STRING, true), + new ExcelColumnStructure("codePostal", ExcelColumnType.STRING, true), + new ExcelColumnStructure("ville", ExcelColumnType.STRING, true), + new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), + new ExcelColumnStructure("typeDroit", ExcelColumnType.STRING, false) }; + ArrayList<ExcelColumnStructure> personneColsList = new ArrayList<ExcelColumnStructure>(Arrays + .asList(personneColsArray)); + excelFileStructure.add(new ExcelSheetStructure("personne", personneColsList)); - // structure for the entities 'personne' - ExcelColumnStructure[] campagneColsArray = new ExcelColumnStructure[] { - new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), - new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), - new ExcelColumnStructure("programme", ExcelColumnType.STRING, false), - new ExcelColumnStructure("complement", ExcelColumnType.STRING, false), - new ExcelColumnStructure("createur", ExcelColumnType.STRING, true), - new ExcelColumnStructure("dateDeb", ExcelColumnType.DATE, true), - new ExcelColumnStructure("dateFin", ExcelColumnType.DATE, true) }; - ArrayList<ExcelColumnStructure> campagneColsList = new ArrayList<ExcelColumnStructure>( - Arrays.asList(campagneColsArray)); - excelFileStructure.add(new ExcelSheetStructure("campagne", campagneColsList)); + // structure for the entities 'personne' + ExcelColumnStructure[] campagneColsArray = new ExcelColumnStructure[] { + new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), + new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), + new ExcelColumnStructure("programme", ExcelColumnType.STRING, false), + new ExcelColumnStructure("complement", ExcelColumnType.STRING, false), + new ExcelColumnStructure("createur", ExcelColumnType.STRING, true), + new ExcelColumnStructure("dateDeb", ExcelColumnType.DATE, true), + new ExcelColumnStructure("dateFin", ExcelColumnType.DATE, true) }; + ArrayList<ExcelColumnStructure> campagneColsList = new ArrayList<ExcelColumnStructure>(Arrays + .asList(campagneColsArray)); + excelFileStructure.add(new ExcelSheetStructure("campagne", campagneColsList)); - // structure for the entities 'campagnePersonneDroit' - ExcelColumnStructure[] campagnePersonneDroitColsArray = new ExcelColumnStructure[] { - new ExcelColumnStructure("campagne", ExcelColumnType.STRING, true), - new ExcelColumnStructure("personne", ExcelColumnType.STRING, true), - new ExcelColumnStructure("droitRecolte", ExcelColumnType.BOOLEAN, true), - new ExcelColumnStructure("droitExtrait", ExcelColumnType.BOOLEAN, true), - new ExcelColumnStructure("droitPuri", ExcelColumnType.BOOLEAN, true), - new ExcelColumnStructure("droitTest", ExcelColumnType.BOOLEAN, true) }; - ArrayList<ExcelColumnStructure> campagnePersonneDroitColsList = new ArrayList<ExcelColumnStructure>( - Arrays.asList(campagnePersonneDroitColsArray)); - excelFileStructure.add(new ExcelSheetStructure("campagnePersonneDroits", campagnePersonneDroitColsList)); + // structure for the entities 'campagnePersonneDroit' + ExcelColumnStructure[] campagnePersonneDroitColsArray = new ExcelColumnStructure[] { + new ExcelColumnStructure("campagne", ExcelColumnType.STRING, true), + new ExcelColumnStructure("personne", ExcelColumnType.STRING, true), + new ExcelColumnStructure("droitRecolte", ExcelColumnType.BOOLEAN, true), + new ExcelColumnStructure("droitExtrait", ExcelColumnType.BOOLEAN, true), + new ExcelColumnStructure("droitPuri", ExcelColumnType.BOOLEAN, true), + new ExcelColumnStructure("droitTest", ExcelColumnType.BOOLEAN, true) }; + ArrayList<ExcelColumnStructure> campagnePersonneDroitColsList = new ArrayList<ExcelColumnStructure>(Arrays + .asList(campagnePersonneDroitColsArray)); + excelFileStructure.add(new ExcelSheetStructure("campagnePersonneDroits", campagnePersonneDroitColsList)); - // structure for the entities 'campagnePersonneParticipants' - ExcelColumnStructure[] campagnePersonneParticipantsColsArray = new ExcelColumnStructure[] { - new ExcelColumnStructure("campagne", ExcelColumnType.STRING, true), - new ExcelColumnStructure("personne", ExcelColumnType.STRING, true), - new ExcelColumnStructure("complement", ExcelColumnType.STRING, false) }; - ArrayList<ExcelColumnStructure> campagnePersonneParticipantsColsList = new ArrayList<ExcelColumnStructure>( - Arrays.asList(campagnePersonneParticipantsColsArray)); - excelFileStructure.add(new ExcelSheetStructure("campagnePersonneParticipants", - campagnePersonneParticipantsColsList)); + // structure for the entities 'campagnePersonneParticipants' + ExcelColumnStructure[] campagnePersonneParticipantsColsArray = new ExcelColumnStructure[] { + new ExcelColumnStructure("campagne", ExcelColumnType.STRING, true), + new ExcelColumnStructure("personne", ExcelColumnType.STRING, true), + new ExcelColumnStructure("complement", ExcelColumnType.STRING, false) }; + ArrayList<ExcelColumnStructure> campagnePersonneParticipantsColsList = new ArrayList<ExcelColumnStructure>( + Arrays.asList(campagnePersonneParticipantsColsArray)); + excelFileStructure.add(new ExcelSheetStructure("campagnePersonneParticipants", + campagnePersonneParticipantsColsList)); - // structure for the entities 'station' - ExcelColumnStructure[] stationColsArray = new ExcelColumnStructure[] { - new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), - new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), - new ExcelColumnStructure("localite", ExcelColumnType.STRING, true), - new ExcelColumnStructure("latitude", ExcelColumnType.STRING, false), - new ExcelColumnStructure("longitude", ExcelColumnType.STRING, false), - new ExcelColumnStructure("referentiel", ExcelColumnType.STRING, false), - new ExcelColumnStructure("complement", ExcelColumnType.STRING, false), - new ExcelColumnStructure("createur", ExcelColumnType.STRING, true) }; - ArrayList<ExcelColumnStructure> stationColsList = new ArrayList<ExcelColumnStructure>( - Arrays.asList(stationColsArray)); - excelFileStructure.add(new ExcelSheetStructure("station", stationColsList)); + // structure for the entities 'station' + ExcelColumnStructure[] stationColsArray = new ExcelColumnStructure[] { + new ExcelColumnStructure("nom", ExcelColumnType.STRING, true), + new ExcelColumnStructure("codePays", ExcelColumnType.STRING, true), + new ExcelColumnStructure("localite", ExcelColumnType.STRING, true), + new ExcelColumnStructure("latitude", ExcelColumnType.STRING, false), + new ExcelColumnStructure("longitude", ExcelColumnType.STRING, false), + new ExcelColumnStructure("referentiel", ExcelColumnType.STRING, false), + new ExcelColumnStructure("complement", ExcelColumnType.STRING, false), + new ExcelColumnStructure("createur", ExcelColumnType.STRING, true) }; + ArrayList<ExcelColumnStructure> stationColsList = new ArrayList<ExcelColumnStructure>(Arrays + .asList(stationColsArray)); + excelFileStructure.add(new ExcelSheetStructure("station", stationColsList)); } @@ -241,34 +241,34 @@ * @throws DataConstraintException - */ private void populatePersonneUtilisateur(ExcelColumnsReader excelReader) throws ExcelImportException, - DataConstraintException { - excelReader.selectSheet("personne"); + DataConstraintException { + excelReader.selectSheet("personne"); - Map<String, Object> line = excelReader.readLine(); - while (!line.isEmpty()) { - String nom = (String) line.get("nom"); - String prenom = (String) line.get("prenom"); - String organisme = (String) line.get("organisme"); - String fonction = (String) line.get("fonction"); - String tel = (String) line.get("tel"); - String fax = (String) line.get("fax"); - String courriel = (String) line.get("courriel"); - String adressePostale = (String) line.get("adressePostale"); - String codePostal = (String) line.get("codePostal"); - String ville = (String) line.get("ville"); - String codePays = (String) line.get("codePays"); - String typeDroit = (String) line.get("typeDroit"); - String password = "password"; - Boolean estValide = true; - LOG.info("adding personne (xls line " + excelReader.getCurrentNumLine() + ") with values :"); - LOG.info("[nom : '" + nom + "', prenom : '" + prenom + "', organisme : '" + organisme + "', fonction : '" - + fonction + "', tel : '" + tel + "', fax : '" + fax + "', courriel : '" + courriel - + "', adressePostale : '" + adressePostale + "', codePays : '" + codePays + "', typeDroit : '" - + typeDroit + "', password : '" + password + "', estValide : '" + estValide + "']"); - addUtilisateurOrPersonne(nom, prenom, organisme, fonction, tel, fax, courriel, adressePostale, codePostal, - ville, codePays, typeDroit, password, estValide); - line = excelReader.readLine(); - } + Map<String, Object> line = excelReader.readLine(); + while (!line.isEmpty()) { + String nom = (String) line.get("nom"); + String prenom = (String) line.get("prenom"); + String organisme = (String) line.get("organisme"); + String fonction = (String) line.get("fonction"); + String tel = (String) line.get("tel"); + String fax = (String) line.get("fax"); + String courriel = (String) line.get("courriel"); + String adressePostale = (String) line.get("adressePostale"); + String codePostal = (String) line.get("codePostal"); + String ville = (String) line.get("ville"); + String codePays = (String) line.get("codePays"); + String typeDroit = (String) line.get("typeDroit"); + String password = "password"; + Boolean estValide = true; + LOG.info("adding personne (xls line " + excelReader.getCurrentNumLine() + ") with values :"); + LOG.info("[nom : '" + nom + "', prenom : '" + prenom + "', organisme : '" + organisme + "', fonction : '" + + fonction + "', tel : '" + tel + "', fax : '" + fax + "', courriel : '" + courriel + + "', adressePostale : '" + adressePostale + "', codePays : '" + codePays + "', typeDroit : '" + + typeDroit + "', password : '" + password + "', estValide : '" + estValide + "']"); + addUtilisateurOrPersonne(nom, prenom, organisme, fonction, tel, fax, courriel, adressePostale, codePostal, + ville, codePays, typeDroit, password, estValide); + line = excelReader.readLine(); + } } /** @@ -279,27 +279,27 @@ * @throws DataNotFoundException - */ private void populateCampagne(ExcelColumnsReader excelReader) throws ExcelImportException, DataConstraintException, - DataNotFoundException { - excelReader.selectSheet("campagne"); + DataNotFoundException { + excelReader.selectSheet("campagne"); - Map<String, Object> line = excelReader.readLine(); - while (!line.isEmpty()) { - String nom = (String) line.get("nom"); - String codePays = (String) line.get("codePays"); - String programme = (String) line.get("programme"); - String complement = (String) line.get("complement"); - String createur = (String) line.get("createur"); - Date dateDeb = (Date) line.get("dateDeb"); - Date dateFin = (Date) line.get("dateFin"); + Map<String, Object> line = excelReader.readLine(); + while (!line.isEmpty()) { + String nom = (String) line.get("nom"); + String codePays = (String) line.get("codePays"); + String programme = (String) line.get("programme"); + String complement = (String) line.get("complement"); + String createur = (String) line.get("createur"); + Date dateDeb = (Date) line.get("dateDeb"); + Date dateFin = (Date) line.get("dateFin"); - LOG.debug("adding campagne (xls line " + excelReader.getCurrentNumLine() + ") with values :"); - LOG.debug("[nom : '" + nom + "', codePays : '" + codePays + "', programme : '" + programme - + "', complement : '" + complement + "', createur : '" + createur + "', dateDeb : '" + dateDeb - + "', dateFin : '" + dateFin + "']"); - addCampagne(nom, codePays, programme, complement, createur, dateDeb, dateFin); + LOG.debug("adding campagne (xls line " + excelReader.getCurrentNumLine() + ") with values :"); + LOG.debug("[nom : '" + nom + "', codePays : '" + codePays + "', programme : '" + programme + + "', complement : '" + complement + "', createur : '" + createur + "', dateDeb : '" + dateDeb + + "', dateFin : '" + dateFin + "']"); + addCampagne(nom, codePays, programme, complement, createur, dateDeb, dateFin); - line = excelReader.readLine(); - } + line = excelReader.readLine(); + } } /** @@ -310,26 +310,26 @@ * @throws DataNotFoundException - */ private void populateCampagnePersonneDroits(ExcelColumnsReader excelReader) throws ExcelImportException, - DataConstraintException, DataNotFoundException { - excelReader.selectSheet("campagnePersonneDroits"); + DataConstraintException, DataNotFoundException { + excelReader.selectSheet("campagnePersonneDroits"); - Map<String, Object> line = excelReader.readLine(); - while (!line.isEmpty()) { - String campagne = (String) line.get("campagne"); - String personne = (String) line.get("personne"); - Boolean droitRecolte = (Boolean) line.get("droitRecolte"); - Boolean droitExtrait = (Boolean) line.get("droitExtrait"); - Boolean droitPuri = (Boolean) line.get("droitPuri"); - Boolean droitTest = (Boolean) line.get("droitTest"); + Map<String, Object> line = excelReader.readLine(); + while (!line.isEmpty()) { + String campagne = (String) line.get("campagne"); + String personne = (String) line.get("personne"); + Boolean droitRecolte = (Boolean) line.get("droitRecolte"); + Boolean droitExtrait = (Boolean) line.get("droitExtrait"); + Boolean droitPuri = (Boolean) line.get("droitPuri"); + Boolean droitTest = (Boolean) line.get("droitTest"); - LOG.debug("adding campagnePersonneDroits (xls line " + excelReader.getCurrentNumLine() + ") with values :"); - LOG.debug("[campagne : '" + campagne + "', personne : '" + personne + "', droitRecolte : '" + droitRecolte - + "', droitExtrait : '" + droitExtrait + "', droitPuri : '" + droitPuri + "', droitTest : '" - + droitTest + "']"); - addCampagnePersonneDroits(campagne, personne, droitExtrait, droitPuri, droitRecolte, droitTest); + LOG.debug("adding campagnePersonneDroits (xls line " + excelReader.getCurrentNumLine() + ") with values :"); + LOG.debug("[campagne : '" + campagne + "', personne : '" + personne + "', droitRecolte : '" + droitRecolte + + "', droitExtrait : '" + droitExtrait + "', droitPuri : '" + droitPuri + "', droitTest : '" + + droitTest + "']"); + addCampagnePersonneDroits(campagne, personne, droitExtrait, droitPuri, droitRecolte, droitTest); - line = excelReader.readLine(); - } + line = excelReader.readLine(); + } } /** @@ -341,23 +341,23 @@ */ @SuppressWarnings("unused") private void populateCampagnePersonneParticipants(ExcelColumnsReader excelReader) throws ExcelImportException, - DataConstraintException, DataNotFoundException { - excelReader.selectSheet("campagnePersonneParticipants"); + DataConstraintException, DataNotFoundException { + excelReader.selectSheet("campagnePersonneParticipants"); - Map<String, Object> line = excelReader.readLine(); - while (!line.isEmpty()) { - String campagne = (String) line.get("campagne"); - String personne = (String) line.get("personne"); - String complement = (String) line.get("complement"); + Map<String, Object> line = excelReader.readLine(); + while (!line.isEmpty()) { + String campagne = (String) line.get("campagne"); + String personne = (String) line.get("personne"); + String complement = (String) line.get("complement"); - LOG.debug("adding campagnePersonneParticipants (xls line " + excelReader.getCurrentNumLine() - + ") with values :"); - LOG.debug("[campagne : '" + campagne + "', personne : '" + personne + "', complement : '" + complement - + "']"); - addCampagnePersonneParticipants(campagne, personne, complement); + LOG.debug("adding campagnePersonneParticipants (xls line " + excelReader.getCurrentNumLine() + + ") with values :"); + LOG.debug("[campagne : '" + campagne + "', personne : '" + personne + "', complement : '" + complement + + "']"); + addCampagnePersonneParticipants(campagne, personne, complement); - line = excelReader.readLine(); - } + line = excelReader.readLine(); + } } /** @@ -368,29 +368,29 @@ * @throws DataNotFoundException - */ private void populateStation(ExcelColumnsReader excelReader) throws ExcelImportException, DataConstraintException, - DataNotFoundException { - excelReader.selectSheet("station"); + DataNotFoundException { + excelReader.selectSheet("station"); - Map<String, Object> line = excelReader.readLine(); - while (!line.isEmpty()) { - String nom = (String) line.get("nom"); - String codePays = (String) line.get("codePays"); - String localite = (String) line.get("localite"); - String latitude = (String) line.get("latitude"); - String longitude = (String) line.get("longitude"); - String referentiel = (String) line.get("referentiel"); - String complement = (String) line.get("complement"); - String createur = (String) line.get("createur"); + Map<String, Object> line = excelReader.readLine(); + while (!line.isEmpty()) { + String nom = (String) line.get("nom"); + String codePays = (String) line.get("codePays"); + String localite = (String) line.get("localite"); + String latitude = (String) line.get("latitude"); + String longitude = (String) line.get("longitude"); + String referentiel = (String) line.get("referentiel"); + String complement = (String) line.get("complement"); + String createur = (String) line.get("createur"); - LOG.debug("adding campagnePersonneParticipants (xls line " + excelReader.getCurrentNumLine() - + ") with values :"); - LOG.debug("[nom :'" + nom + "', codePays : '" + codePays + "', localite : '" + localite + "', latitude : '" - + latitude + "', longitude : '" + longitude + "', referentiel : '" + referentiel - + "', complement : '" + complement + "', createur : '" + createur + "']"); - addStation(nom, codePays, localite, latitude, longitude, complement, createur, referentiel); + LOG.debug("adding campagnePersonneParticipants (xls line " + excelReader.getCurrentNumLine() + + ") with values :"); + LOG.debug("[nom :'" + nom + "', codePays : '" + codePays + "', localite : '" + localite + "', latitude : '" + + latitude + "', longitude : '" + longitude + "', referentiel : '" + referentiel + + "', complement : '" + complement + "', createur : '" + createur + "']"); + addStation(nom, codePays, localite, latitude, longitude, complement, createur, referentiel); - line = excelReader.readLine(); - } + line = excelReader.readLine(); + } } /** @@ -406,16 +406,16 @@ * @throws DataNotFoundException - */ private void addCampagne(String nom, String codePays, String programme, String complement, String createur, - Date dateDeb, Date dateFin) throws DataConstraintException, DataNotFoundException { - Campagne c = new Campagne(); - c.setNom(nom); - c.setCodePays(codePays); - c.setProgramme(programme); - c.setComplement(complement); - c.setCreateur(personneService.loadPersonne(createur)); - c.setDateDeb(dateDeb); - c.setDateFin(dateFin); - campagneService.createCampagne(c); + Date dateDeb, Date dateFin) throws DataConstraintException, DataNotFoundException { + Campagne c = new Campagne(); + c.setNom(nom); + c.setCodePays(codePays); + c.setProgramme(programme); + c.setComplement(complement); + c.setCreateur(personneService.loadPersonne(createur)); + c.setDateDeb(dateDeb); + c.setDateFin(dateFin); + campagneService.createCampagne(c); } /** @@ -430,17 +430,17 @@ * @throws DataConstraintException - */ private void addCampagnePersonneDroits(String campagne, String personne, Boolean droitExtrait, Boolean droitPuri, - Boolean droitRecolte, Boolean droitTest) throws DataNotFoundException, DataConstraintException { - CampagnePersonneDroits d = new CampagnePersonneDroits(); - d.getId().setPk1(campagneService.loadCampagne(campagne)); - d.getId().setPk2(personneService.loadPersonne(personne)); - d.getDroits().setDroitExtrait(droitExtrait); - d.getDroits().setDroitPuri(droitPuri); - d.getDroits().setDroitRecolte(droitRecolte); - d.getDroits().setDroitTestBio(droitTest); - // d.id.pk1.personnesDroits.add(d); - // d.id.pk2.campagnesDroits.put(d.id.pk1, d); - personneService.updatePersonne(d.getId().getPk2()); + Boolean droitRecolte, Boolean droitTest) throws DataNotFoundException, DataConstraintException { + CampagnePersonneDroits d = new CampagnePersonneDroits(); + d.getId().setPk1(campagneService.loadCampagne(campagne)); + d.getId().setPk2(personneService.loadPersonne(personne)); + d.getDroits().setDroitExtrait(droitExtrait); + d.getDroits().setDroitPuri(droitPuri); + d.getDroits().setDroitRecolte(droitRecolte); + d.getDroits().setDroitTestBio(droitTest); + // d.id.pk1.personnesDroits.add(d); + // d.id.pk2.campagnesDroits.put(d.id.pk1, d); + personneService.updatePersonne(d.getId().getPk2()); } /** @@ -452,14 +452,14 @@ * @throws DataConstraintException - */ private void addCampagnePersonneParticipants(String campagne, String personne, String complement) - throws DataNotFoundException, DataConstraintException { - CampagnePersonneParticipant p = new CampagnePersonneParticipant(); - p.getId().setPk1(campagneService.loadCampagne(campagne)); - p.getId().setPk2(personneService.loadPersonne(personne)); - p.setComplement(complement); - p.getId().getPk1().getParticipants().add(p); - p.getId().getPk2().getCampagnesParticipees().add(p); - campagneService.updateCampagne(p.getId().getPk1()); + throws DataNotFoundException, DataConstraintException { + CampagnePersonneParticipant p = new CampagnePersonneParticipant(); + p.getId().setPk1(campagneService.loadCampagne(campagne)); + p.getId().setPk2(personneService.loadPersonne(personne)); + p.setComplement(complement); + p.getId().getPk1().getParticipants().add(p); + p.getId().getPk2().getCampagnesParticipees().add(p); + campagneService.updateCampagne(p.getId().getPk1()); } /** @@ -482,26 +482,26 @@ */ @SuppressWarnings("unused") private void addLot(String campagne, String complement, String createur, String date, String echantillonColl, - String echantillonIdent, String echantillonPhylo, String masseFraiche, String masseSeche, String partie, - String ref, String specimenRef, String station) throws DataNotFoundException, ParseException { - Lot l = new Lot(); - l.setCampagne(campagneService.loadCampagne(campagne)); - l.setComplement(complement); - l.setCreateur(personneService.loadPersonne(createur)); - l.setDateRecolte(DATE_FORMAT.parse(date)); - l.setEchantillonColl(Boolean.valueOf(echantillonColl)); - l.setEchantillonIdent(Boolean.valueOf(echantillonIdent)); - l.setEchantillonPhylo(Boolean.valueOf(echantillonPhylo)); - DecimalFormat fmt = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH); - fmt.setMaximumFractionDigits(DataContext.DECIMAL_SCALE); - fmt.setMaximumIntegerDigits(DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); - fmt.setParseBigDecimal(true); - l.setMasseFraiche((BigDecimal) fmt.parse(masseFraiche)); - l.setMasseSeche((BigDecimal) fmt.parse(masseSeche)); - l.setPartie(lotService.loadPartie(partie)); - l.setRef(ref); - l.setSpecimenRef(specimenService.loadSpecimen(specimenRef)); - l.setStation(stationService.loadStation(station)); + String echantillonIdent, String echantillonPhylo, String masseFraiche, String masseSeche, String partie, + String ref, String specimenRef, String station) throws DataNotFoundException, ParseException { + Lot l = new Lot(); + l.setCampagne(campagneService.loadCampagne(campagne)); + l.setComplement(complement); + l.setCreateur(personneService.loadPersonne(createur)); + l.setDateRecolte(DATE_FORMAT.parse(date)); + l.setEchantillonColl(Boolean.valueOf(echantillonColl)); + l.setEchantillonIdent(Boolean.valueOf(echantillonIdent)); + l.setEchantillonPhylo(Boolean.valueOf(echantillonPhylo)); + DecimalFormat fmt = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH); + fmt.setMaximumFractionDigits(DataContext.DECIMAL_SCALE); + fmt.setMaximumIntegerDigits(DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); + fmt.setParseBigDecimal(true); + l.setMasseFraiche((BigDecimal) fmt.parse(masseFraiche)); + l.setMasseSeche((BigDecimal) fmt.parse(masseSeche)); + l.setPartie(lotService.loadPartie(partie)); + l.setRef(ref); + l.setSpecimenRef(specimenService.loadSpecimen(specimenRef)); + l.setStation(stationService.loadStation(station)); } /** @@ -517,17 +517,17 @@ */ @SuppressWarnings("unused") private void addLotPersonneDroits(String lot, String personne, String droitExtrait, String droitPuri, - String droitRécolte, String droitTest) throws DataNotFoundException, DataConstraintException { - LotPersonneDroits d = new LotPersonneDroits(); - d.getId().setPk1(lotService.loadLot(lot)); - d.getId().setPk2(personneService.loadPersonne(personne)); - d.getDroits().setDroitExtrait(Boolean.valueOf(droitExtrait)); - d.getDroits().setDroitPuri(Boolean.valueOf(droitPuri)); - d.getDroits().setDroitRecolte(Boolean.valueOf(droitRécolte)); - d.getDroits().setDroitTestBio(Boolean.valueOf(droitTest)); - d.getId().getPk1().getPersonnesDroits().add(d); - d.getId().getPk2().getLotsDroits().put(d.getId().getPk1(), d); - personneService.updatePersonne(d.getId().getPk2()); + String droitRécolte, String droitTest) throws DataNotFoundException, DataConstraintException { + LotPersonneDroits d = new LotPersonneDroits(); + d.getId().setPk1(lotService.loadLot(lot)); + d.getId().setPk2(personneService.loadPersonne(personne)); + d.getDroits().setDroitExtrait(Boolean.valueOf(droitExtrait)); + d.getDroits().setDroitPuri(Boolean.valueOf(droitPuri)); + d.getDroits().setDroitRecolte(Boolean.valueOf(droitRécolte)); + d.getDroits().setDroitTestBio(Boolean.valueOf(droitTest)); + d.getId().getPk1().getPersonnesDroits().add(d); + d.getId().getPk2().getLotsDroits().put(d.getId().getPk1(), d); + personneService.updatePersonne(d.getId().getPk2()); } /** @@ -537,9 +537,9 @@ */ @SuppressWarnings("unused") private void addPartie(String nom) throws DataConstraintException { - Partie p = new Partie(); - p.setNom(nom); - lotService.createPartie(p); + Partie p = new Partie(); + p.setNom(nom); + lotService.createPartie(p); } /** @@ -550,10 +550,10 @@ */ @SuppressWarnings("unused") private void addSpecimen(String ref, String embranchement) throws DataConstraintException { - Specimen s = new Specimen(); - s.setRef(ref); - s.setEmbranchement(embranchement); - specimenService.createSpecimen(s); + Specimen s = new Specimen(); + s.setRef(ref); + s.setEmbranchement(embranchement); + specimenService.createSpecimen(s); } /** @@ -571,18 +571,18 @@ * @throws ExcelImportException - */ private void addStation(String nom, String codePays, String localite, String latitude, String longitude, - String complement, String createur, String referentiel) throws DataNotFoundException, - DataConstraintException, ExcelImportException { - Station s = new Station(); - s.setNom(nom); - s.setCodePays(codePays); - s.setComplement(complement); - s.setCreateur(personneService.loadPersonne(createur)); - s.setLatitude(StringUtils.leftPad(StringUtils.deleteWhitespace(latitude), CoordTools.LATITUDE_LENGTH)); - s.setLongitude(StringUtils.leftPad(StringUtils.deleteWhitespace(longitude), CoordTools.LONGITUDE_LENGTH)); - s.setReferentiel(getReferentialNumber(referentiel)); - s.setLocalite(localite); - stationService.createStation(s); + String complement, String createur, String referentiel) throws DataNotFoundException, + DataConstraintException, ExcelImportException { + Station s = new Station(); + s.setNom(nom); + s.setCodePays(codePays); + s.setComplement(complement); + s.setCreateur(personneService.loadPersonne(createur)); + s.setLatitude(StringUtils.leftPad(StringUtils.deleteWhitespace(latitude), CoordTools.LATITUDE_LENGTH)); + s.setLongitude(StringUtils.leftPad(StringUtils.deleteWhitespace(longitude), CoordTools.LONGITUDE_LENGTH)); + s.setReferentiel(getReferentialNumber(referentiel)); + s.setLocalite(localite); + stationService.createStation(s); } /** @@ -592,12 +592,12 @@ * @throws ExcelImportException - */ private Integer getReferentialNumber(String referentialString) throws ExcelImportException { - for (Map.Entry<Integer, String> curEntry : DataContext.REFERENTIELS.entrySet()) { - if (curEntry.getValue().equals(referentialString)) { - return curEntry.getKey(); - } - } - throw new ExcelImportException("'" + referentialString + "' is not a allowed referential"); + for (Map.Entry<Integer, String> curEntry : DataContext.REFERENTIELS.entrySet()) { + if (curEntry.getValue().equals(referentialString)) { + return curEntry.getKey(); + } + } + throw new ExcelImportException("'" + referentialString + "' is not a allowed referential"); } /** @@ -619,39 +619,39 @@ * @throws DataConstraintException - */ private void addUtilisateurOrPersonne(String nom, String prenom, String organisme, String fonction, String tel, - String fax, String courriel, String adressePostale, String codePostal, String ville, String codePays, - String typeDroit, String password, Boolean estValide) throws DataConstraintException { - if (StringUtils.isEmpty(typeDroit)) { - Personne p = new Personne(); - p.setNom(nom); - p.setPrenom(prenom); - p.setOrganisme(organisme); - p.setFonction(fonction); - p.setTel(tel); - p.setFax(fax); - p.setCourriel(courriel); - p.setAdressePostale(adressePostale); - p.setCodePostal(codePostal); - p.setVille(ville); - p.setCodePays(codePays); - personneService.createPersonne(p); - } else { - Utilisateur u = new Utilisateur(); - u.setNom(nom); - u.setPrenom(prenom); - u.setOrganisme(organisme); - u.setFonction(fonction); - u.setTel(tel); - u.setFax(fax); - u.setCourriel(courriel); - u.setAdressePostale(adressePostale); - u.setCodePostal(codePostal); - u.setVille(ville); - u.setCodePays(codePays); - u.setTypeDroit(TypeDroit.valueOf(typeDroit)); - u.setPasswordHash(personneService.hashPassword(password)); - u.setValide(estValide); - personneService.createUtilisateur(u); - } + String fax, String courriel, String adressePostale, String codePostal, String ville, String codePays, + String typeDroit, String password, Boolean estValide) throws DataConstraintException { + if (StringUtils.isEmpty(typeDroit)) { + Personne p = new Personne(); + p.setNom(nom); + p.setPrenom(prenom); + p.setOrganisme(organisme); + p.setFonction(fonction); + p.setTel(tel); + p.setFax(fax); + p.setCourriel(courriel); + p.setAdressePostale(adressePostale); + p.setCodePostal(codePostal); + p.setVille(ville); + p.setCodePays(codePays); + personneService.createPersonne(p); + } else { + Utilisateur u = new Utilisateur(); + u.setNom(nom); + u.setPrenom(prenom); + u.setOrganisme(organisme); + u.setFonction(fonction); + u.setTel(tel); + u.setFax(fax); + u.setCourriel(courriel); + u.setAdressePostale(adressePostale); + u.setCodePostal(codePostal); + u.setVille(ville); + u.setCodePays(codePays); + u.setTypeDroit(TypeDroit.valueOf(typeDroit)); + u.setPasswordHash(personneService.hashPassword(password)); + u.setValide(estValide); + personneService.createUtilisateur(u); + } } } \ No newline at end of file Modified: trunk/cantharella.utils/pom.xml =================================================================== --- trunk/cantharella.utils/pom.xml 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/pom.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -12,8 +12,21 @@ <artifactId>cantharella.utils</artifactId> <name>Cantharella :: Utils</name> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + <plugin> + <groupId>com.googlecode.maven-java-formatter-plugin</groupId> + <artifactId>maven-java-formatter-plugin</artifactId> + </plugin> + </plugins> + </build> + <dependencies> - <dependency> + <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> @@ -25,7 +38,7 @@ <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> - <dependency> + <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/AssertTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/AssertTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/AssertTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,10 +67,10 @@ * @param strings Strings array */ public static void assertArrayNotEmpty(String[] strings) { - assertNotNull(strings); - for (String string : strings) { - assertNotEmpty(string); - } + assertNotNull(strings); + for (String string : strings) { + assertNotEmpty(string); + } } /** @@ -78,10 +78,10 @@ * @param objects Objects array */ public static void assertArrayNotNull(Object[] objects) { - assertNotNull(objects); - for (Object object : objects) { - assertNotNull(object); - } + assertNotNull(objects); + for (Object object : objects) { + assertNotNull(object); + } } /** @@ -90,9 +90,9 @@ * @param clazz Expected class/superclass/interface/superinterface */ public static void assertClassOrInterface(Object object, Class<?> clazz) { - assertNotNull(object); - assertNotNull(clazz); - assert clazz.isAssignableFrom(object.getClass()) : String.format(CLASS, clazz.getName()); + assertNotNull(object); + assertNotNull(clazz); + assert clazz.isAssignableFrom(object.getClass()) : String.format(CLASS, clazz.getName()); } /** @@ -100,10 +100,10 @@ * @param objects Objects collection */ public static void assertCollectionNotNull(Collection<?> objects) { - assertNotNull(objects); - for (Object object : objects) { - assertNotNull(object); - } + assertNotNull(objects); + for (Object object : objects) { + assertNotNull(object); + } } /** @@ -113,7 +113,7 @@ * @param expectedValue Expected value */ public static <N extends Number> void assertEquals(N value, N expectedValue) { - assert value.doubleValue() == expectedValue.doubleValue() : String.format(EQUALS, expectedValue); + assert value.doubleValue() == expectedValue.doubleValue() : String.format(EQUALS, expectedValue); } /** @@ -123,7 +123,7 @@ * @param bound Bound */ public static <N extends Number> void assertGreater(N value, N bound) { - assert value.doubleValue() > bound.doubleValue() : String.format(GREATER, bound); + assert value.doubleValue() > bound.doubleValue() : String.format(GREATER, bound); } /** @@ -133,7 +133,7 @@ * @param bound Bound */ public static <N extends Number> void assertGreaterOrEquals(N value, N bound) { - assert value.doubleValue() >= bound.doubleValue() : String.format(GREATER_OR_EQUALS, bound); + assert value.doubleValue() >= bound.doubleValue() : String.format(GREATER_OR_EQUALS, bound); } /** @@ -143,9 +143,9 @@ * @param values Values collection */ public static <O> void assertIn(O object, Collection<O> values) { - assertNotNull(object); - assertNotEmpty(values); - assert values.contains(object) : String.format(IN, object); + assertNotNull(object); + assertNotEmpty(values); + assert values.contains(object) : String.format(IN, object); } /** @@ -155,8 +155,8 @@ * @param values Values array */ public static <O> void assertIn(O object, O... values) { - assertNotEmpty(values); - assertIn(object, Arrays.asList(values)); + assertNotEmpty(values); + assertIn(object, Arrays.asList(values)); } /** @@ -166,7 +166,7 @@ * @param bound Bound */ public static <N extends Number> void assertLower(N value, N bound) { - assert value.doubleValue() < bound.doubleValue() : String.format(LOWER, bound); + assert value.doubleValue() < bound.doubleValue() : String.format(LOWER, bound); } /** @@ -176,7 +176,7 @@ * @param bound Bound */ public static <N extends Number> void assertLowerOrEquals(N value, N bound) { - assert value.doubleValue() <= bound.doubleValue() : String.format(LOWER_OR_EQUALS, bound); + assert value.doubleValue() <= bound.doubleValue() : String.format(LOWER_OR_EQUALS, bound); } /** @@ -184,8 +184,8 @@ * @param collection Collection */ public static void assertNotEmpty(Collection<?> collection) { - assertNotNull(collection); - assert !collection.isEmpty() : NOT_EMPTY; + assertNotNull(collection); + assert !collection.isEmpty() : NOT_EMPTY; } /** @@ -193,8 +193,8 @@ * @param array Array */ public static void assertNotEmpty(Object[] array) { - assertNotNull(array); - assert array.length > 0 : NOT_EMPTY; + assertNotNull(array); + assert array.length > 0 : NOT_EMPTY; } /** @@ -202,8 +202,8 @@ * @param string String */ public static void assertNotEmpty(String string) { - assertNotNull(string); - assert !string.isEmpty() : NOT_EMPTY; + assertNotNull(string); + assert !string.isEmpty() : NOT_EMPTY; } /** @@ -213,7 +213,7 @@ * @param unexpectedValue Unxpected value */ public static <N extends Number> void assertNotEquals(N value, N unexpectedValue) { - assert value.doubleValue() != unexpectedValue.doubleValue() : String.format(NOT_EQUALS, unexpectedValue); + assert value.doubleValue() != unexpectedValue.doubleValue() : String.format(NOT_EQUALS, unexpectedValue); } /** @@ -222,7 +222,7 @@ * @param value Value */ public static <N extends Number> void assertNotNegative(N value) { - assertGreaterOrEquals(value, 0); + assertGreaterOrEquals(value, 0); } /** @@ -230,7 +230,7 @@ * @param object Object */ public static void assertNotNull(Object object) { - assert object != null : NOT_NULL; + assert object != null : NOT_NULL; } /** @@ -239,13 +239,13 @@ * @param value Value */ public static <N extends Number> void assertPositive(N value) { - assertGreater(value, 0); + assertGreater(value, 0); } /** * Constructor (prevents instantiation) */ private AssertTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanLookup.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanLookup.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanLookup.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,23 +45,23 @@ * @param accessType Access type */ public BeanLookup(Object bean, AccessType accessType) { - super(); - AssertTools.assertNotNull(bean); - AssertTools.assertNotNull(accessType); - this.bean = bean; - this.accessType = accessType; + super(); + AssertTools.assertNotNull(bean); + AssertTools.assertNotNull(accessType); + this.bean = bean; + this.accessType = accessType; } /** {@inheritDoc} */ @Override public String lookup(String key) { - AssertTools.assertNotNull(key); - Object value; - try { - value = BeanTools.getValue(bean, accessType, key); - } catch (IllegalArgumentException e) { - value = null; - } - return value != null ? value.toString() : null; + AssertTools.assertNotNull(key); + Object value; + try { + value = BeanTools.getValue(bean, accessType, key); + } catch (IllegalArgumentException e) { + value = null; + } + return value != null ? value.toString() : null; } } \ No newline at end of file Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/BeanTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,10 +49,10 @@ * Access type */ public enum AccessType { - /** Access by (public) field */ - FIELD, - /** Access by (public) getter */ - GETTER; + /** Access by (public) field */ + FIELD, + /** Access by (public) getter */ + GETTER; } /** Error message for annotation not found in a class */ @@ -73,40 +73,40 @@ * @return Equality */ public static boolean equals(Object thiz, Object obj, AccessType accessType, String... properties) { - AssertTools.assertNotNull(thiz); - AssertTools.assertNotEmpty(properties); - AssertTools.assertArrayNotNull(properties); - if (thiz == obj) { - return true; - } - if (obj != null - && thiz != null - && (thiz.getClass().isAssignableFrom(obj.getClass()) || obj.getClass() - .isAssignableFrom(thiz.getClass()))) { - EqualsBuilder builder = new EqualsBuilder(); - for (String property : properties) { - try { - Object val1 = getValue(thiz, accessType, property); - Object val2 = getValue(obj, accessType, property); + AssertTools.assertNotNull(thiz); + AssertTools.assertNotEmpty(properties); + AssertTools.assertArrayNotNull(properties); + if (thiz == obj) { + return true; + } + if (obj != null + && thiz != null + && (thiz.getClass().isAssignableFrom(obj.getClass()) || obj.getClass() + .isAssignableFrom(thiz.getClass()))) { + EqualsBuilder builder = new EqualsBuilder(); + for (String property : properties) { + try { + Object val1 = getValue(thiz, accessType, property); + Object val2 = getValue(obj, accessType, property); - // Test hashCodes first - if (val1 != null && val2 != null && !builder.append(val1.hashCode(), val2.hashCode()).isEquals()) { - return false; - } + // Test hashCodes first + if (val1 != null && val2 != null && !builder.append(val1.hashCode(), val2.hashCode()).isEquals()) { + return false; + } - if (!builder.append(val1, val2).isEquals()) { - return false; - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), property), e); - } + if (!builder.append(val1, val2).isEquals()) { + return false; + } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), property), e); + } - } - return builder.isEquals(); - } - return false; + } + return builder.isEquals(); + } + return false; } /** @@ -117,39 +117,39 @@ * @return Equality */ public static boolean equals(Object thiz, Object obj, Field... fields) { - AssertTools.assertNotNull(thiz); - AssertTools.assertNotEmpty(fields); - AssertTools.assertArrayNotNull(fields); - if (thiz == obj) { - return true; - } - if (obj != null - && thiz != null - && (thiz.getClass().isAssignableFrom(obj.getClass()) || obj.getClass() - .isAssignableFrom(thiz.getClass()))) { - EqualsBuilder builder = new EqualsBuilder(); - for (Field field : fields) { - try { - Object val1 = field.get(thiz); - Object val2 = field.get(obj); + AssertTools.assertNotNull(thiz); + AssertTools.assertNotEmpty(fields); + AssertTools.assertArrayNotNull(fields); + if (thiz == obj) { + return true; + } + if (obj != null + && thiz != null + && (thiz.getClass().isAssignableFrom(obj.getClass()) || obj.getClass() + .isAssignableFrom(thiz.getClass()))) { + EqualsBuilder builder = new EqualsBuilder(); + for (Field field : fields) { + try { + Object val1 = field.get(thiz); + Object val2 = field.get(obj); - // Test hashCodes first - if (val1 != null && val2 != null && !builder.append(val1.hashCode(), val2.hashCode()).isEquals()) { - return false; - } + // Test hashCodes first + if (val1 != null && val2 != null && !builder.append(val1.hashCode(), val2.hashCode()).isEquals()) { + return false; + } - if (!builder.append(val1, val2).isEquals()) { - return false; - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), field.getName()), e); - } - } - return builder.isEquals(); - } - return false; + if (!builder.append(val1, val2).isEquals()) { + return false; + } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), field.getName()), e); + } + } + return builder.isEquals(); + } + return false; } /** @@ -160,9 +160,9 @@ * @throws NoSuchFieldException If an annotation cannot be found */ public static Field getAnnotatedPublicField(Object thiz, Class<? extends Annotation>... annotations) - throws NoSuchFieldException { - AssertTools.assertNotNull(thiz); - return getAnnotatedPublicField(thiz.getClass(), annotations); + throws NoSuchFieldException { + AssertTools.assertNotNull(thiz); + return getAnnotatedPublicField(thiz.getClass(), annotations); } /** @@ -173,32 +173,32 @@ * @throws NoSuchFieldException If an annotation cannot be found */ public static Field getAnnotatedPrivateField(Class<?> clazz, Class<? extends Annotation>... annotations) - throws NoSuchFieldException { - AssertTools.assertNotNull(clazz); - AssertTools.assertNotEmpty(annotations); - AssertTools.assertArrayNotNull(annotations); - Field[] fields = clazz.getDeclaredFields(); - Field field = null; - int i = 0; - while (field == null && i < fields.length) { - int j = 0; - while (field == null && j < annotations.length) { - if (fields[i].isAnnotationPresent(annotations[j])) { - field = fields[i]; - } - ++j; - } - ++i; - } - if (field == null) { - // if not found - if (clazz.getSuperclass() == null) { - throw new NoSuchFieldException(String.format(ANNOTATION, clazz.getName(), Arrays.toString(annotations))); - } - // recursive search in the superclass - return getAnnotatedInheritedField(clazz, clazz.getSuperclass(), annotations); - } - return field; + throws NoSuchFieldException { + AssertTools.assertNotNull(clazz); + AssertTools.assertNotEmpty(annotations); + AssertTools.assertArrayNotNull(annotations); + Field[] fields = clazz.getDeclaredFields(); + Field field = null; + int i = 0; + while (field == null && i < fields.length) { + int j = 0; + while (field == null && j < annotations.length) { + if (fields[i].isAnnotationPresent(annotations[j])) { + field = fields[i]; + } + ++j; + } + ++i; + } + if (field == null) { + // if not found + if (clazz.getSuperclass() == null) { + throw new NoSuchFieldException(String.format(ANNOTATION, clazz.getName(), Arrays.toString(annotations))); + } + // recursive search in the superclass + return getAnnotatedInheritedField(clazz, clazz.getSuperclass(), annotations); + } + return field; } /** @@ -210,37 +210,37 @@ * @throws NoSuchFieldException If an annotation cannot be found */ private static Field getAnnotatedInheritedField(Class<?> baseClazz, Class<?> browsedClazz, - Class<? extends Annotation>... annotations) throws NoSuchFieldException { - AssertTools.assertNotNull(baseClazz); - AssertTools.assertNotEmpty(annotations); - AssertTools.assertArrayNotNull(annotations); + Class<? extends Annotation>... annotations) throws NoSuchFieldException { + AssertTools.assertNotNull(baseClazz); + AssertTools.assertNotEmpty(annotations); + AssertTools.assertArrayNotNull(annotations); - Field[] fields = browsedClazz.getDeclaredFields(); - Field field = null; - int i = 0; - while (field == null && i < fields.length) { - int j = 0; - while (field == null && j < annotations.length) { - if (fields[i].isAnnotationPresent(annotations[j]) - && (Modifier.isProtected(fields[i].getModifiers()) - || Modifier.isPublic(fields[i].getModifiers()) || Modifier.isPrivate(fields[i] - .getModifiers()))) { - field = fields[i]; - } - ++j; - } - ++i; - } - if (field == null) { - // if not found - if (browsedClazz.getSuperclass() == null) { - throw new NoSuchFieldException(String.format(ANNOTATION, baseClazz.getName(), Arrays - .toString(annotations))); - } - // recursive search in the superclass - getAnnotatedInheritedField(baseClazz, browsedClazz.getSuperclass(), annotations); - } - return field; + Field[] fields = browsedClazz.getDeclaredFields(); + Field field = null; + int i = 0; + while (field == null && i < fields.length) { + int j = 0; + while (field == null && j < annotations.length) { + if (fields[i].isAnnotationPresent(annotations[j]) + && (Modifier.isProtected(fields[i].getModifiers()) + || Modifier.isPublic(fields[i].getModifiers()) || Modifier.isPrivate(fields[i] + .getModifiers()))) { + field = fields[i]; + } + ++j; + } + ++i; + } + if (field == null) { + // if not found + if (browsedClazz.getSuperclass() == null) { + throw new NoSuchFieldException(String.format(ANNOTATION, baseClazz.getName(), Arrays + .toString(annotations))); + } + // recursive search in the superclass + getAnnotatedInheritedField(baseClazz, browsedClazz.getSuperclass(), annotations); + } + return field; } /** @@ -251,27 +251,27 @@ * @throws NoSuchFieldException If an annotation cannot be found */ public static Field getAnnotatedPublicField(Class<?> clazz, Class<? extends Annotation>... annotations) - throws NoSuchFieldException { - AssertTools.assertNotNull(clazz); - AssertTools.assertNotEmpty(annotations); - AssertTools.assertArrayNotNull(annotations); - Field[] fields = clazz.getFields(); - Field field = null; - int i = 0; - while (field == null && i < fields.length) { - int j = 0; - while (field == null && j < annotations.length) { - if (fields[i].isAnnotationPresent(annotations[j])) { - field = fields[i]; - } - ++j; - } - ++i; - } - if (field == null) { - throw new NoSuchFieldException(String.format(ANNOTATION, clazz.getName(), Arrays.toString(annotations))); - } - return field; + throws NoSuchFieldException { + AssertTools.assertNotNull(clazz); + AssertTools.assertNotEmpty(annotations); + AssertTools.assertArrayNotNull(annotations); + Field[] fields = clazz.getFields(); + Field field = null; + int i = 0; + while (field == null && i < fields.length) { + int j = 0; + while (field == null && j < annotations.length) { + if (fields[i].isAnnotationPresent(annotations[j])) { + field = fields[i]; + } + ++j; + } + ++i; + } + if (field == null) { + throw new NoSuchFieldException(String.format(ANNOTATION, clazz.getName(), Arrays.toString(annotations))); + } + return field; } /** @@ -284,10 +284,10 @@ * @throws NoSuchFieldException If the property does not exist */ public static <A extends Annotation> A getAnnotationOnProperty(Class<?> beanClass, Class<A> annotation, - String property) throws NoSuchFieldException { - AssertTools.assertNotNull(beanClass); - AssertTools.assertNotNull(annotation); - return beanClass.getField(property).getAnnotation(annotation); + String property) throws NoSuchFieldException { + AssertTools.assertNotNull(beanClass); + AssertTools.assertNotNull(annotation); + return beanClass.getField(property).getAnnotation(annotation); } /** @@ -298,34 +298,34 @@ * @return Property value */ public static Object getValue(Object bean, AccessType accessType, String property) { - AssertTools.assertNotNull(bean); - AssertTools.assertNotNull(accessType); - AssertTools.assertNotEmpty(property); - Object value; - switch (accessType) { - case GETTER: - try { - value = new PropertyDescriptor(property, bean.getClass(), "is" + StringUtils.capitalize(property), - null).getReadMethod().invoke(bean, PARAMETERS); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(e); - } - break; - case FIELD: - try { - value = bean.getClass().getField(property).get(bean); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(e); - } - break; - default: - throw new IllegalArgumentException(); - } - return value; + AssertTools.assertNotNull(bean); + AssertTools.assertNotNull(accessType); + AssertTools.assertNotEmpty(property); + Object value; + switch (accessType) { + case GETTER: + try { + value = new PropertyDescriptor(property, bean.getClass(), "is" + StringUtils.capitalize(property), null) + .getReadMethod().invoke(bean, PARAMETERS); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + break; + case FIELD: + try { + value = bean.getClass().getField(property).get(bean); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + break; + default: + throw new IllegalArgumentException(); + } + return value; } /** @@ -336,15 +336,15 @@ * @return Property value */ public static Object getValueFromPath(Object bean, AccessType accessType, String pathToProperty) { - AssertTools.assertNotNull(bean); - AssertTools.assertNotNull(accessType); - AssertTools.assertNotEmpty(pathToProperty); - List<String> beanNames = createAccessBeanList(pathToProperty); - Object curBean = bean; - for (String beanName : beanNames) { - curBean = BeanTools.getValue(curBean, AccessType.GETTER, beanName); - } - return curBean; + AssertTools.assertNotNull(bean); + AssertTools.assertNotNull(accessType); + AssertTools.assertNotEmpty(pathToProperty); + List<String> beanNames = createAccessBeanList(pathToProperty); + Object curBean = bean; + for (String beanName : beanNames) { + curBean = BeanTools.getValue(curBean, AccessType.GETTER, beanName); + } + return curBean; } /** @@ -354,12 +354,12 @@ * @return an array of all the different bean names to access */ private static List<String> createAccessBeanList(final String propertiesPath) { - final Matcher matcher = Pattern.compile("\\w+").matcher(propertiesPath); - List<String> paramList = new ArrayList<String>(); - while (matcher.find()) { - paramList.add(propertiesPath.substring(matcher.start(), matcher.end())); - } - return paramList; + final Matcher matcher = Pattern.compile("\\w+").matcher(propertiesPath); + List<String> paramList = new ArrayList<String>(); + while (matcher.find()) { + paramList.add(propertiesPath.substring(matcher.start(), matcher.end())); + } + return paramList; } /** @@ -369,23 +369,23 @@ * @return HashCode */ public static int hashCode(Object thiz, Field... fields) { - AssertTools.assertNotNull(thiz); - AssertTools.assertNotEmpty(fields); - AssertTools.assertArrayNotNull(fields); - int seed = thiz.getClass().hashCode(); - int hashCode = seed; - for (Field field : fields) { - Object value; - try { - value = field.get(thiz); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), field.getName()), e); - } - hashCode += value != null ? seed ^ value.hashCode() : 0; - } - return hashCode; + AssertTools.assertNotNull(thiz); + AssertTools.assertNotEmpty(fields); + AssertTools.assertArrayNotNull(fields); + int seed = thiz.getClass().hashCode(); + int hashCode = seed; + for (Field field : fields) { + Object value; + try { + value = field.get(thiz); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(String.format(FIELD, thiz.getClass(), field.getName()), e); + } + hashCode += value != null ? seed ^ value.hashCode() : 0; + } + return hashCode; } /** @@ -395,15 +395,15 @@ * @return HashCode */ public static int hashCode(Object thiz, Object... ids) { - AssertTools.assertNotNull(thiz); - AssertTools.assertNotEmpty(ids); - AssertTools.assertNotNull(ids); - int seed = thiz.getClass().hashCode(); - int hashCode = seed; - for (Object id : ids) { - hashCode += id != null ? seed ^ id.hashCode() : 0; - } - return hashCode; + AssertTools.assertNotNull(thiz); + AssertTools.assertNotEmpty(ids); + AssertTools.assertNotNull(ids); + int seed = thiz.getClass().hashCode(); + int hashCode = seed; + for (Object id : ids) { + hashCode += id != null ? seed ^ id.hashCode() : 0; + } + return hashCode; } /** @@ -416,8 +416,8 @@ * @throws NoSuchFieldException If the property does not exist */ public static <A extends Annotation> boolean isAnnotationOnProperty(Class<?> beanClass, Class<A> annotation, - String property) throws NoSuchFieldException { - return getAnnotationOnProperty(beanClass, annotation, property) != null; + String property) throws NoSuchFieldException { + return getAnnotationOnProperty(beanClass, annotation, property) != null; } /** @@ -429,22 +429,22 @@ * @return Bean display */ public static String toString(Object bean, String delimiter, AccessType accessType, String... pathsToProperties) { - AssertTools.assertNotNull(bean); - AssertTools.assertNotEmpty(delimiter); - AssertTools.assertArrayNotNull(pathsToProperties); - Class<?> clazz = bean.getClass(); - StringBuilder builder = new StringBuilder(clazz.getName()); - for (String pathToProperty : pathsToProperties) { - try { - Object value = getValueFromPath(bean, accessType, pathToProperty); - builder.append(delimiter + pathToProperty + ": " + (value != null ? value.toString() : "<null>")); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IllegalArgumentException(String.format(FIELD, clazz, pathToProperty), e); - } - } - return builder.toString(); + AssertTools.assertNotNull(bean); + AssertTools.assertNotEmpty(delimiter); + AssertTools.assertArrayNotNull(pathsToProperties); + Class<?> clazz = bean.getClass(); + StringBuilder builder = new StringBuilder(clazz.getName()); + for (String pathToProperty : pathsToProperties) { + try { + Object value = getValueFromPath(bean, accessType, pathToProperty); + builder.append(delimiter + pathToProperty + ": " + (value != null ? value.toString() : "<null>")); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalArgumentException(String.format(FIELD, clazz, pathToProperty), e); + } + } + return builder.toString(); } /** @@ -455,14 +455,14 @@ * @return Bean display */ public static String toString(Object bean, AccessType accessType, String... properties) { - return toString(bean, "\n- ", accessType, properties); + return toString(bean, "\n- ", accessType, properties); } /** * Constructor (prevents instantiation) */ private BeanTools() { - // + // } /** @@ -473,8 +473,8 @@ * @return Bean display */ public static String beanListToString(List<? extends Object> beansList, AccessType accessType, - String... pathsToProperties) { - return BeanTools.beanListToString(beansList, "\n", ", ", accessType, pathsToProperties); + String... pathsToProperties) { + return BeanTools.beanListToString(beansList, "\n", ", ", accessType, pathsToProperties); } /** @@ -487,21 +487,21 @@ * @return Bean display */ public static String beanListToString(List<? extends Object> beansList, String delimiterBeans, - String delimiterProperties, AccessType accessType, String... pathsToProperties) { - AssertTools.assertNotNull(beansList); - AssertTools.assertNotEmpty(delimiterProperties); - AssertTools.assertNotEmpty(delimiterBeans); - AssertTools.assertNotNull(accessType); - StringBuilder builder = new StringBuilder(); - Iterator<? extends Object> itBeans = beansList.iterator(); - while (itBeans.hasNext()) { - Object bean = itBeans.next(); - builder.append(toString(bean, delimiterProperties, accessType, pathsToProperties)); - if (itBeans.hasNext()) { - builder.append(delimiterBeans); - } - } - return builder.toString(); + String delimiterProperties, AccessType accessType, String... pathsToProperties) { + AssertTools.assertNotNull(beansList); + AssertTools.assertNotEmpty(delimiterProperties); + AssertTools.assertNotEmpty(delimiterBeans); + AssertTools.assertNotNull(accessType); + StringBuilder builder = new StringBuilder(); + Iterator<? extends Object> itBeans = beansList.iterator(); + while (itBeans.hasNext()) { + Object bean = itBeans.next(); + builder.append(toString(bean, delimiterProperties, accessType, pathsToProperties)); + if (itBeans.hasNext()) { + builder.append(delimiterBeans); + } + } + return builder.toString(); } /** @@ -515,7 +515,7 @@ */ @SuppressWarnings("unchecked") public static <T> Comparator<T> createPropertyComparator(final String propertyExpression) { - return new BeanComparator(propertyExpression); + return new BeanComparator(propertyExpression); } /** @@ -533,6 +533,6 @@ */ @SuppressWarnings("unchecked") public static <T> Comparator<T> createPropertyComparator(final String propertyExpression, Comparator<T> comparator) { - return new BeanComparator(propertyExpression, comparator); + return new BeanComparator(propertyExpression, comparator); } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CantharellaConfig.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CantharellaConfig.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CantharellaConfig.java 2013-02-18 07:27:17 UTC (rev 119) @@ -27,7 +27,6 @@ import org.nuiton.util.ApplicationConfig; import org.nuiton.util.ArgumentsParserException; - /** * Used as factory in spring configuration to get configuration file as properties * this class use internaly {@link ApplicationConfig}. @@ -46,7 +45,7 @@ * @throws ArgumentsParserException */ static public Properties getProperties() throws ArgumentsParserException { - return getProperties("cantharella.conf"); + return getProperties("cantharella.conf"); } /** @@ -58,9 +57,9 @@ * @throws ArgumentsParserException */ static public Properties getProperties(String filename) throws ArgumentsParserException { - ApplicationConfig config = new ApplicationConfig(filename); - config.parse(); - Properties result = config.getFlatOptions(); - return result; + ApplicationConfig config = new ApplicationConfig(filename); + config.parse(); + Properties result = config.getFlatOptions(); + return result; } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CaptchaTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CaptchaTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CaptchaTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,14 +41,14 @@ * @return Captcha */ public static String random() { - return RandomStringUtils - .randomNumeric((int) (Math.random() * (CAPTCHA_LENGTH_MAX - CAPTCHA_LENGTH_MIN) + CAPTCHA_LENGTH_MIN)); + return RandomStringUtils + .randomNumeric((int) (Math.random() * (CAPTCHA_LENGTH_MAX - CAPTCHA_LENGTH_MIN) + CAPTCHA_LENGTH_MIN)); } /** * Constructor (prevents from instantiation) */ private CaptchaTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CollectionTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CollectionTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CollectionTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,21 +48,21 @@ * @return The answer */ public static <T> boolean containsOnlySameValue(Collection<T> collection, T value) { - AssertTools.assertNotNull(collection); + AssertTools.assertNotNull(collection); - if (collection.isEmpty()) { - return false; - } + if (collection.isEmpty()) { + return false; + } - boolean hasSame = true; - Iterator<T> itCol = collection.iterator(); - while (hasSame && itCol.hasNext()) { - T curVal = itCol.next(); - if (!ObjectUtils.equals(curVal, value)) { - hasSame = false; - } - } - return hasSame; + boolean hasSame = true; + Iterator<T> itCol = collection.iterator(); + while (hasSame && itCol.hasNext()) { + T curVal = itCol.next(); + if (!ObjectUtils.equals(curVal, value)) { + hasSame = false; + } + } + return hasSame; } /** @@ -73,9 +73,9 @@ * @return Intersection */ public static <T> Set<T> intersect(Set<T> s1, Set<T> s2) { - Set<T> intersect = s1 == null ? new HashSet<T>() : new HashSet<T>(s1); - intersect.retainAll(s2); - return intersect; + Set<T> intersect = s1 == null ? new HashSet<T>() : new HashSet<T>(s1); + intersect.retainAll(s2); + return intersect; } /** @@ -85,11 +85,11 @@ * @param collectionToRead Collection to read */ public static <T> void setter(Collection<T> collectionToWrite, Collection<T> collectionToRead) { - AssertTools.assertNotNull(collectionToWrite); - collectionToWrite.clear(); - if (collectionToRead != null) { - collectionToWrite.addAll(collectionToRead); - } + AssertTools.assertNotNull(collectionToWrite); + collectionToWrite.clear(); + if (collectionToRead != null) { + collectionToWrite.addAll(collectionToRead); + } } /** @@ -102,16 +102,16 @@ * @return true if the value is found, otherwise false */ public static boolean containsWithValue(Collection<? extends Object> collection, String pathToProperty, - AccessType accessType, Object value) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); - for (Object curBean : collection) { - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - if (curVal.equals(value)) { - return true; - } - } - return false; + AccessType accessType, Object value) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); + for (Object curBean : collection) { + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + if (curVal.equals(value)) { + return true; + } + } + return false; } /** @@ -123,17 +123,17 @@ * @return The count result */ public static int countWithValue(Collection<? extends Object> collection, String pathToProperty, - AccessType accessType, Object value) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); - int count = 0; - for (Object curBean : collection) { - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - if (value.equals(curVal)) { - count++; - } - } - return count; + AccessType accessType, Object value) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); + int count = 0; + for (Object curBean : collection) { + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + if (value.equals(curVal)) { + count++; + } + } + return count; } /** @@ -147,16 +147,16 @@ * @return The bean with the specific value, null if not found */ public static <T extends Object> T findWithValue(List<T> collection, String pathToProperty, AccessType accessType, - Object value) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); - for (T curBean : collection) { - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - if (value.equals(curVal)) { - return curBean; - } - } - return null; + Object value) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); + for (T curBean : collection) { + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + if (value.equals(curVal)) { + return curBean; + } + } + return null; } /** @@ -169,21 +169,21 @@ * @return true if found, false otherwise */ public static boolean removeWithValue(Collection<? extends Object> collection, String pathToProperty, - AccessType accessType, Object value) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); - boolean hasDeleted = false; + AccessType accessType, Object value) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); + boolean hasDeleted = false; - Iterator<? extends Object> itList = collection.iterator(); - while (itList.hasNext()) { - Object curBean = itList.next(); - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - if (value.equals(curVal)) { - itList.remove(); - hasDeleted = true; - } - } - return hasDeleted; + Iterator<? extends Object> itList = collection.iterator(); + while (itList.hasNext()) { + Object curBean = itList.next(); + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + if (value.equals(curVal)) { + itList.remove(); + hasDeleted = true; + } + } + return hasDeleted; } /** @@ -196,21 +196,21 @@ * @return true if at least one value is found, false otherwise */ public static boolean removeAllWithValue(Collection<? extends Object> collection, String pathToProperty, - AccessType accessType, Collection<? extends Object> values) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); - boolean hasDeleted = false; + AccessType accessType, Collection<? extends Object> values) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); + boolean hasDeleted = false; - Iterator<? extends Object> itList = collection.iterator(); - while (itList.hasNext()) { - Object curBean = itList.next(); - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - if (curVal != null && values.contains(curVal)) { - itList.remove(); - hasDeleted = true; - } - } - return hasDeleted; + Iterator<? extends Object> itList = collection.iterator(); + while (itList.hasNext()) { + Object curBean = itList.next(); + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + if (curVal != null && values.contains(curVal)) { + itList.remove(); + hasDeleted = true; + } + } + return hasDeleted; } /** @@ -222,23 +222,23 @@ * @return These values */ public static List<Object> valuesFromList(Collection<? extends Object> collection, String pathToProperty, - AccessType accessType) { - AssertTools.assertNotNull(collection); - AssertTools.assertNotEmpty(pathToProperty); + AccessType accessType) { + AssertTools.assertNotNull(collection); + AssertTools.assertNotEmpty(pathToProperty); - List<Object> values = new ArrayList<Object>(); - for (Object curBean : collection) { - Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); - values.add(curVal); - } - return values; + List<Object> values = new ArrayList<Object>(); + for (Object curBean : collection) { + Object curVal = BeanTools.getValueFromPath(curBean, accessType, pathToProperty); + values.add(curVal); + } + return values; } /** * Constructor (prevents instantiation) */ private CollectionTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CoordTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CoordTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/CoordTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -112,64 +112,64 @@ private static final String MINUTES_SEPARATOR_PATTERN = "\\."; static { - String[] md = LONGITUDE_MAX_MINUTES_STRING.split(MINUTES_SEPARATOR_PATTERN); + String[] md = LONGITUDE_MAX_MINUTES_STRING.split(MINUTES_SEPARATOR_PATTERN); - MINUTES_INTEGER_LENGTH = md[0].length(); - MINUTES_DECIMAL_LENGTH = md[1].length(); + MINUTES_INTEGER_LENGTH = md[0].length(); + MINUTES_DECIMAL_LENGTH = md[1].length(); - String patternMinutes = "[0-9]"; - String patternDegrees = "[ 0-9]"; + String patternMinutes = "[0-9]"; + String patternDegrees = "[ 0-9]"; - StringBuilder pattern = new StringBuilder("^("); - for (int i = 0; i < String.valueOf(LATITUDE_MAX_DEGREES).length(); ++i) { - pattern.append(patternDegrees); - } - pattern.append(')'); - pattern.append(DEGREES); - pattern.append('('); - for (int i = 0; i < MINUTES_INTEGER_LENGTH; ++i) { - pattern.append(patternMinutes); - } - pattern.append(")"); - pattern.append(MINUTES_SEPARATOR_PATTERN); - pattern.append('('); - for (int i = 0; i < MINUTES_DECIMAL_LENGTH; ++i) { - pattern.append(patternMinutes); - } - pattern.append(')'); - pattern.append(MINUTES); - pattern.append("(["); - for (char o : LATITUDE_ORIENTATIONS) { - pattern.append(o); - } - pattern.append("])$"); - LATITUDE_PATTERN = Pattern.compile(pattern.toString()); + StringBuilder pattern = new StringBuilder("^("); + for (int i = 0; i < String.valueOf(LATITUDE_MAX_DEGREES).length(); ++i) { + pattern.append(patternDegrees); + } + pattern.append(')'); + pattern.append(DEGREES); + pattern.append('('); + for (int i = 0; i < MINUTES_INTEGER_LENGTH; ++i) { + pattern.append(patternMinutes); + } + pattern.append(")"); + pattern.append(MINUTES_SEPARATOR_PATTERN); + pattern.append('('); + for (int i = 0; i < MINUTES_DECIMAL_LENGTH; ++i) { + pattern.append(patternMinutes); + } + pattern.append(')'); + pattern.append(MINUTES); + pattern.append("(["); + for (char o : LATITUDE_ORIENTATIONS) { + pattern.append(o); + } + pattern.append("])$"); + LATITUDE_PATTERN = Pattern.compile(pattern.toString()); - pattern = new StringBuilder("^("); - for (int i = 0; i < String.valueOf(LONGITUDE_MAX_DEGREES).length(); ++i) { - pattern.append(patternDegrees); - } - pattern.append(')'); - pattern.append(DEGREES); - pattern.append('('); - for (int i = 0; i < MINUTES_INTEGER_LENGTH; ++i) { - pattern.append(patternMinutes); - } - pattern.append(")"); - pattern.append(MINUTES_SEPARATOR_PATTERN); - pattern.append('('); - for (int i = 0; i < MINUTES_DECIMAL_LENGTH; ++i) { - pattern.append(patternMinutes); - } - pattern.append(')'); - pattern.append(MINUTES); - pattern.append("(["); - for (char o : LONGITUDE_ORIENTATIONS) { - pattern.append(o); - } - pattern.append("])$"); + pattern = new StringBuilder("^("); + for (int i = 0; i < String.valueOf(LONGITUDE_MAX_DEGREES).length(); ++i) { + pattern.append(patternDegrees); + } + pattern.append(')'); + pattern.append(DEGREES); + pattern.append('('); + for (int i = 0; i < MINUTES_INTEGER_LENGTH; ++i) { + pattern.append(patternMinutes); + } + pattern.append(")"); + pattern.append(MINUTES_SEPARATOR_PATTERN); + pattern.append('('); + for (int i = 0; i < MINUTES_DECIMAL_LENGTH; ++i) { + pattern.append(patternMinutes); + } + pattern.append(')'); + pattern.append(MINUTES); + pattern.append("(["); + for (char o : LONGITUDE_ORIENTATIONS) { + pattern.append(o); + } + pattern.append("])$"); - LONGITUDE_PATTERN = Pattern.compile(pattern.toString()); + LONGITUDE_PATTERN = Pattern.compile(pattern.toString()); } /** @@ -180,22 +180,22 @@ * @return Latitude */ public static String latitude(Integer d, BigDecimal m, Character o) { - // Check values - AssertTools.assertGreaterOrEquals(d, LATITUDE_MIN_DEGREES); - AssertTools.assertLowerOrEquals(d, LATITUDE_MAX_DEGREES); - AssertTools.assertGreaterOrEquals(m, LATITUDE_MIN_MINUTES); - AssertTools.assertLowerOrEquals(m, LATITUDE_MAX_MINUTES); - AssertTools.assertIn(Character.toUpperCase(o), LATITUDE_ORIENTATIONS); - // Format values - // LOG.debug(m); - // LOG.debug(NumberTools.doubleToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH)); - String[] md = NumberTools.bigDecimalToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH, - 2).split(MINUTES_SEPARATOR_PATTERN); - // LOG.debug(md); - return StringUtils.leftPad(String.valueOf(d), String.valueOf(LATITUDE_MAX_DEGREES).length()) + DEGREES - + StringUtils.leftPad(String.valueOf(md[0]), MINUTES_INTEGER_LENGTH, MINUTES_BLANK) + MINUTES_SEPARATOR - + StringUtils.rightPad(md[1], MINUTES_DECIMAL_LENGTH, MINUTES_BLANK) + MINUTES - + Character.toUpperCase(o); + // Check values + AssertTools.assertGreaterOrEquals(d, LATITUDE_MIN_DEGREES); + AssertTools.assertLowerOrEquals(d, LATITUDE_MAX_DEGREES); + AssertTools.assertGreaterOrEquals(m, LATITUDE_MIN_MINUTES); + AssertTools.assertLowerOrEquals(m, LATITUDE_MAX_MINUTES); + AssertTools.assertIn(Character.toUpperCase(o), LATITUDE_ORIENTATIONS); + // Format values + // LOG.debug(m); + // LOG.debug(NumberTools.doubleToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH)); + String[] md = NumberTools.bigDecimalToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH, + 2).split(MINUTES_SEPARATOR_PATTERN); + // LOG.debug(md); + return StringUtils.leftPad(String.valueOf(d), String.valueOf(LATITUDE_MAX_DEGREES).length()) + DEGREES + + StringUtils.leftPad(String.valueOf(md[0]), MINUTES_INTEGER_LENGTH, MINUTES_BLANK) + MINUTES_SEPARATOR + + StringUtils.rightPad(md[1], MINUTES_DECIMAL_LENGTH, MINUTES_BLANK) + MINUTES + + Character.toUpperCase(o); } /** @@ -204,12 +204,12 @@ * @return Degrees */ public static Integer latitudeDegrees(String latitude) { - if (StringUtils.isEmpty(latitude)) { - return null; - } - Matcher matcher = LATITUDE_PATTERN.matcher(latitude); - matcher.lookingAt(); - return Integer.valueOf(matcher.group(1).trim()); + if (StringUtils.isEmpty(latitude)) { + return null; + } + Matcher matcher = LATITUDE_PATTERN.matcher(latitude); + matcher.lookingAt(); + return Integer.valueOf(matcher.group(1).trim()); } /** @@ -218,13 +218,13 @@ * @return Minutes */ public static BigDecimal latitudeMinutes(String latitude) { - if (StringUtils.isEmpty(latitude)) { - return null; - } - Matcher matcher = LATITUDE_PATTERN.matcher(latitude); - matcher.lookingAt(); - return NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), Locale.ENGLISH, - MINUTES_DECIMAL_LENGTH, 2); + if (StringUtils.isEmpty(latitude)) { + return null; + } + Matcher matcher = LATITUDE_PATTERN.matcher(latitude); + matcher.lookingAt(); + return NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), Locale.ENGLISH, + MINUTES_DECIMAL_LENGTH, 2); } /** @@ -233,12 +233,12 @@ * @return Orientation */ public static Character latitudeOrientation(String latitude) { - if (StringUtils.isEmpty(latitude)) { - return null; - } - Matcher matcher = LATITUDE_PATTERN.matcher(latitude); - matcher.lookingAt(); - return Character.valueOf(matcher.group(4).charAt(0)); + if (StringUtils.isEmpty(latitude)) { + return null; + } + Matcher matcher = LATITUDE_PATTERN.matcher(latitude); + matcher.lookingAt(); + return Character.valueOf(matcher.group(4).charAt(0)); } /** @@ -249,19 +249,19 @@ * @return Longitude */ public static String longitude(Integer d, BigDecimal m, Character o) { - // Check values - AssertTools.assertGreaterOrEquals(d, LONGITUDE_MIN_DEGREES); - AssertTools.assertLowerOrEquals(d, LONGITUDE_MAX_DEGREES); - AssertTools.assertGreaterOrEquals(m, LONGITUDE_MIN_MINUTES); - AssertTools.assertLowerOrEquals(m, LONGITUDE_MAX_MINUTES); - AssertTools.assertIn(Character.toUpperCase(o), LONGITUDE_ORIENTATIONS); - // Format values - String[] md = NumberTools.bigDecimalToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH, - 3).split(MINUTES_SEPARATOR_PATTERN); - return StringUtils.leftPad(String.valueOf(d), String.valueOf(LONGITUDE_MAX_DEGREES).length()) + DEGREES - + StringUtils.leftPad(String.valueOf(md[0]), MINUTES_INTEGER_LENGTH, MINUTES_BLANK) + MINUTES_SEPARATOR - + StringUtils.rightPad(md[1], MINUTES_DECIMAL_LENGTH, MINUTES_BLANK) + MINUTES - + Character.toUpperCase(o); + // Check values + AssertTools.assertGreaterOrEquals(d, LONGITUDE_MIN_DEGREES); + AssertTools.assertLowerOrEquals(d, LONGITUDE_MAX_DEGREES); + AssertTools.assertGreaterOrEquals(m, LONGITUDE_MIN_MINUTES); + AssertTools.assertLowerOrEquals(m, LONGITUDE_MAX_MINUTES); + AssertTools.assertIn(Character.toUpperCase(o), LONGITUDE_ORIENTATIONS); + // Format values + String[] md = NumberTools.bigDecimalToString(m, Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, MINUTES_DECIMAL_LENGTH, + 3).split(MINUTES_SEPARATOR_PATTERN); + return StringUtils.leftPad(String.valueOf(d), String.valueOf(LONGITUDE_MAX_DEGREES).length()) + DEGREES + + StringUtils.leftPad(String.valueOf(md[0]), MINUTES_INTEGER_LENGTH, MINUTES_BLANK) + MINUTES_SEPARATOR + + StringUtils.rightPad(md[1], MINUTES_DECIMAL_LENGTH, MINUTES_BLANK) + MINUTES + + Character.toUpperCase(o); } /** @@ -270,12 +270,12 @@ * @return Degrees */ public static Integer longitudeDegrees(String longitude) { - if (StringUtils.isEmpty(longitude)) { - return null; - } - Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); - matcher.lookingAt(); - return Integer.valueOf(matcher.group(1).trim()); + if (StringUtils.isEmpty(longitude)) { + return null; + } + Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); + matcher.lookingAt(); + return Integer.valueOf(matcher.group(1).trim()); } /** @@ -284,13 +284,13 @@ * @return Minutes */ public static BigDecimal longitudeMinutes(String longitude) { - if (StringUtils.isEmpty(longitude)) { - return null; - } - Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); - matcher.lookingAt(); - return NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), Locale.ENGLISH, - MINUTES_DECIMAL_LENGTH, 3); + if (StringUtils.isEmpty(longitude)) { + return null; + } + Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); + matcher.lookingAt(); + return NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), Locale.ENGLISH, + MINUTES_DECIMAL_LENGTH, 3); } /** @@ -299,12 +299,12 @@ * @return Orientation */ public static Character longitudeOrientation(String longitude) { - if (StringUtils.isEmpty(longitude)) { - return null; - } - Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); - matcher.lookingAt(); - return Character.valueOf(matcher.group(4).charAt(0)); + if (StringUtils.isEmpty(longitude)) { + return null; + } + Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); + matcher.lookingAt(); + return Character.valueOf(matcher.group(4).charAt(0)); } /** @@ -313,18 +313,18 @@ * @return TRUE if the latitude is valid */ public static boolean validateLatitude(String latitude) { - AssertTools.assertNotEmpty(latitude); + AssertTools.assertNotEmpty(latitude); - Matcher matcher = LATITUDE_PATTERN.matcher(latitude); - if (matcher.lookingAt()) { - int d = Integer.valueOf(matcher.group(1).trim()); - BigDecimal m = NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), - Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, 2); - // if the latitude is 90 with others minutes, return false - return d >= LATITUDE_MIN_DEGREES && d <= LATITUDE_MAX_DEGREES && LATITUDE_MIN_MINUTES.compareTo(m) <= 0 - && LATITUDE_MAX_MINUTES.compareTo(m) >= 0 && (d != 90 || new BigDecimal("0.000").compareTo(m) == 0); - } - return false; + Matcher matcher = LATITUDE_PATTERN.matcher(latitude); + if (matcher.lookingAt()) { + int d = Integer.valueOf(matcher.group(1).trim()); + BigDecimal m = NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), + Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, 2); + // if the latitude is 90 with others minutes, return false + return d >= LATITUDE_MIN_DEGREES && d <= LATITUDE_MAX_DEGREES && LATITUDE_MIN_MINUTES.compareTo(m) <= 0 + && LATITUDE_MAX_MINUTES.compareTo(m) >= 0 && (d != 90 || new BigDecimal("0.000").compareTo(m) == 0); + } + return false; } /** @@ -333,24 +333,24 @@ * @return TRUE if the longitude is valid */ public static boolean validateLongitude(String longitude) { - AssertTools.assertNotEmpty(longitude); - Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); - if (matcher.lookingAt()) { - int d = Integer.valueOf(matcher.group(1).trim()); - BigDecimal m = NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), - Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, 3); - // if the longitude is 180 with others minutes, return false - return d >= LONGITUDE_MIN_DEGREES && d <= LONGITUDE_MAX_DEGREES && LONGITUDE_MIN_MINUTES.compareTo(m) <= 0 - && LATITUDE_MAX_MINUTES.compareTo(m) >= 0 - && (d != 180 || new BigDecimal("0.000").compareTo(m) == 0); - } - return false; + AssertTools.assertNotEmpty(longitude); + Matcher matcher = LONGITUDE_PATTERN.matcher(longitude); + if (matcher.lookingAt()) { + int d = Integer.valueOf(matcher.group(1).trim()); + BigDecimal m = NumberTools.parseBigDecimal(matcher.group(2) + MINUTES_SEPARATOR + matcher.group(3), + Locale.ENGLISH, MINUTES_DECIMAL_LENGTH, 3); + // if the longitude is 180 with others minutes, return false + return d >= LONGITUDE_MIN_DEGREES && d <= LONGITUDE_MAX_DEGREES && LONGITUDE_MIN_MINUTES.compareTo(m) <= 0 + && LATITUDE_MAX_MINUTES.compareTo(m) >= 0 + && (d != 180 || new BigDecimal("0.000").compareTo(m) == 0); + } + return false; } /** * Constructor */ private CoordTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenerateCsv.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenerateCsv.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenerateCsv.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,50 +41,52 @@ * Logger */ private static final Logger LOG = LoggerFactory.getLogger(GenerateCsv.class); - + /** delimiter de colonne */ private char columnsSeparator; + /** Copyright, pour Ird par défaut */ - private String copyright; + private String copyright; + /** Encoding utilisé pour le CSV */ private String encoding; - + /** Copyright utilisé par défaut, pour l'IRD en français */ private final static String DEFAULT_COPYRIGHT = "©IRD tous droits réservés"; - - /** static varable for UTF-8 encoding */ - public static final String CHARSET_UTF_8 ="UTF-8"; + /** static varable for UTF-8 encoding */ + public static final String CHARSET_UTF_8 = "UTF-8"; + /** static varable for ISO_8859_1 encoding */ - public static final String CHARSET_ISO_8859_1 ="ISO-8859-1"; - + public static final String CHARSET_ISO_8859_1 = "ISO-8859-1"; + /** * Constructeur par défaut */ - public GenerateCsv(){ - this(';',CHARSET_UTF_8); + public GenerateCsv() { + this(';', CHARSET_UTF_8); } - + /** * Constructeur * @param encoding utilisé pour le CSV */ - public GenerateCsv(String encoding){ - this(';',encoding); + public GenerateCsv(String encoding) { + this(';', encoding); } - + /** * Constructeur * * @param columnsSeparator caractère utilisé comme délimiteur de colonne * @param encoding utilisé pour le CSV */ - public GenerateCsv(char columnsSeparator, String encoding){ - setColumnsSeparator(columnsSeparator); - setEncoding(encoding); - setCopyright(DEFAULT_COPYRIGHT); + public GenerateCsv(char columnsSeparator, String encoding) { + setColumnsSeparator(columnsSeparator); + setEncoding(encoding); + setCopyright(DEFAULT_COPYRIGHT); } - + /** * Rend un flux qui décrit un ensemble de données en respectant le format CSV * @@ -93,32 +95,32 @@ * @return le flux de donnée en sortie * @throws IOException exception parvenue dans les traitements entrée/sortie du fichier */ - public ByteArrayOutputStream writeCSV(List<String[]> data, boolean withCopyright) throws IOException{ - - ByteArrayOutputStream csvStream = new ByteArrayOutputStream(); - OutputStreamWriter outWriter = new OutputStreamWriter(csvStream, encoding); - - CSVWriter csvWriter = new CSVWriter(outWriter, this.getColumnsSeparator()); - // paramétrage de l'écriture du CSV - - //écriture des données - csvWriter.writeAll(data); - if (withCopyright){ - //écriture du copyright - csvWriter.writeNext(new String[]{getCopyright()}); - } - csvWriter.close(); - LOG.debug("data written in the CSV stream"); - - return csvStream; + public ByteArrayOutputStream writeCSV(List<String[]> data, boolean withCopyright) throws IOException { + + ByteArrayOutputStream csvStream = new ByteArrayOutputStream(); + OutputStreamWriter outWriter = new OutputStreamWriter(csvStream, encoding); + + CSVWriter csvWriter = new CSVWriter(outWriter, this.getColumnsSeparator()); + // paramétrage de l'écriture du CSV + + //écriture des données + csvWriter.writeAll(data); + if (withCopyright) { + //écriture du copyright + csvWriter.writeNext(new String[] { getCopyright() }); + } + csvWriter.close(); + LOG.debug("data written in the CSV stream"); + + return csvStream; } - + /** * copyright getter * @return copyright */ public String getCopyright() { - return copyright; + return copyright; } /** @@ -126,7 +128,7 @@ * @param copyright copyright */ public void setCopyright(String copyright) { - this.copyright = copyright; + this.copyright = copyright; } /** @@ -134,7 +136,7 @@ * @return columnsSeparator */ public char getColumnsSeparator() { - return columnsSeparator; + return columnsSeparator; } /** @@ -142,7 +144,7 @@ * @param columnsSeparator columnsSeparator */ public void setColumnsSeparator(char columnsSeparator) { - this.columnsSeparator = columnsSeparator; + this.columnsSeparator = columnsSeparator; } /** @@ -150,7 +152,7 @@ * @return encoding */ public String getEncoding() { - return encoding; + return encoding; } /** @@ -158,7 +160,7 @@ * @param encoding encoding */ public void setEncoding(String encoding) { - this.encoding = encoding; + this.encoding = encoding; } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenericsTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenericsTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/GenericsTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,13 +38,13 @@ */ @SuppressWarnings("unchecked") public static <I, O extends I> O cast(I i) { - return (O) i; + return (O) i; } /** * Constructor (prevents instantiation) */ private GenericsTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/IntuitiveStringComparator.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/IntuitiveStringComparator.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/IntuitiveStringComparator.java 2013-02-18 07:27:17 UTC (rev 119) @@ -70,37 +70,37 @@ /** {@inheritDoc} */ @Override public int compare(T s1, T s2) { - str1 = s1; - str2 = s2; - len1 = str1.length(); - len2 = str2.length(); - pos1 = pos2 = 0; + str1 = s1; + str2 = s2; + len1 = str1.length(); + len2 = str2.length(); + pos1 = pos2 = 0; - if (len1 == 0) { - return len2 == 0 ? 0 : -1; - } else if (len2 == 0) { - return 1; - } + if (len1 == 0) { + return len2 == 0 ? 0 : -1; + } else if (len2 == 0) { + return 1; + } - while (pos1 < len1 && pos2 < len2) { - char ch1 = str1.charAt(pos1); - char ch2 = str2.charAt(pos2); - int result = 0; + while (pos1 < len1 && pos2 < len2) { + char ch1 = str1.charAt(pos1); + char ch2 = str2.charAt(pos2); + int result = 0; - if (Character.isDigit(ch1)) { - result = Character.isDigit(ch2) ? compareNumbers() : -1; - } else if (Character.isLetter(ch1)) { - result = Character.isLetter(ch2) ? compareOther(true) : 1; - } else { - result = Character.isDigit(ch2) ? 1 : Character.isLetter(ch2) ? -1 : compareOther(false); - } + if (Character.isDigit(ch1)) { + result = Character.isDigit(ch2) ? compareNumbers() : -1; + } else if (Character.isLetter(ch1)) { + result = Character.isLetter(ch2) ? compareOther(true) : 1; + } else { + result = Character.isDigit(ch2) ? 1 : Character.isLetter(ch2) ? -1 : compareOther(false); + } - if (result != 0) { - return result; - } - } + if (result != 0) { + return result; + } + } - return len1 - len2; + return len1 - len2; } /** @@ -108,39 +108,39 @@ * @return the integer response */ private int compareNumbers() { - int delta = 0; - int zeroes1 = 0, zeroes2 = 0; - char ch1 = (char) 0, ch2 = (char) 0; + int delta = 0; + int zeroes1 = 0, zeroes2 = 0; + char ch1 = (char) 0, ch2 = (char) 0; - // Skip leading zeroes, but keep a count of them. - while (pos1 < len1 && (ch1 = str1.charAt(pos1++)) == '0') { - zeroes1++; - } - while (pos2 < len2 && (ch2 = str2.charAt(pos2++)) == '0') { - zeroes2++; - } + // Skip leading zeroes, but keep a count of them. + while (pos1 < len1 && (ch1 = str1.charAt(pos1++)) == '0') { + zeroes1++; + } + while (pos2 < len2 && (ch2 = str2.charAt(pos2++)) == '0') { + zeroes2++; + } - // If one sequence contains more significant digits than the - // other, it's a larger number. In case they turn out to have - // equal lengths, we compare digits at each position; the first - // unequal pair determines which is the bigger number. - while (true) { - boolean noMoreDigits1 = (ch1 == 0) || !Character.isDigit(ch1); - boolean noMoreDigits2 = (ch2 == 0) || !Character.isDigit(ch2); + // If one sequence contains more significant digits than the + // other, it's a larger number. In case they turn out to have + // equal lengths, we compare digits at each position; the first + // unequal pair determines which is the bigger number. + while (true) { + boolean noMoreDigits1 = (ch1 == 0) || !Character.isDigit(ch1); + boolean noMoreDigits2 = (ch2 == 0) || !Character.isDigit(ch2); - if (noMoreDigits1 && noMoreDigits2) { - return delta != 0 ? delta : zeroes1 - zeroes2; - } else if (noMoreDigits1) { - return -1; - } else if (noMoreDigits2) { - return 1; - } else if (delta == 0 && ch1 != ch2) { - delta = ch1 - ch2; - } + if (noMoreDigits1 && noMoreDigits2) { + return delta != 0 ? delta : zeroes1 - zeroes2; + } else if (noMoreDigits1) { + return -1; + } else if (noMoreDigits2) { + return 1; + } else if (delta == 0 && ch1 != ch2) { + delta = ch1 - ch2; + } - ch1 = pos1 < len1 ? str1.charAt(pos1++) : (char) 0; - ch2 = pos2 < len2 ? str2.charAt(pos2++) : (char) 0; - } + ch1 = pos1 < len1 ? str1.charAt(pos1++) : (char) 0; + ch2 = pos2 < len2 ? str2.charAt(pos2++) : (char) 0; + } } /** @@ -149,22 +149,22 @@ * @return the integer response */ private int compareOther(boolean isLetters) { - char ch1 = str1.charAt(pos1++); - char ch2 = str2.charAt(pos2++); + char ch1 = str1.charAt(pos1++); + char ch2 = str2.charAt(pos2++); - if (ch1 == ch2) { - return 0; - } + if (ch1 == ch2) { + return 0; + } - if (isLetters) { - ch1 = Character.toUpperCase(ch1); - ch2 = Character.toUpperCase(ch2); - if (ch1 != ch2) { - ch1 = Character.toLowerCase(ch1); - ch2 = Character.toLowerCase(ch2); - } - } + if (isLetters) { + ch1 = Character.toUpperCase(ch1); + ch2 = Character.toUpperCase(ch2); + if (ch1 != ch2) { + ch1 = Character.toLowerCase(ch1); + ch2 = Character.toLowerCase(ch2); + } + } - return ch1 - ch2; + return ch1 - ch2; } } \ No newline at end of file Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/NumberTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/NumberTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/NumberTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,7 +41,7 @@ * Constructor (prevents instantiation) */ private NumberTools() { - // + // } /** @@ -51,7 +51,7 @@ * @return The value or null if zero */ public static <N extends Number> N nullIfZero(N n) { - return n == null || n.doubleValue() == 0D ? null : n; + return n == null || n.doubleValue() == 0D ? null : n; } /** @@ -63,35 +63,35 @@ * @return The double rounded according to maxFractionDigit (HALF_UP rounding mode) */ public static Double parseDouble(final String value, final Locale locale, final int maxFractionDigit) { - AssertTools.assertNotEmpty(value); - AssertTools.assertNotNull(locale); + AssertTools.assertNotEmpty(value); + AssertTools.assertNotNull(locale); - DecimalFormat fmt = (DecimalFormat) DecimalFormat.getNumberInstance(locale); - fmt.setMaximumFractionDigits(maxFractionDigit); - fmt.setRoundingMode(RoundingMode.HALF_UP); + DecimalFormat fmt = (DecimalFormat) DecimalFormat.getNumberInstance(locale); + fmt.setMaximumFractionDigits(maxFractionDigit); + fmt.setRoundingMode(RoundingMode.HALF_UP); - ParsePosition position = new ParsePosition(0); - Number nb = (Number) fmt.parseObject(value, position); + ParsePosition position = new ParsePosition(0); + Number nb = (Number) fmt.parseObject(value, position); - if (position.getIndex() != value.length()) { - // second try with '.' for decimal separator - if (value.charAt(position.getIndex()) == '.') { - DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); - symbols.setDecimalSeparator('.'); - fmt.setDecimalFormatSymbols(symbols); + if (position.getIndex() != value.length()) { + // second try with '.' for decimal separator + if (value.charAt(position.getIndex()) == '.') { + DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); + symbols.setDecimalSeparator('.'); + fmt.setDecimalFormatSymbols(symbols); - position = new ParsePosition(0); - nb = (Number) fmt.parseObject(value, position); - if (position.getIndex() != value.length()) { - throw new NumberFormatException("Cannot convert '" + value - + "' to Double. Parse failed at position " + position.getIndex() + "."); - } - } else { - throw new NumberFormatException("Cannot convert '" + value + "' to Double. Parse failed at position " - + position.getIndex() + "."); - } - } - return nb.doubleValue(); + position = new ParsePosition(0); + nb = (Number) fmt.parseObject(value, position); + if (position.getIndex() != value.length()) { + throw new NumberFormatException("Cannot convert '" + value + + "' to Double. Parse failed at position " + position.getIndex() + "."); + } + } else { + throw new NumberFormatException("Cannot convert '" + value + "' to Double. Parse failed at position " + + position.getIndex() + "."); + } + } + return nb.doubleValue(); } /** @@ -104,38 +104,38 @@ * @return The big decimal with a specified precision */ public static BigDecimal parseBigDecimal(final String value, final Locale locale, final int maxFractionDigit, - final int maxIntegerDigit) { - AssertTools.assertNotEmpty(value); - AssertTools.assertNotNull(locale); + final int maxIntegerDigit) { + AssertTools.assertNotEmpty(value); + AssertTools.assertNotNull(locale); - DecimalFormat fmt = (DecimalFormat) NumberFormat.getNumberInstance(locale); - fmt.setMaximumFractionDigits(maxFractionDigit); - fmt.setMaximumIntegerDigits(maxIntegerDigit); - fmt.setParseBigDecimal(true); + DecimalFormat fmt = (DecimalFormat) NumberFormat.getNumberInstance(locale); + fmt.setMaximumFractionDigits(maxFractionDigit); + fmt.setMaximumIntegerDigits(maxIntegerDigit); + fmt.setParseBigDecimal(true); - ParsePosition position = new ParsePosition(0); - BigDecimal bd = (BigDecimal) fmt.parseObject(value, position); + ParsePosition position = new ParsePosition(0); + BigDecimal bd = (BigDecimal) fmt.parseObject(value, position); - if (position.getIndex() != value.length()) { - // second try with '.' for decimal separator - if (value.charAt(position.getIndex()) == '.') { - DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); - symbols.setDecimalSeparator('.'); - fmt.setDecimalFormatSymbols(symbols); + if (position.getIndex() != value.length()) { + // second try with '.' for decimal separator + if (value.charAt(position.getIndex()) == '.') { + DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); + symbols.setDecimalSeparator('.'); + fmt.setDecimalFormatSymbols(symbols); - position = new ParsePosition(0); - bd = (BigDecimal) fmt.parseObject(value, position); - if (position.getIndex() != value.length()) { - throw new NumberFormatException("Cannot convert '" + value - + "' to BigDecimal. Parse failed at position " + position.getIndex() + "."); - } - } else { - throw new NumberFormatException("Cannot convert '" + value - + "' to BigDecimal. Parse failed at position " + position.getIndex() + "."); - } - } + position = new ParsePosition(0); + bd = (BigDecimal) fmt.parseObject(value, position); + if (position.getIndex() != value.length()) { + throw new NumberFormatException("Cannot convert '" + value + + "' to BigDecimal. Parse failed at position " + position.getIndex() + "."); + } + } else { + throw new NumberFormatException("Cannot convert '" + value + + "' to BigDecimal. Parse failed at position " + position.getIndex() + "."); + } + } - return bd; + return bd; } /** @@ -147,18 +147,18 @@ * @return The double rounded according to maxFractionDigit (HALF_UP rounding mode) */ public static String doubleToString(final Double value, final Locale locale, final int minFractionDigit, - final int maxFractionDigit) { - AssertTools.assertNotNull(value); - AssertTools.assertNotNull(locale); + final int maxFractionDigit) { + AssertTools.assertNotNull(value); + AssertTools.assertNotNull(locale); - NumberFormat fmt = NumberFormat.getInstance(locale); - if (fmt != null) { - fmt.setMinimumFractionDigits(minFractionDigit); - fmt.setMaximumFractionDigits(maxFractionDigit); - fmt.setRoundingMode(RoundingMode.HALF_UP); - return fmt.format(value); - } - return value.toString(); + NumberFormat fmt = NumberFormat.getInstance(locale); + if (fmt != null) { + fmt.setMinimumFractionDigits(minFractionDigit); + fmt.setMaximumFractionDigits(maxFractionDigit); + fmt.setRoundingMode(RoundingMode.HALF_UP); + return fmt.format(value); + } + return value.toString(); } /** @@ -171,18 +171,18 @@ * @return The big decimal with a specified precision */ public static String bigDecimalToString(final BigDecimal value, final Locale locale, final int minFractionDigit, - final int maxFractionDigit, final int maxIntegerDigit) { - AssertTools.assertNotNull(value); - AssertTools.assertNotNull(locale); + final int maxFractionDigit, final int maxIntegerDigit) { + AssertTools.assertNotNull(value); + AssertTools.assertNotNull(locale); - NumberFormat fmt = NumberFormat.getInstance(locale); - if (fmt != null) { - fmt.setMinimumFractionDigits(minFractionDigit); - fmt.setMaximumFractionDigits(maxFractionDigit); - fmt.setMaximumIntegerDigits(maxIntegerDigit); - fmt.setRoundingMode(RoundingMode.HALF_UP); - return fmt.format(value); - } - return value.toString(); + NumberFormat fmt = NumberFormat.getInstance(locale); + if (fmt != null) { + fmt.setMinimumFractionDigits(minFractionDigit); + fmt.setMaximumFractionDigits(maxFractionDigit); + fmt.setMaximumIntegerDigits(maxIntegerDigit); + fmt.setRoundingMode(RoundingMode.HALF_UP); + return fmt.format(value); + } + return value.toString(); } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/Pair.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/Pair.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/Pair.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,7 +45,7 @@ * Constructor */ public Pair() { - // + // } /** @@ -54,33 +54,33 @@ * @param value Second element */ public Pair(K key, V value) { - this(); - this.key = key; - this.value = value; + this(); + this.key = key; + this.value = value; } /** @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - return BeanTools.equals(this, obj, AccessType.GETTER, "key", "value"); + return BeanTools.equals(this, obj, AccessType.GETTER, "key", "value"); } /** {@inheritDoc} */ @Override public K getKey() { - return key; + return key; } /** {@inheritDoc} */ @Override public V getValue() { - return value; + return value; } /** @see java.lang.Object#hashCode() **/ @Override public int hashCode() { - return BeanTools.hashCode(this, getKey(), getValue()); + return BeanTools.hashCode(this, getKey(), getValue()); } /** @@ -88,14 +88,14 @@ * @param key key */ public void setKey(K key) { - this.key = key; + this.key = key; } /** {@inheritDoc} */ @Override public V setValue(V value) { - V oldValue = this.value; - this.value = value; - return oldValue; + V oldValue = this.value; + this.value = value; + return oldValue; } } \ No newline at end of file Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/PasswordTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/PasswordTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/PasswordTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,8 +49,8 @@ * @return Hashed password */ public static String md5(String password) { - AssertTools.assertNotNull(password); - return DigestUtils.md5Hex(password); + AssertTools.assertNotNull(password); + return DigestUtils.md5Hex(password); } /** @@ -58,8 +58,8 @@ * @return Password */ public static String random() { - return RandomStringUtils - .randomAlphanumeric((int) (Math.random() * (PASSWORD_LENGTH_MAX - PASSWORD_LENGTH_MIN) + PASSWORD_LENGTH_MIN)); + return RandomStringUtils + .randomAlphanumeric((int) (Math.random() * (PASSWORD_LENGTH_MAX - PASSWORD_LENGTH_MIN) + PASSWORD_LENGTH_MIN)); } /** @@ -68,14 +68,14 @@ * @return Hashed password */ public static String sha1(String password) { - AssertTools.assertNotNull(password); - return DigestUtils.sha1Hex(password); + AssertTools.assertNotNull(password); + return DigestUtils.sha1Hex(password); } /** * Constructor (prevents from instantiation) */ private PasswordTools() { - // + // } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTools.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTools.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTools.java 2013-02-18 07:27:17 UTC (rev 119) @@ -50,15 +50,15 @@ * @return String representing the list of couples, or null if empty */ public static <O1, O2> String couplesToString(Map<O1, O2> couples, String separatorKeysValues, - String separatorCouples) { - AssertTools.assertNotNull(couples); - AssertTools.assertNotNull(separatorKeysValues); - AssertTools.assertNotNull(separatorCouples); - StringBuilder builder = new StringBuilder(); - for (Entry<O1, O2> entry : couples.entrySet()) { - builder.append(entry.getKey() + separatorKeysValues + entry.getValue() + separatorCouples); - } - return StringUtils.stripToNull(truncate(builder, separatorCouples)); + String separatorCouples) { + AssertTools.assertNotNull(couples); + AssertTools.assertNotNull(separatorKeysValues); + AssertTools.assertNotNull(separatorCouples); + StringBuilder builder = new StringBuilder(); + for (Entry<O1, O2> entry : couples.entrySet()) { + builder.append(entry.getKey() + separatorKeysValues + entry.getValue() + separatorCouples); + } + return StringUtils.stripToNull(truncate(builder, separatorCouples)); } /** @@ -68,18 +68,18 @@ * @return List display */ public static String listToString(List<? extends Object> list, String delimiter) { - AssertTools.assertNotNull(list); - AssertTools.assertNotEmpty(delimiter); - StringBuilder builder = new StringBuilder(); - Iterator<? extends Object> itBeans = list.iterator(); - while (itBeans.hasNext()) { - Object bean = itBeans.next(); - builder.append(bean.toString()); - if (itBeans.hasNext()) { - builder.append(delimiter); - } - } - return builder.toString(); + AssertTools.assertNotNull(list); + AssertTools.assertNotEmpty(delimiter); + StringBuilder builder = new StringBuilder(); + Iterator<? extends Object> itBeans = list.iterator(); + while (itBeans.hasNext()) { + Object bean = itBeans.next(); + builder.append(bean.toString()); + if (itBeans.hasNext()) { + builder.append(delimiter); + } + } + return builder.toString(); } /** @@ -88,7 +88,7 @@ * @return String length or -1 if null */ public static int length(String string) { - return string == null ? -1 : string.length(); + return string == null ? -1 : string.length(); } /** @@ -97,15 +97,15 @@ * @return Iterator */ public static Iterator<String> lineIterator(String string) { - AssertTools.assertNotNull(string); - List<String> lines = new ArrayList<String>(); - for (LineIterator i = new LineIterator(new StringReader(string)); i.hasNext();) { - String line = StringUtils.trimToNull(i.nextLine()); - if (line != null) { - lines.add(line); - } - } - return lines.iterator(); + AssertTools.assertNotNull(string); + List<String> lines = new ArrayList<String>(); + for (LineIterator i = new LineIterator(new StringReader(string)); i.hasNext();) { + String line = StringUtils.trimToNull(i.nextLine()); + if (line != null) { + lines.add(line); + } + } + return lines.iterator(); } /** @@ -114,8 +114,8 @@ * @return Iterator */ public static Iterator<String> lineIterator(StringBuilder stringBuilder) { - AssertTools.assertNotNull(stringBuilder); - return lineIterator(stringBuilder.toString()); + AssertTools.assertNotNull(stringBuilder); + return lineIterator(stringBuilder.toString()); } /** @@ -124,7 +124,7 @@ * @return Non-accented string */ public static String replaceAccents(String string) { - return StringUtils.stripAccents(string); + return StringUtils.stripAccents(string); } /** @@ -133,7 +133,7 @@ * @return String transformed */ public static String replaceConsecutiveWhitespaces(String string) { - return StringUtils.isEmpty(string) ? string : string.replaceAll("\\p{Space}+", " "); + return StringUtils.isEmpty(string) ? string : string.replaceAll("\\p{Space}+", " "); } /** @@ -142,7 +142,7 @@ * @return String transformed */ public static String replaceConsecutiveWhitespacesByUnderscore(String string) { - return StringUtils.isEmpty(string) ? string : string.replaceAll("\\p{Space}+", "_"); + return StringUtils.isEmpty(string) ? string : string.replaceAll("\\p{Space}+", "_"); } /** @@ -151,7 +151,7 @@ * @return String transformed */ public static String replaceNonAlpha(String string) { - return StringUtils.isEmpty(string) ? string : string.replaceAll("[^\\p{Alpha}]", " "); + return StringUtils.isEmpty(string) ? string : string.replaceAll("[^\\p{Alpha}]", " "); } /** @@ -161,15 +161,15 @@ * @return Truncated string (empty if empty, null if null) */ public static String truncate(String toTruncate, String truncation) { - AssertTools.assertNotNull(truncation); - String result = toTruncate; - if (!StringUtils.isEmpty(toTruncate) - && toTruncate.length() >= truncation.length() - && truncation.equals(toTruncate.substring(toTruncate.length() - truncation.length(), toTruncate - .length()))) { - result = toTruncate.substring(0, toTruncate.length() - truncation.length()); - } - return result; + AssertTools.assertNotNull(truncation); + String result = toTruncate; + if (!StringUtils.isEmpty(toTruncate) + && toTruncate.length() >= truncation.length() + && truncation.equals(toTruncate.substring(toTruncate.length() - truncation.length(), toTruncate + .length()))) { + result = toTruncate.substring(0, toTruncate.length() - truncation.length()); + } + return result; } /** @@ -179,14 +179,14 @@ * @return Truncated string (empty if empty, null if null) */ public static String truncate(StringBuilder toTruncate, String truncation) { - return toTruncate != null ? truncate(toTruncate.toString(), truncation) : null; + return toTruncate != null ? truncate(toTruncate.toString(), truncation) : null; } /** * Constructor (prevents from instantiation) */ private StringTools() { - // + // } /** @@ -195,14 +195,14 @@ * @return Comparator */ public static <T> Comparator<T> createStringComparator() { - return new Comparator<T>() { - @Override - public int compare(T t1, T t2) { - String t1String = t1 == null ? "" : t1.toString(); - String t2String = t2 == null ? "" : t2.toString(); - - return t1String.compareTo(t2String); - } - }; + return new Comparator<T>() { + @Override + public int compare(T t1, T t2) { + String t1String = t1 == null ? "" : t1.toString(); + String t2String = t2 == null ? "" : t2.toString(); + + return t1String.compareTo(t2String); + } + }; } } Modified: trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTransformer.java =================================================================== --- trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTransformer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/main/java/nc/ird/cantharella/utils/StringTransformer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,7 +39,7 @@ * @param string String to transform */ public StringTransformer(String string) { - this.string = string; + this.string = string; } /** @@ -48,8 +48,8 @@ * @see WordUtils */ public StringTransformer capitalize() { - string = StringUtils.isEmpty(string) ? string : WordUtils.capitalize(string); - return this; + string = StringUtils.isEmpty(string) ? string : WordUtils.capitalize(string); + return this; } /** @@ -58,8 +58,8 @@ * @see WordUtils */ public StringTransformer capitalizeFully() { - string = StringUtils.isEmpty(string) ? string : WordUtils.capitalizeFully(string); - return this; + string = StringUtils.isEmpty(string) ? string : WordUtils.capitalizeFully(string); + return this; } /** @@ -68,8 +68,8 @@ * @see StringTools */ public StringTransformer replaceAccents() { - string = StringUtils.isEmpty(string) ? string : StringTools.replaceAccents(string); - return this; + string = StringUtils.isEmpty(string) ? string : StringTools.replaceAccents(string); + return this; } /** @@ -78,8 +78,8 @@ * @see StringTools */ public StringTransformer replaceConsecutiveWhitespaces() { - string = StringUtils.isEmpty(string) ? string : StringTools.replaceConsecutiveWhitespaces(string); - return this; + string = StringUtils.isEmpty(string) ? string : StringTools.replaceConsecutiveWhitespaces(string); + return this; } /** @@ -88,8 +88,8 @@ * @see StringTools */ public StringTransformer replaceConsecutiveWhitespacesByUnderscore() { - string = StringUtils.isEmpty(string) ? string : StringTools.replaceConsecutiveWhitespacesByUnderscore(string); - return this; + string = StringUtils.isEmpty(string) ? string : StringTools.replaceConsecutiveWhitespacesByUnderscore(string); + return this; } /** @@ -98,8 +98,8 @@ * @see StringTools */ public StringTransformer replaceNonAlpha() { - string = StringUtils.isEmpty(string) ? string : StringTools.replaceNonAlpha(string); - return this; + string = StringUtils.isEmpty(string) ? string : StringTools.replaceNonAlpha(string); + return this; } /** @@ -108,14 +108,14 @@ * @see String */ public StringTransformer toLowerCase() { - string = StringUtils.isEmpty(string) ? string : string.toLowerCase(); - return this; + string = StringUtils.isEmpty(string) ? string : string.toLowerCase(); + return this; } /** {@inheritDoc} */ @Override public String toString() { - return string; + return string; } /** @@ -124,8 +124,8 @@ * @see String */ public StringTransformer toUpperCase() { - string = StringUtils.isEmpty(string) ? string : string.toUpperCase(); - return this; + string = StringUtils.isEmpty(string) ? string : string.toUpperCase(); + return this; } /** @@ -134,8 +134,8 @@ * @see String */ public StringTransformer trim() { - string = StringUtils.isEmpty(string) ? string : string.trim(); - return this; + string = StringUtils.isEmpty(string) ? string : string.trim(); + return this; } /** @@ -144,7 +144,7 @@ * @see StringUtils */ public StringTransformer trimToNull() { - string = string == null ? null : StringUtils.trimToNull(string); - return this; + string = string == null ? null : StringUtils.trimToNull(string); + return this; } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/AssertToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/AssertToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/AssertToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,7 +41,7 @@ */ @Test(expected = AssertionError.class) public void assertArrayNotEmptyFalse1() { - AssertTools.assertArrayNotEmpty(new String[] { "toto", "" }); + AssertTools.assertArrayNotEmpty(new String[] { "toto", "" }); } /** @@ -49,15 +49,15 @@ */ @Test(expected = AssertionError.class) public void assertArrayNotEmptyFalse2() { - AssertTools.assertArrayNotEmpty(new String[] { null, "toto" }); + AssertTools.assertArrayNotEmpty(new String[] { null, "toto" }); } /** * assert array not empty : true */ public void assertArrayNotEmptyTrue() { - AssertTools.assertArrayNotEmpty(new String[] {}); - AssertTools.assertArrayNotEmpty(new String[] { "toto", "titi" }); + AssertTools.assertArrayNotEmpty(new String[] {}); + AssertTools.assertArrayNotEmpty(new String[] { "toto", "titi" }); } /** @@ -65,14 +65,14 @@ */ @Test(expected = AssertionError.class) public void assertArrayNotNullFalse() { - AssertTools.assertArrayNotNull(new Integer[] { Integer.valueOf(0), null, Integer.valueOf(2) }); + AssertTools.assertArrayNotNull(new Integer[] { Integer.valueOf(0), null, Integer.valueOf(2) }); } /** * assert array not null : true */ public void assertArrayNotNullTrue() { - AssertTools.assertArrayNotNull(new Integer[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }); + AssertTools.assertArrayNotNull(new Integer[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }); } /** @@ -80,7 +80,7 @@ */ @Test(expected = AssertionError.class) public void assertClassOrInterfaceFalse() { - AssertTools.assertClassOrInterface("", AssertToolsTest.class); + AssertTools.assertClassOrInterface("", AssertToolsTest.class); } /** @@ -88,7 +88,7 @@ */ @Test(expected = AssertionError.class) public void assertClassOrInterfaceFalseClass() { - AssertTools.assertClassOrInterface("", AssertToolsTest.class); + AssertTools.assertClassOrInterface("", AssertToolsTest.class); } /** @@ -96,7 +96,7 @@ */ @Test(expected = AssertionError.class) public void assertClassOrInterfaceFalseInterface() { - AssertTools.assertClassOrInterface("", Iterable.class); + AssertTools.assertClassOrInterface("", Iterable.class); } /** @@ -104,7 +104,7 @@ */ @Test(expected = AssertionError.class) public void assertClassOrInterfaceNullClass() { - AssertTools.assertClassOrInterface(this, null); + AssertTools.assertClassOrInterface(this, null); } /** @@ -112,7 +112,7 @@ */ @Test(expected = AssertionError.class) public void assertClassOrInterfaceNullObject() { - AssertTools.assertClassOrInterface(null, AssertToolsTest.class); + AssertTools.assertClassOrInterface(null, AssertToolsTest.class); } /** @@ -120,10 +120,10 @@ */ @Test public void assertClassOrInterfaceTrue() { - AssertTools.assertClassOrInterface(this, AssertToolsTest.class); - AssertTools.assertClassOrInterface(this, Object.class); - AssertTools.assertClassOrInterface(Integer.valueOf(0), Number.class); - AssertTools.assertClassOrInterface("", Serializable.class); + AssertTools.assertClassOrInterface(this, AssertToolsTest.class); + AssertTools.assertClassOrInterface(this, Object.class); + AssertTools.assertClassOrInterface(Integer.valueOf(0), Number.class); + AssertTools.assertClassOrInterface("", Serializable.class); } /** @@ -131,8 +131,8 @@ */ @Test public void assertCollectionNotNullNotNull() { - AssertTools.assertCollectionNotNull(Arrays.asList(new String[] {})); - AssertTools.assertCollectionNotNull(Arrays.asList(new String[] { "" })); + AssertTools.assertCollectionNotNull(Arrays.asList(new String[] {})); + AssertTools.assertCollectionNotNull(Arrays.asList(new String[] { "" })); } /** @@ -140,7 +140,7 @@ */ @Test(expected = AssertionError.class) public void assertCollectionNotNullNull() { - AssertTools.assertCollectionNotNull(Arrays.asList(new String[] { null })); + AssertTools.assertCollectionNotNull(Arrays.asList(new String[] { null })); } /** @@ -148,9 +148,9 @@ */ @Test public void assertEqualsEquals() { - AssertTools.assertEquals(-1, -1); - AssertTools.assertEquals(0, 0); - AssertTools.assertEquals(1, 1); + AssertTools.assertEquals(-1, -1); + AssertTools.assertEquals(0, 0); + AssertTools.assertEquals(1, 1); } /** @@ -158,7 +158,7 @@ */ @Test(expected = AssertionError.class) public void assertEqualsNotEquals() { - AssertTools.assertEquals(-1, 0); + AssertTools.assertEquals(-1, 0); } /** @@ -166,7 +166,7 @@ */ @Test public void assertGreateOrEqualsEquals() { - AssertTools.assertGreaterOrEquals(0, 0); + AssertTools.assertGreaterOrEquals(0, 0); } /** @@ -174,7 +174,7 @@ */ @Test public void assertGreateOrEqualsGreater() { - AssertTools.assertGreaterOrEquals(1, 0); + AssertTools.assertGreaterOrEquals(1, 0); } /** @@ -182,7 +182,7 @@ */ @Test(expected = AssertionError.class) public void assertGreateOrEqualsLower() { - AssertTools.assertGreaterOrEquals(-1, 0); + AssertTools.assertGreaterOrEquals(-1, 0); } /** @@ -190,7 +190,7 @@ */ @Test(expected = AssertionError.class) public void assertInArrayFalse() { - AssertTools.assertIn("b", "a", "c"); + AssertTools.assertIn("b", "a", "c"); } /** @@ -198,7 +198,7 @@ */ @Test(expected = AssertionError.class) public void assertInCollectionFalse() { - AssertTools.assertIn("b", Arrays.asList(new String[] { "a", "c" })); + AssertTools.assertIn("b", Arrays.asList(new String[] { "a", "c" })); } /** @@ -206,10 +206,10 @@ */ @Test public void assertInTrue() { - AssertTools.assertIn("b", "b"); - AssertTools.assertIn("b", "a", "b"); - AssertTools.assertIn("b", Arrays.asList(new String[] { "b" })); - AssertTools.assertIn("b", Arrays.asList(new String[] { "a", "b" })); + AssertTools.assertIn("b", "b"); + AssertTools.assertIn("b", "a", "b"); + AssertTools.assertIn("b", Arrays.asList(new String[] { "b" })); + AssertTools.assertIn("b", Arrays.asList(new String[] { "a", "b" })); } /** @@ -217,7 +217,7 @@ */ @Test(expected = AssertionError.class) public void assertLowerEquals() { - AssertTools.assertLower(0, 0); + AssertTools.assertLower(0, 0); } /** @@ -225,7 +225,7 @@ */ @Test public void assertLowerLower() { - AssertTools.assertLower(-1, 0); + AssertTools.assertLower(-1, 0); } /** @@ -233,8 +233,8 @@ */ @Test public void assertLowerOrEqualsLowerOrEquals() { - AssertTools.assertLowerOrEquals(-1, 0); - AssertTools.assertLowerOrEquals(0, 0); + AssertTools.assertLowerOrEquals(-1, 0); + AssertTools.assertLowerOrEquals(0, 0); } /** @@ -242,7 +242,7 @@ */ @Test(expected = AssertionError.class) public void assertLowerOrEqualsUpper() { - AssertTools.assertLower(1, 0); + AssertTools.assertLower(1, 0); } /** @@ -250,7 +250,7 @@ */ @Test(expected = AssertionError.class) public void assertLowerUpper() { - AssertTools.assertLower(1, 0); + AssertTools.assertLower(1, 0); } /** @@ -258,7 +258,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyArrayEmpty() { - AssertTools.assertNotEmpty(new Integer[] {}); + AssertTools.assertNotEmpty(new Integer[] {}); } /** @@ -266,7 +266,7 @@ */ @Test public void assertNotEmptyArrayNotEmpty() { - AssertTools.assertNotEmpty(new String[] { "toto" }); + AssertTools.assertNotEmpty(new String[] { "toto" }); } /** @@ -274,7 +274,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyArrayNull() { - AssertTools.assertNotEmpty((Integer[]) null); + AssertTools.assertNotEmpty((Integer[]) null); } /** @@ -282,7 +282,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyCollectionEmpty() { - AssertTools.assertNotEmpty(new ArrayList<String>()); + AssertTools.assertNotEmpty(new ArrayList<String>()); } /** @@ -290,7 +290,7 @@ */ @Test public void assertNotEmptyCollectionNotEmpty() { - AssertTools.assertNotEmpty(Arrays.asList("toto")); + AssertTools.assertNotEmpty(Arrays.asList("toto")); } /** @@ -298,7 +298,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyCollectionNull() { - AssertTools.assertNotEmpty((Collection<?>) null); + AssertTools.assertNotEmpty((Collection<?>) null); } /** @@ -306,7 +306,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyStringEmpty() { - AssertTools.assertNotEmpty(""); + AssertTools.assertNotEmpty(""); } /** @@ -314,7 +314,7 @@ */ @Test public void assertNotEmptyStringNotEmpty() { - AssertTools.assertNotEmpty("toto"); + AssertTools.assertNotEmpty("toto"); } /** @@ -322,7 +322,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEmptyStringNull() { - AssertTools.assertNotEmpty((String) null); + AssertTools.assertNotEmpty((String) null); } /** @@ -330,7 +330,7 @@ */ @Test(expected = AssertionError.class) public void assertNotEqualsEquals() { - AssertTools.assertNotEquals(0, 0); + AssertTools.assertNotEquals(0, 0); } /** @@ -338,8 +338,8 @@ */ @Test public void assertNotEqualsNotEquals() { - AssertTools.assertNotEquals(1, 0); - AssertTools.assertNotEquals(-1, 0); + AssertTools.assertNotEquals(1, 0); + AssertTools.assertNotEquals(-1, 0); } /** @@ -347,7 +347,7 @@ */ @Test(expected = AssertionError.class) public void assertNotNegativeNegative() { - AssertTools.assertNotNegative(-1); + AssertTools.assertNotNegative(-1); } /** @@ -355,8 +355,8 @@ */ @Test public void assertNotNegativeNotNegative() { - AssertTools.assertNotNegative(1); - AssertTools.assertNotNegative(0); + AssertTools.assertNotNegative(1); + AssertTools.assertNotNegative(0); } /** @@ -364,7 +364,7 @@ */ @Test public void assertNotNullNotNull() { - AssertTools.assertNotNull(""); + AssertTools.assertNotNull(""); } /** @@ -372,7 +372,7 @@ */ @Test(expected = AssertionError.class) public void assertNotNullNull() { - AssertTools.assertNotNull(null); + AssertTools.assertNotNull(null); } /** @@ -380,7 +380,7 @@ */ @Test(expected = AssertionError.class) public void assertPositiveNegative() { - AssertTools.assertPositive(-1); + AssertTools.assertPositive(-1); } /** @@ -388,7 +388,7 @@ */ @Test public void assertPositivePositive() { - AssertTools.assertPositive(1); + AssertTools.assertPositive(1); } /** @@ -396,6 +396,6 @@ */ @Test(expected = AssertionError.class) public void assertPositiveZero() { - AssertTools.assertPositive(0); + AssertTools.assertPositive(0); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanLookupTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanLookupTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanLookupTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -40,62 +40,62 @@ */ public final class Bean { - /** boolean */ - public boolean bool; + /** boolean */ + public boolean bool; - /** integer */ - public Integer integer; + /** integer */ + public Integer integer; - /** string */ - public String string; + /** string */ + public String string; - /** - * integer getter - * @return integer - */ - public Integer getInteger() { - return integer; - } + /** + * integer getter + * @return integer + */ + public Integer getInteger() { + return integer; + } - /** - * string getter - * @return string - */ - public String getString() { - return string; - } + /** + * string getter + * @return string + */ + public String getString() { + return string; + } - /** - * bool getter - * @return bool - */ - public boolean isBool() { - return bool; - } + /** + * bool getter + * @return bool + */ + public boolean isBool() { + return bool; + } - /** - * bool setter - * @param bool bool - */ - public void setBool(boolean bool) { - this.bool = bool; - } + /** + * bool setter + * @param bool bool + */ + public void setBool(boolean bool) { + this.bool = bool; + } - /** - * integer setter - * @param integer integer - */ - public void setInteger(Integer integer) { - this.integer = integer; - } + /** + * integer setter + * @param integer integer + */ + public void setInteger(Integer integer) { + this.integer = integer; + } - /** - * string setter - * @param string string - */ - public void setString(String string) { - this.string = string; - } + /** + * string setter + * @param string string + */ + public void setString(String string) { + this.string = string; + } } @@ -104,28 +104,28 @@ */ @Test public void lookup() { - Bean bean = new Bean(); - BeanLookup lookupGetter = new BeanLookup(bean, AccessType.GETTER); - BeanLookup lookupField = new BeanLookup(bean, AccessType.FIELD); - Assert.assertNull(lookupGetter.lookup("Toto")); - Assert.assertNull(lookupField.lookup("Toto")); - Assert.assertNull(lookupGetter.lookup("integer")); - Assert.assertNull(lookupField.lookup("integer")); - Assert.assertNull(lookupGetter.lookup("string")); - Assert.assertNull(lookupField.lookup("string")); - bean.setInteger(0); - bean.setString(""); - bean.setBool(true); - Assert.assertNull(lookupGetter.lookup("Toto")); - Assert.assertNull(lookupField.lookup("Toto")); - Assert.assertEquals(bean.getInteger().toString(), lookupGetter.lookup("integer")); - Assert.assertEquals(bean.integer.toString(), lookupField.lookup("integer")); - Assert.assertEquals(bean.getString(), lookupGetter.lookup("string")); - Assert.assertEquals(bean.string, lookupField.lookup("string")); - Assert.assertEquals(String.valueOf(bean.isBool()), lookupGetter.lookup("bool")); - Assert.assertEquals(String.valueOf(bean.bool), lookupField.lookup("bool")); - bean.setBool(false); - Assert.assertEquals(String.valueOf(bean.isBool()), lookupGetter.lookup("bool")); - Assert.assertEquals(String.valueOf(bean.bool), lookupField.lookup("bool")); + Bean bean = new Bean(); + BeanLookup lookupGetter = new BeanLookup(bean, AccessType.GETTER); + BeanLookup lookupField = new BeanLookup(bean, AccessType.FIELD); + Assert.assertNull(lookupGetter.lookup("Toto")); + Assert.assertNull(lookupField.lookup("Toto")); + Assert.assertNull(lookupGetter.lookup("integer")); + Assert.assertNull(lookupField.lookup("integer")); + Assert.assertNull(lookupGetter.lookup("string")); + Assert.assertNull(lookupField.lookup("string")); + bean.setInteger(0); + bean.setString(""); + bean.setBool(true); + Assert.assertNull(lookupGetter.lookup("Toto")); + Assert.assertNull(lookupField.lookup("Toto")); + Assert.assertEquals(bean.getInteger().toString(), lookupGetter.lookup("integer")); + Assert.assertEquals(bean.integer.toString(), lookupField.lookup("integer")); + Assert.assertEquals(bean.getString(), lookupGetter.lookup("string")); + Assert.assertEquals(bean.string, lookupField.lookup("string")); + Assert.assertEquals(String.valueOf(bean.isBool()), lookupGetter.lookup("bool")); + Assert.assertEquals(String.valueOf(bean.bool), lookupField.lookup("bool")); + bean.setBool(false); + Assert.assertEquals(String.valueOf(bean.isBool()), lookupGetter.lookup("bool")); + Assert.assertEquals(String.valueOf(bean.bool), lookupField.lookup("bool")); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/BeanToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,50 +45,50 @@ */ public class Bean { - /** integer */ - @Resource - public Integer integer; + /** integer */ + @Resource + public Integer integer; - /** string */ - public String string; + /** string */ + public String string; - /** - * integer getter - * @return integer - */ - public Integer getInteger() { - return integer; - } + /** + * integer getter + * @return integer + */ + public Integer getInteger() { + return integer; + } - /** - * string getter - * @return string - */ - public String getString() { - return string; - } + /** + * string getter + * @return string + */ + public String getString() { + return string; + } - /** {@inheritDoc} */ - @Override - public int hashCode() { - return BeanTools.hashCode(this, integer, string); - } + /** {@inheritDoc} */ + @Override + public int hashCode() { + return BeanTools.hashCode(this, integer, string); + } - /** - * integer setter - * @param integer integer - */ - public void setInteger(Integer integer) { - this.integer = integer; - } + /** + * integer setter + * @param integer integer + */ + public void setInteger(Integer integer) { + this.integer = integer; + } - /** - * string setter - * @param string string - */ - public void setString(String string) { - this.string = string; - } + /** + * string setter + * @param string string + */ + public void setString(String string) { + this.string = string; + } } /** @@ -96,25 +96,25 @@ * @author acheype */ public final class SubBean extends Bean { - /** integer */ - @Resource - public Integer subInteger; + /** integer */ + @Resource + public Integer subInteger; - /** - * subInteger getter - * @return subInteger - */ - public Integer getSubInteger() { - return subInteger; - } + /** + * subInteger getter + * @return subInteger + */ + public Integer getSubInteger() { + return subInteger; + } - /** - * subInteger setter - * @param subInteger subInteger - */ - public void setSubInteger(Integer subInteger) { - this.subInteger = subInteger; - } + /** + * subInteger setter + * @param subInteger subInteger + */ + public void setSubInteger(Integer subInteger) { + this.subInteger = subInteger; + } } /** @@ -123,140 +123,140 @@ */ public final class SubBean2 extends Bean { - /** {@inheritDoc} */ - @Override - public int hashCode() { - return 1; - } + /** {@inheritDoc} */ + @Override + public int hashCode() { + return 1; + } } /** Bean test class 1 */ public class Bean1 { - /** name test 1 */ - private String name1; + /** name test 1 */ + private String name1; - /** bean test class 2 **/ - private Bean2 bean2; + /** bean test class 2 **/ + private Bean2 bean2; - /** id */ - public int id; + /** id */ + public int id; - /** - * name1 getter - * @return name1 - */ - public String getName1() { - return name1; - } + /** + * name1 getter + * @return name1 + */ + public String getName1() { + return name1; + } - /** - * name1 setter - * @param name1 name1 - */ - public void setName1(String name1) { - this.name1 = name1; - } + /** + * name1 setter + * @param name1 name1 + */ + public void setName1(String name1) { + this.name1 = name1; + } - /** - * bean2 getter - * @return bean2 - */ - public Bean2 getBean2() { - return bean2; - } + /** + * bean2 getter + * @return bean2 + */ + public Bean2 getBean2() { + return bean2; + } - /** - * bean2 setter - * @param bean2 bean2 - */ - public void setBean2(Bean2 bean2) { - this.bean2 = bean2; - } + /** + * bean2 setter + * @param bean2 bean2 + */ + public void setBean2(Bean2 bean2) { + this.bean2 = bean2; + } - /** - * id getter - * @return id - */ - public int getId() { - return id; - } + /** + * id getter + * @return id + */ + public int getId() { + return id; + } - /** - * id setter - * @param id id - */ - public void setId(int id) { - this.id = id; - } + /** + * id setter + * @param id id + */ + public void setId(int id) { + this.id = id; + } } /** Bean test class 2 **/ public class Bean2 { - /** name test2 */ - public String name2; + /** name test2 */ + public String name2; - /** - * name2 getter - * @return name2 - */ - public String getName2() { - return name2; - } + /** + * name2 getter + * @return name2 + */ + public String getName2() { + return name2; + } - /** - * name2 setter - * @param name2 name2 - */ - public void setName2(String name2) { - this.name2 = name2; - } + /** + * name2 setter + * @param name2 name2 + */ + public void setName2(String name2) { + this.name2 = name2; + } } /** Bean test class 2 **/ public class Bean3 extends Bean1 { - /** name test2 */ - public String name2; + /** name test2 */ + public String name2; - /** id **/ - public int id; + /** id **/ + public int id; - /** - * id getter - * @return id - */ - @Override - public int getId() { - return this.id; - } + /** + * id getter + * @return id + */ + @Override + public int getId() { + return this.id; + } - /** - * id setter - * @param id id - */ - @Override - public void setId(int id) { - this.id = id; - } + /** + * id setter + * @param id id + */ + @Override + public void setId(int id) { + this.id = id; + } - /** - * name2 getter - * @return name2 - */ - public String getName2() { - return name2; - } + /** + * name2 getter + * @return name2 + */ + public String getName2() { + return name2; + } - /** - * name2 setter - * @param name2 name2 - */ - public void setName2(String name2) { - this.name2 = name2; - } + /** + * name2 setter + * @param name2 name2 + */ + public void setName2(String name2) { + this.name2 = name2; + } } /** @@ -267,93 +267,93 @@ @Test public void beanEquals() throws SecurityException, NoSuchFieldException { - Field fi = Bean.class.getField("integer"); - Field fs = Bean.class.getField("string"); + Field fi = Bean.class.getField("integer"); + Field fs = Bean.class.getField("string"); - Bean bean = new Bean(); - Bean1 bean1 = new Bean1(); - bean1.setId(455); - Bean3 bean3 = new Bean3(); - bean3.setId(455); - // Field fx = Bean1.class.getField("id"); - // Field fz = Bean3.class.getField("id"); + Bean bean = new Bean(); + Bean1 bean1 = new Bean1(); + bean1.setId(455); + Bean3 bean3 = new Bean3(); + bean3.setId(455); + // Field fx = Bean1.class.getField("id"); + // Field fz = Bean3.class.getField("id"); - Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean, fi, fs)); - Assert.assertFalse(BeanTools.equals(bean, null, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, null, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, null, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean, null, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, null, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, null, fi, fs)); - Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean, fi, fs)); - Bean bean12 = new Bean(); + Bean bean12 = new Bean(); - Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean12, bean, fi, fs)); - bean.setInteger(0); - bean.setString(""); + bean.setInteger(0); + bean.setString(""); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); - bean12.setInteger(0); - bean12.setString(""); + bean12.setInteger(0); + bean12.setString(""); - Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertTrue(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertTrue(BeanTools.equals(bean12, bean, fi, fs)); - bean12.setInteger(1); + bean12.setInteger(1); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); - bean12.setString("Toto"); + bean12.setString("Toto"); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); - bean12.setInteger(0); + bean12.setInteger(0); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean, bean12, fi, fs)); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); - Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.GETTER, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, AccessType.FIELD, "integer", "string")); + Assert.assertFalse(BeanTools.equals(bean12, bean, fi, fs)); - Assert.assertTrue(BeanTools.equals(bean1, bean3, AccessType.GETTER, "id")); - Assert.assertTrue(BeanTools.equals(bean1, bean3, AccessType.FIELD, "id")); + Assert.assertTrue(BeanTools.equals(bean1, bean3, AccessType.GETTER, "id")); + Assert.assertTrue(BeanTools.equals(bean1, bean3, AccessType.FIELD, "id")); } /** @@ -363,29 +363,29 @@ */ @Test public void beanHashCode() throws SecurityException, NoSuchFieldException { - Field fi = Bean.class.getField("integer"); - Field fs = Bean.class.getField("string"); - Bean bean1 = new Bean(); - Bean bean2 = new Bean(); - Assert.assertTrue(bean1.hashCode() == bean2.hashCode()); - Assert.assertTrue(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); - bean1.setInteger(0); - bean1.setString(""); - Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); - Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); - bean2.setInteger(0); - bean2.setString(""); - Assert.assertTrue(bean1.hashCode() == bean2.hashCode()); - Assert.assertTrue(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); - bean2.setInteger(1); - Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); - Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); - bean2.setString("Toto"); - Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); - Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); - bean2.setInteger(0); - Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); - Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + Field fi = Bean.class.getField("integer"); + Field fs = Bean.class.getField("string"); + Bean bean1 = new Bean(); + Bean bean2 = new Bean(); + Assert.assertTrue(bean1.hashCode() == bean2.hashCode()); + Assert.assertTrue(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + bean1.setInteger(0); + bean1.setString(""); + Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); + Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + bean2.setInteger(0); + bean2.setString(""); + Assert.assertTrue(bean1.hashCode() == bean2.hashCode()); + Assert.assertTrue(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + bean2.setInteger(1); + Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); + Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + bean2.setString("Toto"); + Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); + Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); + bean2.setInteger(0); + Assert.assertFalse(bean1.hashCode() == bean2.hashCode()); + Assert.assertFalse(BeanTools.hashCode(bean1, fi, fs) == BeanTools.hashCode(bean2, fi, fs)); } /** @@ -393,26 +393,26 @@ */ @Test public void beanToString() { - SubBean bean = new SubBean(); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: <null>\n- string: <null>\n- subInteger: <null>", - BeanTools.toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: <null>\n- string: <null>\n- subInteger: <null>", - BeanTools.toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); - bean.setInteger(0); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: <null>\n- subInteger: <null>", - BeanTools.toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: <null>\n- subInteger: <null>", - BeanTools.toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); - bean.setString(""); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: \n- subInteger: <null>", BeanTools - .toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: \n- subInteger: <null>", BeanTools - .toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); - bean.setString("Toto"); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: Toto\n- subInteger: <null>", BeanTools - .toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); - Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: Toto\n- subInteger: <null>", BeanTools - .toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); + SubBean bean = new SubBean(); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: <null>\n- string: <null>\n- subInteger: <null>", + BeanTools.toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: <null>\n- string: <null>\n- subInteger: <null>", + BeanTools.toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); + bean.setInteger(0); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: <null>\n- subInteger: <null>", + BeanTools.toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: <null>\n- subInteger: <null>", + BeanTools.toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); + bean.setString(""); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: \n- subInteger: <null>", BeanTools + .toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: \n- subInteger: <null>", BeanTools + .toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); + bean.setString("Toto"); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: Toto\n- subInteger: <null>", BeanTools + .toString(bean, AccessType.GETTER, "integer", "string", "subInteger")); + Assert.assertEquals(SubBean.class.getName() + "\n- integer: 0\n- string: Toto\n- subInteger: <null>", BeanTools + .toString(bean, AccessType.FIELD, "integer", "string", "subInteger")); } /** @@ -424,7 +424,7 @@ @SuppressWarnings("unchecked") @Test(expected = NoSuchFieldException.class) public void getAnnotatedPublicFieldKO() throws SecurityException, NullPointerException, NoSuchFieldException { - BeanTools.getAnnotatedPublicField(new Bean(), Deprecated.class); + BeanTools.getAnnotatedPublicField(new Bean(), Deprecated.class); } /** @@ -436,8 +436,8 @@ @SuppressWarnings("unchecked") @Test public void getAnnotatedPublicFieldOK() throws SecurityException, NullPointerException, NoSuchFieldException { - Field f = Bean.class.getField("integer"); - Assert.assertEquals(f, BeanTools.getAnnotatedPublicField(new Bean(), Resource.class)); + Field f = Bean.class.getField("integer"); + Assert.assertEquals(f, BeanTools.getAnnotatedPublicField(new Bean(), Resource.class)); } /** @@ -448,9 +448,9 @@ */ @Test public void isAnnotationOnProperty() throws SecurityException, NullPointerException, NoSuchFieldException { - Assert.assertTrue(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "subInteger")); - Assert.assertTrue(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "integer")); - Assert.assertFalse(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "string")); + Assert.assertTrue(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "subInteger")); + Assert.assertTrue(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "integer")); + Assert.assertFalse(BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "string")); } /** @@ -461,7 +461,7 @@ */ @Test(expected = NoSuchFieldException.class) public void isAnnotationOnPropertyError() throws SecurityException, NullPointerException, NoSuchFieldException { - BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "toto"); + BeanTools.isAnnotationOnProperty(SubBean.class, Resource.class, "toto"); } /** @@ -469,16 +469,16 @@ */ @Test(expected = IllegalArgumentException.class) public void getValueFromPath() { - Bean1 b1 = new Bean1(); - Bean2 b2 = new Bean2(); + Bean1 b1 = new Bean1(); + Bean2 b2 = new Bean2(); - b1.setName1("name1"); - b2.setName2("name2"); - b1.setBean2(b2); + b1.setName1("name1"); + b2.setName2("name2"); + b1.setBean2(b2); - Assert.assertSame(b1.getName1(), BeanTools.getValueFromPath(b1, AccessType.GETTER, "name1")); - Assert.assertSame(b1.getBean2().getName2(), BeanTools.getValueFromPath(b1, AccessType.GETTER, "bean2.name2")); - BeanTools.getValueFromPath(b1, AccessType.FIELD, "bean2.nameX"); + Assert.assertSame(b1.getName1(), BeanTools.getValueFromPath(b1, AccessType.GETTER, "name1")); + Assert.assertSame(b1.getBean2().getName2(), BeanTools.getValueFromPath(b1, AccessType.GETTER, "bean2.name2")); + BeanTools.getValueFromPath(b1, AccessType.FIELD, "bean2.nameX"); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CaptchaToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CaptchaToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CaptchaToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,14 +37,14 @@ */ @Test public void random() { - String captcha1 = CaptchaTools.random(); - Assert.assertNotNull(captcha1); - Assert.assertTrue(captcha1.length() >= CaptchaTools.CAPTCHA_LENGTH_MIN); - Assert.assertTrue(captcha1.length() <= CaptchaTools.CAPTCHA_LENGTH_MAX); - String captcha2 = CaptchaTools.random(); - Assert.assertNotNull(captcha2); - Assert.assertTrue(captcha2.length() >= CaptchaTools.CAPTCHA_LENGTH_MIN); - Assert.assertTrue(captcha2.length() <= CaptchaTools.CAPTCHA_LENGTH_MAX); - Assert.assertTrue(!captcha1.equals(captcha2)); + String captcha1 = CaptchaTools.random(); + Assert.assertNotNull(captcha1); + Assert.assertTrue(captcha1.length() >= CaptchaTools.CAPTCHA_LENGTH_MIN); + Assert.assertTrue(captcha1.length() <= CaptchaTools.CAPTCHA_LENGTH_MAX); + String captcha2 = CaptchaTools.random(); + Assert.assertNotNull(captcha2); + Assert.assertTrue(captcha2.length() >= CaptchaTools.CAPTCHA_LENGTH_MIN); + Assert.assertTrue(captcha2.length() <= CaptchaTools.CAPTCHA_LENGTH_MAX); + Assert.assertTrue(!captcha1.equals(captcha2)); } } \ No newline at end of file Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CollectionToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CollectionToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CollectionToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,36 +54,36 @@ * Constructor */ public CollectionToolsTest() { - init(); + init(); } /** * initialisation of tests */ private void init() { - BeanToolsTest beanTest = new BeanToolsTest(); + BeanToolsTest beanTest = new BeanToolsTest(); - Bean1 b1 = beanTest.new Bean1(); - Bean2 b12 = beanTest.new Bean2(); - b12.setName2("name12"); - b1.setName1("name"); - b1.setBean2(b12); + Bean1 b1 = beanTest.new Bean1(); + Bean2 b12 = beanTest.new Bean2(); + b12.setName2("name12"); + b1.setName1("name"); + b1.setBean2(b12); - Bean1 b2 = beanTest.new Bean1(); - Bean2 b22 = beanTest.new Bean2(); - b22.setName2("name22"); - b2.setName1("name"); - b2.setBean2(b22); + Bean1 b2 = beanTest.new Bean1(); + Bean2 b22 = beanTest.new Bean2(); + b22.setName2("name22"); + b2.setName1("name"); + b2.setBean2(b22); - Bean1 b3 = beanTest.new Bean1(); - Bean2 b32 = beanTest.new Bean2(); - b32.setName2(null); - b3.setName1("name"); - b3.setBean2(b32); + Bean1 b3 = beanTest.new Bean1(); + Bean2 b32 = beanTest.new Bean2(); + b32.setName2(null); + b3.setName1("name"); + b3.setBean2(b32); - beansCol.add(b1); - beansCol.add(b2); - beansCol.add(b3); + beansCol.add(b1); + beansCol.add(b2); + beansCol.add(b3); } /** @@ -91,21 +91,21 @@ */ @Test public void containsOnlyValue() { - Collection<String> col1 = new ArrayList<String>(Arrays.asList(new String[] { "fff", "fff" })); - Collection<String> col2 = new ArrayList<String>(); - Collection<String> col3 = new ArrayList<String>(Arrays.asList(new String[] { "ab", "fff" })); - Collection<String> col4 = new ArrayList<String>(Arrays.asList(new String[] { null, null })); - Collection<String> col5 = new ArrayList<String>(Arrays.asList(new String[] { null, "fff" })); - Collection<String> col6 = new ArrayList<String>(Arrays.asList(new String[] { "fff" })); - Collection<Integer> col7 = new ArrayList<Integer>(Arrays.asList(new Integer[] { 5, 5, 5, 5, 5 })); + Collection<String> col1 = new ArrayList<String>(Arrays.asList(new String[] { "fff", "fff" })); + Collection<String> col2 = new ArrayList<String>(); + Collection<String> col3 = new ArrayList<String>(Arrays.asList(new String[] { "ab", "fff" })); + Collection<String> col4 = new ArrayList<String>(Arrays.asList(new String[] { null, null })); + Collection<String> col5 = new ArrayList<String>(Arrays.asList(new String[] { null, "fff" })); + Collection<String> col6 = new ArrayList<String>(Arrays.asList(new String[] { "fff" })); + Collection<Integer> col7 = new ArrayList<Integer>(Arrays.asList(new Integer[] { 5, 5, 5, 5, 5 })); - Assert.assertTrue(CollectionTools.containsOnlySameValue(col1, "fff")); - Assert.assertFalse(CollectionTools.containsOnlySameValue(col2, "")); - Assert.assertFalse(CollectionTools.containsOnlySameValue(col3, "fff")); - Assert.assertTrue(CollectionTools.containsOnlySameValue(col4, null)); - Assert.assertFalse(CollectionTools.containsOnlySameValue(col5, null)); - Assert.assertTrue(CollectionTools.containsOnlySameValue(col6, "fff")); - Assert.assertTrue(CollectionTools.containsOnlySameValue(col7, 5)); + Assert.assertTrue(CollectionTools.containsOnlySameValue(col1, "fff")); + Assert.assertFalse(CollectionTools.containsOnlySameValue(col2, "")); + Assert.assertFalse(CollectionTools.containsOnlySameValue(col3, "fff")); + Assert.assertTrue(CollectionTools.containsOnlySameValue(col4, null)); + Assert.assertFalse(CollectionTools.containsOnlySameValue(col5, null)); + Assert.assertTrue(CollectionTools.containsOnlySameValue(col6, "fff")); + Assert.assertTrue(CollectionTools.containsOnlySameValue(col7, 5)); } /** @@ -113,31 +113,31 @@ */ @Test public void intersect() { - Set<Integer> s1 = new HashSet<Integer>(); - Set<Integer> s2 = new HashSet<Integer>(); - Assert.assertTrue(CollectionTools.intersect(null, null).isEmpty()); - Assert.assertTrue(CollectionTools.intersect(s1, null).isEmpty()); - Assert.assertTrue(CollectionTools.intersect(null, s2).isEmpty()); - Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); - s1.add(Integer.valueOf(0)); - Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); - s2.add(Integer.valueOf(1)); - Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); - s1.add(Integer.valueOf(2)); - s2.add(Integer.valueOf(2)); - Set<Integer> intersect = CollectionTools.intersect(s1, s2); - Assert.assertEquals(1, intersect.size()); - Assert.assertTrue(intersect.contains(Integer.valueOf(2))); - s1.add(Integer.valueOf(3)); - s2.add(Integer.valueOf(3)); - intersect = CollectionTools.intersect(s1, s2); - Assert.assertEquals(2, intersect.size()); - Assert.assertTrue(intersect.contains(Integer.valueOf(2))); - Assert.assertTrue(intersect.contains(Integer.valueOf(3))); - intersect = CollectionTools.intersect(s2, s1); - Assert.assertEquals(2, intersect.size()); - Assert.assertTrue(intersect.contains(Integer.valueOf(2))); - Assert.assertTrue(intersect.contains(Integer.valueOf(3))); + Set<Integer> s1 = new HashSet<Integer>(); + Set<Integer> s2 = new HashSet<Integer>(); + Assert.assertTrue(CollectionTools.intersect(null, null).isEmpty()); + Assert.assertTrue(CollectionTools.intersect(s1, null).isEmpty()); + Assert.assertTrue(CollectionTools.intersect(null, s2).isEmpty()); + Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); + s1.add(Integer.valueOf(0)); + Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); + s2.add(Integer.valueOf(1)); + Assert.assertTrue(CollectionTools.intersect(s1, s2).isEmpty()); + s1.add(Integer.valueOf(2)); + s2.add(Integer.valueOf(2)); + Set<Integer> intersect = CollectionTools.intersect(s1, s2); + Assert.assertEquals(1, intersect.size()); + Assert.assertTrue(intersect.contains(Integer.valueOf(2))); + s1.add(Integer.valueOf(3)); + s2.add(Integer.valueOf(3)); + intersect = CollectionTools.intersect(s1, s2); + Assert.assertEquals(2, intersect.size()); + Assert.assertTrue(intersect.contains(Integer.valueOf(2))); + Assert.assertTrue(intersect.contains(Integer.valueOf(3))); + intersect = CollectionTools.intersect(s2, s1); + Assert.assertEquals(2, intersect.size()); + Assert.assertTrue(intersect.contains(Integer.valueOf(2))); + Assert.assertTrue(intersect.contains(Integer.valueOf(3))); } /** @@ -145,19 +145,19 @@ */ @Test public void setter() { - Collection<Integer> toWrite = new ArrayList<Integer>(); - Collection<Integer> toRead = null; - toWrite.add(0); - CollectionTools.setter(toWrite, toRead); - Assert.assertTrue(toWrite.isEmpty()); - toWrite.add(0); - toRead = new ArrayList<Integer>(); - CollectionTools.setter(toWrite, toRead); - Assert.assertTrue(toWrite.isEmpty()); - toWrite.add(0); - toRead.add(1); - CollectionTools.setter(toWrite, toRead); - Assert.assertArrayEquals(toRead.toArray(), toWrite.toArray()); + Collection<Integer> toWrite = new ArrayList<Integer>(); + Collection<Integer> toRead = null; + toWrite.add(0); + CollectionTools.setter(toWrite, toRead); + Assert.assertTrue(toWrite.isEmpty()); + toWrite.add(0); + toRead = new ArrayList<Integer>(); + CollectionTools.setter(toWrite, toRead); + Assert.assertTrue(toWrite.isEmpty()); + toWrite.add(0); + toRead.add(1); + CollectionTools.setter(toWrite, toRead); + Assert.assertArrayEquals(toRead.toArray(), toWrite.toArray()); } /** @@ -165,15 +165,15 @@ */ @Test public void toStringComparator() { - List<String> list = new ArrayList<String>(); - list.add("t"); - list.add(null); - list.add(""); - list.add("z"); - list.add("b"); - list.add(" "); - Collections.sort(list, StringTools.createStringComparator()); - Assert.assertArrayEquals(list.toArray(new String[0]), new String[] { null, "", " ", "b", "t", "z" }); + List<String> list = new ArrayList<String>(); + list.add("t"); + list.add(null); + list.add(""); + list.add("z"); + list.add("b"); + list.add(" "); + Collections.sort(list, StringTools.createStringComparator()); + Assert.assertArrayEquals(list.toArray(new String[0]), new String[] { null, "", " ", "b", "t", "z" }); } /** @@ -181,10 +181,10 @@ */ @Test public void containsFieldWithValue() { - Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "name1", AccessType.GETTER, "name")); - Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12")); - Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name22")); - Assert.assertFalse(CollectionTools.containsWithValue(beansCol, "name1", AccessType.GETTER, "XXX")); + Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "name1", AccessType.GETTER, "name")); + Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12")); + Assert.assertTrue(CollectionTools.containsWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name22")); + Assert.assertFalse(CollectionTools.containsWithValue(beansCol, "name1", AccessType.GETTER, "XXX")); } /** @@ -192,10 +192,10 @@ */ @Test public void countFieldWithValue() { - Assert.assertSame(CollectionTools.countWithValue(beansCol, "name1", AccessType.GETTER, "name"), 3); - Assert.assertSame(CollectionTools.countWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12"), 1); - Assert.assertSame(CollectionTools.countWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name22"), 1); - Assert.assertSame(CollectionTools.countWithValue(beansCol, "name1", AccessType.GETTER, "XXX"), 0); + Assert.assertSame(CollectionTools.countWithValue(beansCol, "name1", AccessType.GETTER, "name"), 3); + Assert.assertSame(CollectionTools.countWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12"), 1); + Assert.assertSame(CollectionTools.countWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name22"), 1); + Assert.assertSame(CollectionTools.countWithValue(beansCol, "name1", AccessType.GETTER, "XXX"), 0); } /** @@ -203,17 +203,17 @@ */ @Test public void removeWithValue() { - Assert.assertTrue(CollectionTools.removeWithValue(beansCol, "name1", AccessType.GETTER, "name")); - Assert.assertSame(beansCol.size(), 0); - beansCol.clear(); - init(); + Assert.assertTrue(CollectionTools.removeWithValue(beansCol, "name1", AccessType.GETTER, "name")); + Assert.assertSame(beansCol.size(), 0); + beansCol.clear(); + init(); - Assert.assertTrue(CollectionTools.removeWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12")); - Assert.assertSame(beansCol.size(), 2); - beansCol.clear(); - init(); + Assert.assertTrue(CollectionTools.removeWithValue(beansCol, "bean2.name2", AccessType.GETTER, "name12")); + Assert.assertSame(beansCol.size(), 2); + beansCol.clear(); + init(); - Assert.assertFalse(CollectionTools.removeWithValue(beansCol, "name1", AccessType.GETTER, "XXX")); + Assert.assertFalse(CollectionTools.removeWithValue(beansCol, "name1", AccessType.GETTER, "XXX")); } /** @@ -221,20 +221,20 @@ */ @Test public void removeAllWithValue() { - Assert.assertTrue(CollectionTools.removeAllWithValue(beansCol, "name1", AccessType.GETTER, Arrays - .asList(new String[] { "name" }))); - Assert.assertSame(beansCol.size(), 0); - beansCol.clear(); - init(); + Assert.assertTrue(CollectionTools.removeAllWithValue(beansCol, "name1", AccessType.GETTER, Arrays + .asList(new String[] { "name" }))); + Assert.assertSame(beansCol.size(), 0); + beansCol.clear(); + init(); - Assert.assertTrue(CollectionTools.removeAllWithValue(beansCol, "bean2.name2", AccessType.GETTER, Arrays - .asList(new String[] { "name12", "name22" }))); - Assert.assertSame(beansCol.size(), 1); - beansCol.clear(); - init(); + Assert.assertTrue(CollectionTools.removeAllWithValue(beansCol, "bean2.name2", AccessType.GETTER, Arrays + .asList(new String[] { "name12", "name22" }))); + Assert.assertSame(beansCol.size(), 1); + beansCol.clear(); + init(); - Assert.assertFalse(CollectionTools.removeAllWithValue(beansCol, "name1", AccessType.GETTER, Arrays - .asList(new String[] { "XXX", "YYY", "ZZZ" }))); + Assert.assertFalse(CollectionTools.removeAllWithValue(beansCol, "name1", AccessType.GETTER, Arrays + .asList(new String[] { "XXX", "YYY", "ZZZ" }))); } /** @@ -242,9 +242,9 @@ */ @Test public void valuesFromList() { - Assert.assertEquals(CollectionTools.valuesFromList(beansCol, "name1", AccessType.GETTER), Arrays - .asList(new String[] { "name", "name", "name" })); - Assert.assertEquals(CollectionTools.valuesFromList(beansCol, "bean2.name2", AccessType.GETTER), Arrays - .asList(new String[] { "name12", "name22", null })); + Assert.assertEquals(CollectionTools.valuesFromList(beansCol, "name1", AccessType.GETTER), Arrays + .asList(new String[] { "name", "name", "name" })); + Assert.assertEquals(CollectionTools.valuesFromList(beansCol, "bean2.name2", AccessType.GETTER), Arrays + .asList(new String[] { "name12", "name22", null })); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CoordToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CoordToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/CoordToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,18 +41,18 @@ */ @Test public void latitude() { - Integer degrees = 1; - BigDecimal minutes = new BigDecimal("2.300"); - Character orientation = 'N'; - String latitude = CoordTools.latitude(degrees, minutes, orientation); + Integer degrees = 1; + BigDecimal minutes = new BigDecimal("2.300"); + Character orientation = 'N'; + String latitude = CoordTools.latitude(degrees, minutes, orientation); - Assert.assertTrue(CoordTools.validateLatitude(latitude)); - Assert.assertFalse(CoordTools.validateLatitude(latitude - .replace(orientation, Character.toLowerCase(orientation)))); + Assert.assertTrue(CoordTools.validateLatitude(latitude)); + Assert.assertFalse(CoordTools.validateLatitude(latitude + .replace(orientation, Character.toLowerCase(orientation)))); - Assert.assertEquals(degrees, CoordTools.latitudeDegrees(latitude)); - Assert.assertEquals(minutes, CoordTools.latitudeMinutes(latitude)); - Assert.assertEquals(orientation, CoordTools.latitudeOrientation(latitude)); + Assert.assertEquals(degrees, CoordTools.latitudeDegrees(latitude)); + Assert.assertEquals(minutes, CoordTools.latitudeMinutes(latitude)); + Assert.assertEquals(orientation, CoordTools.latitudeOrientation(latitude)); } /** @@ -60,17 +60,17 @@ */ @Test public void longitude() { - Integer degrees = 1; - BigDecimal minutes = new BigDecimal("52.999"); - Character orientation = 'E'; - String longitude = CoordTools.longitude(degrees, minutes, orientation); + Integer degrees = 1; + BigDecimal minutes = new BigDecimal("52.999"); + Character orientation = 'E'; + String longitude = CoordTools.longitude(degrees, minutes, orientation); - Assert.assertTrue(CoordTools.validateLongitude(longitude)); - Assert.assertFalse(CoordTools.validateLongitude(longitude.replace(orientation, Character - .toLowerCase(orientation)))); + Assert.assertTrue(CoordTools.validateLongitude(longitude)); + Assert.assertFalse(CoordTools.validateLongitude(longitude.replace(orientation, Character + .toLowerCase(orientation)))); - Assert.assertEquals(degrees, CoordTools.longitudeDegrees(longitude)); - Assert.assertEquals(minutes, CoordTools.longitudeMinutes(longitude)); - Assert.assertEquals(orientation, CoordTools.longitudeOrientation(longitude)); + Assert.assertEquals(degrees, CoordTools.longitudeDegrees(longitude)); + Assert.assertEquals(minutes, CoordTools.longitudeMinutes(longitude)); + Assert.assertEquals(orientation, CoordTools.longitudeOrientation(longitude)); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/GenericsToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/GenericsToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/GenericsToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,8 +37,8 @@ */ @Test public void cast() { - Number n = 1; - Integer i = GenericsTools.cast(n); - Assert.assertEquals((Integer) 1, i); + Number n = 1; + Integer i = GenericsTools.cast(n); + Assert.assertEquals((Integer) 1, i); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/NumberToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/NumberToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/NumberToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,104 +42,104 @@ */ @Test public void nullIfZero() { - // AtomicInteger - AtomicInteger ai = null; - Assert.assertNull(NumberTools.nullIfZero(ai)); - ai = new AtomicInteger(-1); - Assert.assertEquals(ai, NumberTools.nullIfZero(ai)); - ai.set(0); - Assert.assertNull(NumberTools.nullIfZero(ai)); - ai.set(1); - Assert.assertEquals(ai, NumberTools.nullIfZero(ai)); - // AtomicLong - AtomicLong al = null; - Assert.assertNull(NumberTools.nullIfZero(al)); - al = new AtomicLong(-1L); - Assert.assertEquals(al, NumberTools.nullIfZero(al)); - al.set(0L); - Assert.assertNull(NumberTools.nullIfZero(al)); - al.set(1L); - Assert.assertEquals(al, NumberTools.nullIfZero(al)); - // BigDecimal - BigDecimal bd = null; - Assert.assertNull(NumberTools.nullIfZero(bd)); - bd = new BigDecimal(-1.0D); - Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); - bd = new BigDecimal(-.5D); - Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); - bd = new BigDecimal(0.0D); - Assert.assertNull(NumberTools.nullIfZero(bd)); - bd = new BigDecimal(.5D); - Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); - bd = new BigDecimal(1.0D); - Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); - // BigInteger - BigInteger bi = null; - Assert.assertNull(NumberTools.nullIfZero(bi)); - bi = new BigInteger("-1"); - Assert.assertEquals(bi, NumberTools.nullIfZero(bi)); - bi = new BigInteger("0"); - Assert.assertNull(NumberTools.nullIfZero(bi)); - bi = new BigInteger("1"); - Assert.assertEquals(bi, NumberTools.nullIfZero(bi)); - // Byte - Byte b = null; - Assert.assertNull(NumberTools.nullIfZero(b)); - b = 0; - Assert.assertNull(NumberTools.nullIfZero(b)); - b = 1; - Assert.assertEquals(b, NumberTools.nullIfZero(b)); - // Double - Double d = null; - Assert.assertNull(NumberTools.nullIfZero(d)); - d = -1.0D; - Assert.assertEquals(d, NumberTools.nullIfZero(d)); - d = -.5D; - Assert.assertEquals(d, NumberTools.nullIfZero(d)); - d = 0.0D; - Assert.assertNull(NumberTools.nullIfZero(d)); - d = .5D; - Assert.assertEquals(d, NumberTools.nullIfZero(d)); - d = 1.0D; - Assert.assertEquals(d, NumberTools.nullIfZero(d)); - // Float - Float f = null; - Assert.assertNull(NumberTools.nullIfZero(f)); - f = -1.0F; - Assert.assertEquals(f, NumberTools.nullIfZero(f)); - f = -.5F; - Assert.assertEquals(f, NumberTools.nullIfZero(f)); - f = 0.0F; - Assert.assertNull(NumberTools.nullIfZero(f)); - f = .5F; - Assert.assertEquals(f, NumberTools.nullIfZero(f)); - f = 1.0F; - Assert.assertEquals(f, NumberTools.nullIfZero(f)); - // Integer - Integer i = null; - Assert.assertNull(NumberTools.nullIfZero(i)); - i = -1; - Assert.assertEquals(i, NumberTools.nullIfZero(i)); - i = 0; - Assert.assertNull(NumberTools.nullIfZero(i)); - i = 1; - Assert.assertEquals(i, NumberTools.nullIfZero(i)); - // Long - Long l = null; - Assert.assertNull(NumberTools.nullIfZero(l)); - l = -1L; - Assert.assertEquals(l, NumberTools.nullIfZero(l)); - l = 0L; - Assert.assertNull(NumberTools.nullIfZero(l)); - l = 1L; - Assert.assertEquals(l, NumberTools.nullIfZero(l)); - // Short - Short s = null; - Assert.assertNull(NumberTools.nullIfZero(s)); - s = -1; - Assert.assertEquals(s, NumberTools.nullIfZero(s)); - s = 0; - Assert.assertNull(NumberTools.nullIfZero(s)); - s = 1; + // AtomicInteger + AtomicInteger ai = null; + Assert.assertNull(NumberTools.nullIfZero(ai)); + ai = new AtomicInteger(-1); + Assert.assertEquals(ai, NumberTools.nullIfZero(ai)); + ai.set(0); + Assert.assertNull(NumberTools.nullIfZero(ai)); + ai.set(1); + Assert.assertEquals(ai, NumberTools.nullIfZero(ai)); + // AtomicLong + AtomicLong al = null; + Assert.assertNull(NumberTools.nullIfZero(al)); + al = new AtomicLong(-1L); + Assert.assertEquals(al, NumberTools.nullIfZero(al)); + al.set(0L); + Assert.assertNull(NumberTools.nullIfZero(al)); + al.set(1L); + Assert.assertEquals(al, NumberTools.nullIfZero(al)); + // BigDecimal + BigDecimal bd = null; + Assert.assertNull(NumberTools.nullIfZero(bd)); + bd = new BigDecimal(-1.0D); + Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); + bd = new BigDecimal(-.5D); + Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); + bd = new BigDecimal(0.0D); + Assert.assertNull(NumberTools.nullIfZero(bd)); + bd = new BigDecimal(.5D); + Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); + bd = new BigDecimal(1.0D); + Assert.assertEquals(bd, NumberTools.nullIfZero(bd)); + // BigInteger + BigInteger bi = null; + Assert.assertNull(NumberTools.nullIfZero(bi)); + bi = new BigInteger("-1"); + Assert.assertEquals(bi, NumberTools.nullIfZero(bi)); + bi = new BigInteger("0"); + Assert.assertNull(NumberTools.nullIfZero(bi)); + bi = new BigInteger("1"); + Assert.assertEquals(bi, NumberTools.nullIfZero(bi)); + // Byte + Byte b = null; + Assert.assertNull(NumberTools.nullIfZero(b)); + b = 0; + Assert.assertNull(NumberTools.nullIfZero(b)); + b = 1; + Assert.assertEquals(b, NumberTools.nullIfZero(b)); + // Double + Double d = null; + Assert.assertNull(NumberTools.nullIfZero(d)); + d = -1.0D; + Assert.assertEquals(d, NumberTools.nullIfZero(d)); + d = -.5D; + Assert.assertEquals(d, NumberTools.nullIfZero(d)); + d = 0.0D; + Assert.assertNull(NumberTools.nullIfZero(d)); + d = .5D; + Assert.assertEquals(d, NumberTools.nullIfZero(d)); + d = 1.0D; + Assert.assertEquals(d, NumberTools.nullIfZero(d)); + // Float + Float f = null; + Assert.assertNull(NumberTools.nullIfZero(f)); + f = -1.0F; + Assert.assertEquals(f, NumberTools.nullIfZero(f)); + f = -.5F; + Assert.assertEquals(f, NumberTools.nullIfZero(f)); + f = 0.0F; + Assert.assertNull(NumberTools.nullIfZero(f)); + f = .5F; + Assert.assertEquals(f, NumberTools.nullIfZero(f)); + f = 1.0F; + Assert.assertEquals(f, NumberTools.nullIfZero(f)); + // Integer + Integer i = null; + Assert.assertNull(NumberTools.nullIfZero(i)); + i = -1; + Assert.assertEquals(i, NumberTools.nullIfZero(i)); + i = 0; + Assert.assertNull(NumberTools.nullIfZero(i)); + i = 1; + Assert.assertEquals(i, NumberTools.nullIfZero(i)); + // Long + Long l = null; + Assert.assertNull(NumberTools.nullIfZero(l)); + l = -1L; + Assert.assertEquals(l, NumberTools.nullIfZero(l)); + l = 0L; + Assert.assertNull(NumberTools.nullIfZero(l)); + l = 1L; + Assert.assertEquals(l, NumberTools.nullIfZero(l)); + // Short + Short s = null; + Assert.assertNull(NumberTools.nullIfZero(s)); + s = -1; + Assert.assertEquals(s, NumberTools.nullIfZero(s)); + s = 0; + Assert.assertNull(NumberTools.nullIfZero(s)); + s = 1; } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PairTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PairTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PairTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,16 +37,16 @@ */ @Test public void pair() { - Pair<Integer, String> pair = new Pair<Integer, String>(1, "Toto"); - Assert.assertEquals((Integer) 1, pair.getKey()); - Assert.assertEquals("Toto", pair.getValue()); - pair.setKey(2); - Assert.assertEquals((Integer) 2, pair.getKey()); - Assert.assertEquals("Toto", pair.setValue("Titi")); - Assert.assertEquals("Titi", pair.getValue()); - Pair<Integer, String> pair2 = new Pair<Integer, String>(1, "Titi"); - Assert.assertNotSame(pair, pair2); - Pair<Integer, String> pair3 = new Pair<Integer, String>(2, "Titi"); - Assert.assertEquals(pair, pair3); + Pair<Integer, String> pair = new Pair<Integer, String>(1, "Toto"); + Assert.assertEquals((Integer) 1, pair.getKey()); + Assert.assertEquals("Toto", pair.getValue()); + pair.setKey(2); + Assert.assertEquals((Integer) 2, pair.getKey()); + Assert.assertEquals("Toto", pair.setValue("Titi")); + Assert.assertEquals("Titi", pair.getValue()); + Pair<Integer, String> pair2 = new Pair<Integer, String>(1, "Titi"); + Assert.assertNotSame(pair, pair2); + Pair<Integer, String> pair3 = new Pair<Integer, String>(2, "Titi"); + Assert.assertEquals(pair, pair3); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PasswordToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PasswordToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/PasswordToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,16 +37,16 @@ */ @Test public void md5() { - String hash1 = PasswordTools.md5("toto"); - Assert.assertNotNull(hash1); - Assert.assertEquals(PasswordTools.MD5_LENGTH, hash1.length()); - Assert.assertEquals(PasswordTools.md5("toto"), hash1); - String hash2 = PasswordTools.md5("titi"); - Assert.assertNotNull(hash2); - Assert.assertEquals(PasswordTools.MD5_LENGTH, hash2.length()); - Assert.assertEquals(PasswordTools.md5("titi"), hash2); - Assert.assertNotNull(hash1); - Assert.assertTrue(!hash1.equals(hash2)); + String hash1 = PasswordTools.md5("toto"); + Assert.assertNotNull(hash1); + Assert.assertEquals(PasswordTools.MD5_LENGTH, hash1.length()); + Assert.assertEquals(PasswordTools.md5("toto"), hash1); + String hash2 = PasswordTools.md5("titi"); + Assert.assertNotNull(hash2); + Assert.assertEquals(PasswordTools.MD5_LENGTH, hash2.length()); + Assert.assertEquals(PasswordTools.md5("titi"), hash2); + Assert.assertNotNull(hash1); + Assert.assertTrue(!hash1.equals(hash2)); } /** @@ -54,15 +54,15 @@ */ @Test public void random() { - String password1 = PasswordTools.random(); - Assert.assertNotNull(password1); - Assert.assertTrue(password1.length() >= PasswordTools.PASSWORD_LENGTH_MIN); - Assert.assertTrue(password1.length() <= PasswordTools.PASSWORD_LENGTH_MAX); - String password2 = PasswordTools.random(); - Assert.assertNotNull(password2); - Assert.assertTrue(password2.length() >= PasswordTools.PASSWORD_LENGTH_MIN); - Assert.assertTrue(password2.length() <= PasswordTools.PASSWORD_LENGTH_MAX); - Assert.assertTrue(!password1.equals(password2)); + String password1 = PasswordTools.random(); + Assert.assertNotNull(password1); + Assert.assertTrue(password1.length() >= PasswordTools.PASSWORD_LENGTH_MIN); + Assert.assertTrue(password1.length() <= PasswordTools.PASSWORD_LENGTH_MAX); + String password2 = PasswordTools.random(); + Assert.assertNotNull(password2); + Assert.assertTrue(password2.length() >= PasswordTools.PASSWORD_LENGTH_MIN); + Assert.assertTrue(password2.length() <= PasswordTools.PASSWORD_LENGTH_MAX); + Assert.assertTrue(!password1.equals(password2)); } /** @@ -70,14 +70,14 @@ */ @Test public void sha1() { - String hash1 = PasswordTools.sha1("toto"); - Assert.assertNotNull(hash1); - Assert.assertEquals(PasswordTools.sha1("toto"), hash1); - Assert.assertEquals(PasswordTools.SHA1_LENGTH, hash1.length()); - String hash2 = PasswordTools.sha1("titi"); - Assert.assertNotNull(hash2); - Assert.assertEquals(PasswordTools.SHA1_LENGTH, hash2.length()); - Assert.assertNotNull(hash1); - Assert.assertTrue(!hash1.equals(hash2)); + String hash1 = PasswordTools.sha1("toto"); + Assert.assertNotNull(hash1); + Assert.assertEquals(PasswordTools.sha1("toto"), hash1); + Assert.assertEquals(PasswordTools.SHA1_LENGTH, hash1.length()); + String hash2 = PasswordTools.sha1("titi"); + Assert.assertNotNull(hash2); + Assert.assertEquals(PasswordTools.SHA1_LENGTH, hash2.length()); + Assert.assertNotNull(hash1); + Assert.assertTrue(!hash1.equals(hash2)); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringToolsTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringToolsTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringToolsTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,17 +42,17 @@ */ @Test public void couplesToString() { - // Empty - Map<String, Integer> couples = new HashMap<String, Integer>(); - String toString = StringTools.couplesToString(couples, " ", " / "); - // One couple - couples.put("Toto", 1); - toString = StringTools.couplesToString(couples, " ", " / "); - Assert.assertEquals("Toto 1", toString); - // Two couples - couples.put("Titi", 2); - toString = StringTools.couplesToString(couples, " ", " / "); - Assert.assertEquals("Toto 1 / Titi 2", toString); + // Empty + Map<String, Integer> couples = new HashMap<String, Integer>(); + String toString = StringTools.couplesToString(couples, " ", " / "); + // One couple + couples.put("Toto", 1); + toString = StringTools.couplesToString(couples, " ", " / "); + Assert.assertEquals("Toto 1", toString); + // Two couples + couples.put("Titi", 2); + toString = StringTools.couplesToString(couples, " ", " / "); + Assert.assertEquals("Toto 1 / Titi 2", toString); } /** @@ -60,9 +60,9 @@ */ @Test public void length() { - Assert.assertEquals(-1, StringTools.length(null)); - Assert.assertEquals(0, StringTools.length("")); - Assert.assertEquals(1, StringTools.length("a")); + Assert.assertEquals(-1, StringTools.length(null)); + Assert.assertEquals(0, StringTools.length("")); + Assert.assertEquals(1, StringTools.length("a")); } /** @@ -70,30 +70,30 @@ */ @Test public void lineIterator() { - // Empty - StringBuilder lines = new StringBuilder(); - Iterator<String> i = StringTools.lineIterator(lines); - Assert.assertFalse(i.hasNext()); - // One line - lines.append("Toto"); - i = StringTools.lineIterator(lines); - Assert.assertTrue(i.hasNext()); - Assert.assertEquals("Toto", i.next()); - Assert.assertFalse(i.hasNext()); - // Two lines with a blank one - lines.append("\n "); - i = StringTools.lineIterator(lines); - Assert.assertTrue(i.hasNext()); - Assert.assertEquals("Toto", i.next()); - Assert.assertFalse(i.hasNext()); - // Three lines with a blank one - lines.append("\nTiti"); - i = StringTools.lineIterator(lines); - Assert.assertTrue(i.hasNext()); - Assert.assertEquals("Toto", i.next()); - Assert.assertTrue(i.hasNext()); - Assert.assertEquals("Titi", i.next()); - Assert.assertFalse(i.hasNext()); + // Empty + StringBuilder lines = new StringBuilder(); + Iterator<String> i = StringTools.lineIterator(lines); + Assert.assertFalse(i.hasNext()); + // One line + lines.append("Toto"); + i = StringTools.lineIterator(lines); + Assert.assertTrue(i.hasNext()); + Assert.assertEquals("Toto", i.next()); + Assert.assertFalse(i.hasNext()); + // Two lines with a blank one + lines.append("\n "); + i = StringTools.lineIterator(lines); + Assert.assertTrue(i.hasNext()); + Assert.assertEquals("Toto", i.next()); + Assert.assertFalse(i.hasNext()); + // Three lines with a blank one + lines.append("\nTiti"); + i = StringTools.lineIterator(lines); + Assert.assertTrue(i.hasNext()); + Assert.assertEquals("Toto", i.next()); + Assert.assertTrue(i.hasNext()); + Assert.assertEquals("Titi", i.next()); + Assert.assertFalse(i.hasNext()); } /** @@ -101,11 +101,11 @@ */ @Test public void replaceAccents() { - Assert.assertEquals(null, StringTools.replaceAccents(null)); - Assert.assertEquals("", StringTools.replaceAccents("")); - Assert.assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYz", StringTools.replaceAccents("AbCdEfGhIjKlMnOpQrStUvWxYz")); - Assert.assertEquals("&e'(-e_ca)=u%*µ^¨$£}¤]@^`|[{#~", StringTools - .replaceAccents("&é'(-è_çà)=ù%*µ^¨$£}¤]@^`|[{#~")); + Assert.assertEquals(null, StringTools.replaceAccents(null)); + Assert.assertEquals("", StringTools.replaceAccents("")); + Assert.assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYz", StringTools.replaceAccents("AbCdEfGhIjKlMnOpQrStUvWxYz")); + Assert.assertEquals("&e'(-e_ca)=u%*µ^¨$£}¤]@^`|[{#~", StringTools + .replaceAccents("&é'(-è_çà)=ù%*µ^¨$£}¤]@^`|[{#~")); } /** @@ -113,11 +113,11 @@ */ @Test public void replaceConsecutiveWhitespaces() { - Assert.assertNull(StringTools.replaceConsecutiveWhitespaces(null)); - Assert.assertEquals("", StringTools.replaceConsecutiveWhitespaces("")); - Assert.assertEquals(" ", StringTools.replaceConsecutiveWhitespaces(" ")); - Assert.assertEquals(" ", StringTools.replaceConsecutiveWhitespaces(" ")); - Assert.assertEquals(" toto titi ", StringTools.replaceConsecutiveWhitespaces(" toto titi ")); + Assert.assertNull(StringTools.replaceConsecutiveWhitespaces(null)); + Assert.assertEquals("", StringTools.replaceConsecutiveWhitespaces("")); + Assert.assertEquals(" ", StringTools.replaceConsecutiveWhitespaces(" ")); + Assert.assertEquals(" ", StringTools.replaceConsecutiveWhitespaces(" ")); + Assert.assertEquals(" toto titi ", StringTools.replaceConsecutiveWhitespaces(" toto titi ")); } /** @@ -125,11 +125,11 @@ */ @Test public void replaceConsecutiveWhitespacesByUnderscore() { - Assert.assertNull(StringTools.replaceConsecutiveWhitespaces(null)); - Assert.assertEquals("", StringTools.replaceConsecutiveWhitespacesByUnderscore("")); - Assert.assertEquals("_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" ")); - Assert.assertEquals("_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" ")); - Assert.assertEquals("_toto_titi_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" toto titi ")); + Assert.assertNull(StringTools.replaceConsecutiveWhitespaces(null)); + Assert.assertEquals("", StringTools.replaceConsecutiveWhitespacesByUnderscore("")); + Assert.assertEquals("_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" ")); + Assert.assertEquals("_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" ")); + Assert.assertEquals("_toto_titi_", StringTools.replaceConsecutiveWhitespacesByUnderscore(" toto titi ")); } /** @@ -137,12 +137,12 @@ */ @Test public void replaceNonAlpha() { - Assert.assertNull(StringTools.replaceNonAlpha(null)); - Assert.assertEquals("", StringTools.replaceNonAlpha("")); - Assert.assertEquals(" ", StringTools.replaceNonAlpha(" ")); - Assert.assertEquals("e", StringTools.replaceNonAlpha("e")); - Assert.assertEquals(" ", StringTools.replaceNonAlpha("é")); - Assert.assertEquals("tot ", StringTools.replaceNonAlpha("totô2")); + Assert.assertNull(StringTools.replaceNonAlpha(null)); + Assert.assertEquals("", StringTools.replaceNonAlpha("")); + Assert.assertEquals(" ", StringTools.replaceNonAlpha(" ")); + Assert.assertEquals("e", StringTools.replaceNonAlpha("e")); + Assert.assertEquals(" ", StringTools.replaceNonAlpha("é")); + Assert.assertEquals("tot ", StringTools.replaceNonAlpha("totô2")); } /** @@ -150,23 +150,23 @@ */ @Test public void truncate() { - String truncation = ".."; - StringBuilder toTruncate = new StringBuilder(); - // Null - Assert.assertNull(StringTools.truncate((StringBuilder) null, truncation)); - Assert.assertNull(StringTools.truncate((String) null, truncation)); - // Empty - Assert.assertNotNull(StringTools.truncate(toTruncate, truncation)); - Assert.assertTrue(StringTools.truncate(toTruncate, truncation).isEmpty()); - // Without truncation - toTruncate.append("."); - Assert.assertEquals(".", StringTools.truncate(toTruncate, truncation)); - // With truncation -> empty - toTruncate.append("."); - Assert.assertNotNull(StringTools.truncate(toTruncate, truncation)); - Assert.assertTrue(StringTools.truncate(toTruncate, truncation).isEmpty()); - // With truncation -> !empty - toTruncate.append("."); - Assert.assertEquals(".", StringTools.truncate(toTruncate, truncation)); + String truncation = ".."; + StringBuilder toTruncate = new StringBuilder(); + // Null + Assert.assertNull(StringTools.truncate((StringBuilder) null, truncation)); + Assert.assertNull(StringTools.truncate((String) null, truncation)); + // Empty + Assert.assertNotNull(StringTools.truncate(toTruncate, truncation)); + Assert.assertTrue(StringTools.truncate(toTruncate, truncation).isEmpty()); + // Without truncation + toTruncate.append("."); + Assert.assertEquals(".", StringTools.truncate(toTruncate, truncation)); + // With truncation -> empty + toTruncate.append("."); + Assert.assertNotNull(StringTools.truncate(toTruncate, truncation)); + Assert.assertTrue(StringTools.truncate(toTruncate, truncation).isEmpty()); + // With truncation -> !empty + toTruncate.append("."); + Assert.assertEquals(".", StringTools.truncate(toTruncate, truncation)); } } Modified: trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringTransformerTest.java =================================================================== --- trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringTransformerTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.utils/src/test/java/nc/ird/module/utils/StringTransformerTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,11 +38,11 @@ */ @Test public void capitalize() { - Assert.assertNull(new StringTransformer(null).capitalize().toString()); - Assert.assertEquals("", new StringTransformer("").capitalize().toString()); - Assert.assertEquals("AAa", new StringTransformer("AAa").capitalize().toString()); - Assert.assertEquals("AAa BBb", new StringTransformer("aAa bBb").capitalize().toString()); - Assert.assertEquals("AAa-bBb", new StringTransformer("aAa-bBb").capitalize().toString()); + Assert.assertNull(new StringTransformer(null).capitalize().toString()); + Assert.assertEquals("", new StringTransformer("").capitalize().toString()); + Assert.assertEquals("AAa", new StringTransformer("AAa").capitalize().toString()); + Assert.assertEquals("AAa BBb", new StringTransformer("aAa bBb").capitalize().toString()); + Assert.assertEquals("AAa-bBb", new StringTransformer("aAa-bBb").capitalize().toString()); } /** @@ -50,11 +50,11 @@ */ @Test public void capitalizeFully() { - Assert.assertNull(new StringTransformer(null).capitalizeFully().toString()); - Assert.assertEquals("", new StringTransformer("").capitalizeFully().toString()); - Assert.assertEquals("Aaa", new StringTransformer("AAa").capitalizeFully().toString()); - Assert.assertEquals("Aaa Bbb", new StringTransformer("aAa bBb").capitalizeFully().toString()); - Assert.assertEquals("Aaa-bbb", new StringTransformer("aAa-bBb").capitalizeFully().toString()); + Assert.assertNull(new StringTransformer(null).capitalizeFully().toString()); + Assert.assertEquals("", new StringTransformer("").capitalizeFully().toString()); + Assert.assertEquals("Aaa", new StringTransformer("AAa").capitalizeFully().toString()); + Assert.assertEquals("Aaa Bbb", new StringTransformer("aAa bBb").capitalizeFully().toString()); + Assert.assertEquals("Aaa-bbb", new StringTransformer("aAa-bBb").capitalizeFully().toString()); } /** @@ -62,12 +62,12 @@ */ @Test public void init() { - Assert.assertNull(new StringTransformer(null).toString()); - Assert.assertEquals("", new StringTransformer("").toString()); - Assert.assertEquals("toto", new StringTransformer("toto").toString()); + Assert.assertNull(new StringTransformer(null).toString()); + Assert.assertEquals("", new StringTransformer("").toString()); + Assert.assertEquals("toto", new StringTransformer("toto").toString()); - StringTransformer st = new StringTransformer(null); - Assert.assertEquals(st, st.trim()); + StringTransformer st = new StringTransformer(null); + Assert.assertEquals(st, st.trim()); } /** @@ -75,12 +75,12 @@ */ @Test public void replaceAccents() { - Assert.assertNull(new StringTransformer(null).replaceAccents().toString()); - Assert.assertEquals("", new StringTransformer("").replaceAccents().toString()); - Assert.assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYz", new StringTransformer("AbCdEfGhIjKlMnOpQrStUvWxYz") - .replaceAccents().toString()); - Assert.assertEquals("&e'(-e_ca)=u%*µ^¨$£}¤]@^`|[{#~", new StringTransformer("&é'(-è_çà)=ù%*µ^¨$£}¤]@^`|[{#~") - .replaceAccents().toString()); + Assert.assertNull(new StringTransformer(null).replaceAccents().toString()); + Assert.assertEquals("", new StringTransformer("").replaceAccents().toString()); + Assert.assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYz", new StringTransformer("AbCdEfGhIjKlMnOpQrStUvWxYz") + .replaceAccents().toString()); + Assert.assertEquals("&e'(-e_ca)=u%*µ^¨$£}¤]@^`|[{#~", new StringTransformer("&é'(-è_çà)=ù%*µ^¨$£}¤]@^`|[{#~") + .replaceAccents().toString()); } /** @@ -88,12 +88,12 @@ */ @Test public void replaceConsecutiveWhitespaces() { - Assert.assertNull(new StringTransformer(null).replaceConsecutiveWhitespaces().toString()); - Assert.assertEquals("", new StringTransformer("").replaceConsecutiveWhitespaces().toString()); - Assert.assertEquals(" ", new StringTransformer(" ").replaceConsecutiveWhitespaces().toString()); - Assert.assertEquals(" ", new StringTransformer(" ").replaceConsecutiveWhitespaces().toString()); - Assert.assertEquals(" toto titi ", new StringTransformer(" toto titi ").replaceConsecutiveWhitespaces() - .toString()); + Assert.assertNull(new StringTransformer(null).replaceConsecutiveWhitespaces().toString()); + Assert.assertEquals("", new StringTransformer("").replaceConsecutiveWhitespaces().toString()); + Assert.assertEquals(" ", new StringTransformer(" ").replaceConsecutiveWhitespaces().toString()); + Assert.assertEquals(" ", new StringTransformer(" ").replaceConsecutiveWhitespaces().toString()); + Assert.assertEquals(" toto titi ", new StringTransformer(" toto titi ").replaceConsecutiveWhitespaces() + .toString()); } /** @@ -101,12 +101,12 @@ */ @Test public void replaceNonAlpha() { - Assert.assertNull(new StringTransformer(null).toString()); - Assert.assertEquals("", new StringTransformer("").replaceNonAlpha().toString()); - Assert.assertEquals(" ", new StringTransformer(" ").replaceNonAlpha().toString()); - Assert.assertEquals("e", new StringTransformer("e").replaceNonAlpha().toString()); - Assert.assertEquals(" ", new StringTransformer("é").replaceNonAlpha().toString()); - Assert.assertEquals("tot ", new StringTransformer("totô2").replaceNonAlpha().toString()); + Assert.assertNull(new StringTransformer(null).toString()); + Assert.assertEquals("", new StringTransformer("").replaceNonAlpha().toString()); + Assert.assertEquals(" ", new StringTransformer(" ").replaceNonAlpha().toString()); + Assert.assertEquals("e", new StringTransformer("e").replaceNonAlpha().toString()); + Assert.assertEquals(" ", new StringTransformer("é").replaceNonAlpha().toString()); + Assert.assertEquals("tot ", new StringTransformer("totô2").replaceNonAlpha().toString()); } /** @@ -114,10 +114,10 @@ */ @Test public void toLowerCase() { - Assert.assertNull(new StringTransformer(null).toLowerCase().toString()); - Assert.assertEquals("", new StringTransformer("").toLowerCase().toString()); - Assert.assertEquals("a", new StringTransformer("A").toLowerCase().toString()); - Assert.assertEquals("aaaââ", new StringTransformer("aAaÂâ").toLowerCase().toString()); + Assert.assertNull(new StringTransformer(null).toLowerCase().toString()); + Assert.assertEquals("", new StringTransformer("").toLowerCase().toString()); + Assert.assertEquals("a", new StringTransformer("A").toLowerCase().toString()); + Assert.assertEquals("aaaââ", new StringTransformer("aAaÂâ").toLowerCase().toString()); } /** @@ -125,10 +125,10 @@ */ @Test public void toUpperCase() { - Assert.assertNull(new StringTransformer(null).toUpperCase().toString()); - Assert.assertEquals("", new StringTransformer("").toUpperCase().toString()); - Assert.assertEquals("A", new StringTransformer("a").toUpperCase().toString()); - Assert.assertEquals("AAAÂÂ", new StringTransformer("aAaÂâ").toUpperCase().toString()); + Assert.assertNull(new StringTransformer(null).toUpperCase().toString()); + Assert.assertEquals("", new StringTransformer("").toUpperCase().toString()); + Assert.assertEquals("A", new StringTransformer("a").toUpperCase().toString()); + Assert.assertEquals("AAAÂÂ", new StringTransformer("aAaÂâ").toUpperCase().toString()); } /** @@ -136,11 +136,11 @@ */ @Test public void trim() { - Assert.assertNull(new StringTransformer(null).trim().toString()); - Assert.assertEquals("", new StringTransformer("").trim().toString()); - Assert.assertEquals("", new StringTransformer(" ").trim().toString()); - Assert.assertEquals("toto", new StringTransformer(" toto ").trim().toString()); - Assert.assertEquals("toto titi", new StringTransformer(" toto titi ").trim().toString()); + Assert.assertNull(new StringTransformer(null).trim().toString()); + Assert.assertEquals("", new StringTransformer("").trim().toString()); + Assert.assertEquals("", new StringTransformer(" ").trim().toString()); + Assert.assertEquals("toto", new StringTransformer(" toto ").trim().toString()); + Assert.assertEquals("toto titi", new StringTransformer(" toto titi ").trim().toString()); } /** @@ -148,10 +148,10 @@ */ @Test public void trimToNull() { - Assert.assertNull(new StringTransformer(null).trimToNull().toString()); - Assert.assertNull(new StringTransformer("").trimToNull().toString()); - Assert.assertNull(new StringTransformer(" ").trimToNull().toString()); - Assert.assertEquals("toto", new StringTransformer(" toto ").trimToNull().toString()); - Assert.assertEquals("toto titi", new StringTransformer(" toto titi ").trim().toString()); + Assert.assertNull(new StringTransformer(null).trimToNull().toString()); + Assert.assertNull(new StringTransformer("").trimToNull().toString()); + Assert.assertNull(new StringTransformer(" ").trimToNull().toString()); + Assert.assertEquals("toto", new StringTransformer(" toto ").trimToNull().toString()); + Assert.assertEquals("toto titi", new StringTransformer(" toto titi ").trim().toString()); } } Modified: trunk/cantharella.web/pom.xml =================================================================== --- trunk/cantharella.web/pom.xml 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/pom.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,6 @@ </resource> </resources> <plugins> - <!-- Default plugins for the web layer --> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> @@ -47,6 +46,14 @@ <stopKey>jetty-stop</stopKey> </configuration> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + <plugin> + <groupId>com.googlecode.maven-java-formatter-plugin</groupId> + <artifactId>maven-java-formatter-plugin</artifactId> + </plugin> </plugins> </build> Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebApplicationImpl.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebApplicationImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebApplicationImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -115,7 +115,7 @@ * @param object Object to be injected */ public static void injectSpringBeans(Object object) { - Injector.get().inject(object); + Injector.get().inject(object); } /** Debug mode */ @@ -142,193 +142,193 @@ * @param messages Internationalization messages */ public WebApplicationImpl(boolean debug, boolean optimize, RuntimeConfigurationType wicketConfiguration, - IStringResourceLoader... messages) { - AssertTools.assertArrayNotNull(messages); - this.debug = debug; - this.optimize = optimize; - this.wicketConfiguration = wicketConfiguration; - this.messages = messages; + IStringResourceLoader... messages) { + AssertTools.assertArrayNotNull(messages); + this.debug = debug; + this.optimize = optimize; + this.wicketConfiguration = wicketConfiguration; + this.messages = messages; } /** {@inheritDoc} */ @Override public RuntimeConfigurationType getConfigurationType() { - return wicketConfiguration; + return wicketConfiguration; } /** {@inheritDoc} */ @Override public Class<HomePage> getHomePage() { - return HomePage.class; + return HomePage.class; } /** {@inheritDoc} */ @Override protected void init() { - super.init(); - getComponentInstantiationListeners().add(new SpringComponentInjector(this)); - injectSpringBeans(this); - try { - personneService.checkOrCreateAdmin(); - } catch (DataConstraintException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - setApplicationSettings(); - setDebugSettings(); - setExceptionSettings(); - setFrameworkSettings(); - setMarkupSettings(); - setPageSettings(); - setRequestCycleSettings(); - setRequestLoggerSettings(); - setResourceSettings(); - setSecuritySettings(); - mountUrls(); + super.init(); + getComponentInstantiationListeners().add(new SpringComponentInjector(this)); + injectSpringBeans(this); + try { + personneService.checkOrCreateAdmin(); + } catch (DataConstraintException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + setApplicationSettings(); + setDebugSettings(); + setExceptionSettings(); + setFrameworkSettings(); + setMarkupSettings(); + setPageSettings(); + setRequestCycleSettings(); + setRequestLoggerSettings(); + setResourceSettings(); + setSecuritySettings(); + mountUrls(); } /** {@inheritDoc} */ @Override protected IConverterLocator newConverterLocator() { - ConverterLocator converterLocator = (ConverterLocator) super.newConverterLocator(); - converterLocator.set(Double.class, DoubleConverterImpl.INSTANCE); - converterLocator.set(BigDecimal.class, BigDecimalConverterImpl.INSTANCE); - return converterLocator; + ConverterLocator converterLocator = (ConverterLocator) super.newConverterLocator(); + converterLocator.set(Double.class, DoubleConverterImpl.INSTANCE); + converterLocator.set(BigDecimal.class, BigDecimalConverterImpl.INSTANCE); + return converterLocator; } /** {@inheritDoc} */ @Override public Session newSession(Request request, Response response) { - return new AuthSession(request); + return new AuthSession(request); } /** * Application settings */ private void setApplicationSettings() { - getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class); - getApplicationSettings().setDefaultMaximumUploadSize(WebContext.HTTP_MAXIMUM_UPLOAD); - getApplicationSettings().setInternalErrorPage(InternalErrorPage.class); - getApplicationSettings().setPageExpiredErrorPage(PageExpiredErrorPage.class); + getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class); + getApplicationSettings().setDefaultMaximumUploadSize(WebContext.HTTP_MAXIMUM_UPLOAD); + getApplicationSettings().setInternalErrorPage(InternalErrorPage.class); + getApplicationSettings().setPageExpiredErrorPage(PageExpiredErrorPage.class); } /** * Debug settings */ private void setDebugSettings() { - getDebugSettings().setAjaxDebugModeEnabled(debug); - getDebugSettings().setComponentUseCheck(debug); - getDebugSettings().setDevelopmentUtilitiesEnabled(debug); - getDebugSettings().setLinePreciseReportingOnAddComponentEnabled(debug); - getDebugSettings().setLinePreciseReportingOnNewComponentEnabled(debug); - getDebugSettings().setOutputComponentPath(debug); - getDebugSettings().setOutputMarkupContainerClassName(debug); + getDebugSettings().setAjaxDebugModeEnabled(debug); + getDebugSettings().setComponentUseCheck(debug); + getDebugSettings().setDevelopmentUtilitiesEnabled(debug); + getDebugSettings().setLinePreciseReportingOnAddComponentEnabled(debug); + getDebugSettings().setLinePreciseReportingOnNewComponentEnabled(debug); + getDebugSettings().setOutputComponentPath(debug); + getDebugSettings().setOutputMarkupContainerClassName(debug); } /** * Exception settings */ private void setExceptionSettings() { - getExceptionSettings().setUnexpectedExceptionDisplay( - debug ? IExceptionSettings.SHOW_EXCEPTION_PAGE : IExceptionSettings.SHOW_INTERNAL_ERROR_PAGE); + getExceptionSettings().setUnexpectedExceptionDisplay( + debug ? IExceptionSettings.SHOW_EXCEPTION_PAGE : IExceptionSettings.SHOW_INTERNAL_ERROR_PAGE); } /** * Framework settings */ private void setFrameworkSettings() { - getFrameworkSettings().setDetachListener(null); + getFrameworkSettings().setDetachListener(null); } /** * Markup settings */ private void setMarkupSettings() { - getMarkupSettings().setAutomaticLinking(false); - getMarkupSettings().setCompressWhitespace(optimize); - getMarkupSettings().setDefaultAfterDisabledLink("</strike"); - getMarkupSettings().setDefaultBeforeDisabledLink("<strike>"); - getMarkupSettings().setDefaultMarkupEncoding(DataContext.ENCODING); - // getMarkupSettings().setMarkupCache(???); - // getMarkupSettings().setMarkupParserFactory(???); - getMarkupSettings().setStripComments(optimize); - getMarkupSettings().setStripWicketTags(true); + getMarkupSettings().setAutomaticLinking(false); + getMarkupSettings().setCompressWhitespace(optimize); + getMarkupSettings().setDefaultAfterDisabledLink("</strike"); + getMarkupSettings().setDefaultBeforeDisabledLink("<strike>"); + getMarkupSettings().setDefaultMarkupEncoding(DataContext.ENCODING); + // getMarkupSettings().setMarkupCache(???); + // getMarkupSettings().setMarkupParserFactory(???); + getMarkupSettings().setStripComments(optimize); + getMarkupSettings().setStripWicketTags(true); - getMarkupSettings().setThrowExceptionOnMissingXmlDeclaration(false); + getMarkupSettings().setThrowExceptionOnMissingXmlDeclaration(false); } /** * Page settings */ private void setPageSettings() { - // getPageSettings().addComponentResolver(???); - getPageSettings().setVersionPagesByDefault(true); + // getPageSettings().addComponentResolver(???); + getPageSettings().setVersionPagesByDefault(true); } /** * Request cycle settings */ private void setRequestCycleSettings() { - // getRequestCycleSettings().addResponseFilter(???); - getRequestCycleSettings().setBufferResponse(true); - getRequestCycleSettings().setGatherExtendedBrowserInfo(false); - getRequestCycleSettings().setRenderStrategy(RenderStrategy.REDIRECT_TO_BUFFER); - getRequestCycleSettings().setResponseRequestEncoding(DataContext.ENCODING); - getRequestCycleSettings().setTimeout(WebContext.HTTP_TIME_OUT); + // getRequestCycleSettings().addResponseFilter(???); + getRequestCycleSettings().setBufferResponse(true); + getRequestCycleSettings().setGatherExtendedBrowserInfo(false); + getRequestCycleSettings().setRenderStrategy(RenderStrategy.REDIRECT_TO_BUFFER); + getRequestCycleSettings().setResponseRequestEncoding(DataContext.ENCODING); + getRequestCycleSettings().setTimeout(WebContext.HTTP_TIME_OUT); } /** * Request logger settings */ private void setRequestLoggerSettings() { - getRequestLoggerSettings().setRecordSessionSize(debug); - getRequestLoggerSettings().setRequestLoggerEnabled(debug); - getRequestLoggerSettings().setRequestsWindowSize(WebContext.HTTP_REQUEST_LOGGER_WINDOW_SIZE); + getRequestLoggerSettings().setRecordSessionSize(debug); + getRequestLoggerSettings().setRequestLoggerEnabled(debug); + getRequestLoggerSettings().setRequestsWindowSize(WebContext.HTTP_REQUEST_LOGGER_WINDOW_SIZE); } /** * Resource settings */ private void setResourceSettings() { - for (IStringResourceLoader message : messages) { - getResourceSettings().getStringResourceLoaders().add(message); - } - getResourceSettings().setDefaultCacheDuration(optimize ? WebContext.HTTP_CACHE_DURATION : Duration.NONE); + for (IStringResourceLoader message : messages) { + getResourceSettings().getStringResourceLoaders().add(message); + } + getResourceSettings().setDefaultCacheDuration(optimize ? WebContext.HTTP_CACHE_DURATION : Duration.NONE); - getResourceSettings().setJavaScriptCompressor(optimize ? new DefaultJavaScriptCompressor() : null); + getResourceSettings().setJavaScriptCompressor(optimize ? new DefaultJavaScriptCompressor() : null); - getResourceSettings().setCssCompressor(optimize ? new NoOpTextCompressor() : null); + getResourceSettings().setCssCompressor(optimize ? new NoOpTextCompressor() : null); - getResourceSettings().setParentFolderPlaceholder(null); - getResourceSettings().setResourcePollFrequency(null); + getResourceSettings().setParentFolderPlaceholder(null); + getResourceSettings().setResourcePollFrequency(null); - getResourceSettings().setThrowExceptionOnMissingResource(true); - getResourceSettings().setUseDefaultOnMissingResource(!debug); + getResourceSettings().setThrowExceptionOnMissingResource(true); + getResourceSettings().setUseDefaultOnMissingResource(!debug); } /** * Security settings */ private void setSecuritySettings() { - getSecuritySettings().setAuthorizationStrategy(new AuthStrategy()); + getSecuritySettings().setAuthorizationStrategy(new AuthStrategy()); - // Customize the cookie age for the authentification stategy - IAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy(WebContext.AUTH_COOKIE_KEY) { + // Customize the cookie age for the authentification stategy + IAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy(WebContext.AUTH_COOKIE_KEY) { - /** Cookie utils with custom settings */ - private CookieUtils cookieUtils; + /** Cookie utils with custom settings */ + private CookieUtils cookieUtils; - protected CookieUtils getCookieUtils() { - if (cookieUtils == null) { - cookieUtils = new CookieUtils(); - cookieUtils.getSettings().setMaxAge(WebContext.AUTH_COOKIE_MAX_AGE); - } - return cookieUtils; - } - }; - getSecuritySettings().setAuthenticationStrategy(authStrategy); + protected CookieUtils getCookieUtils() { + if (cookieUtils == null) { + cookieUtils = new CookieUtils(); + cookieUtils.getSettings().setMaxAge(WebContext.AUTH_COOKIE_MAX_AGE); + } + return cookieUtils; + } + }; + getSecuritySettings().setAuthenticationStrategy(authStrategy); - getSecuritySettings().setEnforceMounts(false); + getSecuritySettings().setEnforceMounts(false); } /** @@ -336,91 +336,91 @@ */ private void mountUrls() { - getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/list", ListCampagnesPage.class)); - mountPage("/campagne/list", ListCampagnesPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/edit", ManageCampagnePage.class)); - mountPage("/campagne/edit", ManageCampagnePage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/view", ReadCampagnePage.class)); - mountPage("/campagne/view", ReadCampagnePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/list", ListCampagnesPage.class)); + mountPage("/campagne/list", ListCampagnesPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/edit", ManageCampagnePage.class)); + mountPage("/campagne/edit", ManageCampagnePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/campagne/view", ReadCampagnePage.class)); + mountPage("/campagne/view", ReadCampagnePage.class); - getRootRequestMapperAsCompound().add( - new MountMapper("/config", new PackageMapper(PackageName.forClass(ListConfigurationPage.class)))); + getRootRequestMapperAsCompound().add( + new MountMapper("/config", new PackageMapper(PackageName.forClass(ListConfigurationPage.class)))); - getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/list", ListExtractionsPage.class)); - mountPage("/extraction/list", ListExtractionsPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/edit", ManageExtractionPage.class)); - mountPage("/extraction/edit", ManageExtractionPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/view", ReadExtractionPage.class)); - mountPage("/extraction/view", ReadExtractionPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/list", ListExtractionsPage.class)); + mountPage("/extraction/list", ListExtractionsPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/edit", ManageExtractionPage.class)); + mountPage("/extraction/edit", ManageExtractionPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/extraction/view", ReadExtractionPage.class)); + mountPage("/extraction/view", ReadExtractionPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/lot/list", ListLotsPage.class)); - mountPage("/lot/list", ListLotsPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/lot/edit", ManageLotPage.class)); - mountPage("/lot/edit", ManageLotPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/lot/view", ReadLotPage.class)); - mountPage("/lot/view", ReadLotPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/lot/list", ListLotsPage.class)); + mountPage("/lot/list", ListLotsPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/lot/edit", ManageLotPage.class)); + mountPage("/lot/edit", ManageLotPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/lot/view", ReadLotPage.class)); + mountPage("/lot/view", ReadLotPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/personne/list", ListPersonnesPage.class)); - mountPage("/personne/list", ListPersonnesPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/personne/edit", ManagePersonnePage.class)); - mountPage("/personne/edit", ManagePersonnePage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/personne/view", ReadPersonnePage.class)); - mountPage("/personne/view", ReadPersonnePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/personne/list", ListPersonnesPage.class)); + mountPage("/personne/list", ListPersonnesPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/personne/edit", ManagePersonnePage.class)); + mountPage("/personne/edit", ManagePersonnePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/personne/view", ReadPersonnePage.class)); + mountPage("/personne/view", ReadPersonnePage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/purification/list", ListPurificationsPage.class)); - mountPage("/purification/list", ListPurificationsPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/purification/edit", ManagePurificationPage.class)); - mountPage("/purification/edit", ManagePurificationPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/purification/view", ReadPurificationPage.class)); - mountPage("/purification/view", ReadPurificationPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/purification/list", ListPurificationsPage.class)); + mountPage("/purification/list", ListPurificationsPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/purification/edit", ManagePurificationPage.class)); + mountPage("/purification/edit", ManagePurificationPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/purification/view", ReadPurificationPage.class)); + mountPage("/purification/view", ReadPurificationPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/list", ListSpecimensPage.class)); - mountPage("/specimen/list", ListSpecimensPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/edit", ManageSpecimenPage.class)); - mountPage("/specimen/edit", ManageSpecimenPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/view", ReadSpecimenPage.class)); - mountPage("/specimen/view", ReadSpecimenPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/list", ListSpecimensPage.class)); + mountPage("/specimen/list", ListSpecimensPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/edit", ManageSpecimenPage.class)); + mountPage("/specimen/edit", ManageSpecimenPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/specimen/view", ReadSpecimenPage.class)); + mountPage("/specimen/view", ReadSpecimenPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/station/list", ListStationsPage.class)); - mountPage("/station/list", ListStationsPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/station/edit", ManageStationPage.class)); - mountPage("/station/edit", ManageStationPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/station/view", ReadStationPage.class)); - mountPage("/station/view", ReadStationPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/station/list", ListStationsPage.class)); + mountPage("/station/list", ListStationsPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/station/edit", ManageStationPage.class)); + mountPage("/station/edit", ManageStationPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/station/view", ReadStationPage.class)); + mountPage("/station/view", ReadStationPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/list", ListMoleculesPage.class)); - mountPage("/molecule/list", ListMoleculesPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/edit", ManageMoleculePage.class)); - mountPage("/molecule/edit", ManageMoleculePage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/view", ReadMoleculePage.class)); - mountPage("/molecule/view", ReadMoleculePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/list", ListMoleculesPage.class)); + mountPage("/molecule/list", ListMoleculesPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/edit", ManageMoleculePage.class)); + mountPage("/molecule/edit", ManageMoleculePage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/molecule/view", ReadMoleculePage.class)); + mountPage("/molecule/view", ReadMoleculePage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/list", ListTestsBioPage.class)); - mountPage("/testBio/list", ListTestsBioPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/edit", ManageTestBioPage.class)); - mountPage("/testBio/edit", ManageTestBioPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/view", ReadTestBioPage.class)); - mountPage("/testBio/view", ReadTestBioPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/list", ListTestsBioPage.class)); + mountPage("/testBio/list", ListTestsBioPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/edit", ManageTestBioPage.class)); + mountPage("/testBio/edit", ManageTestBioPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/testBio/view", ReadTestBioPage.class)); + mountPage("/testBio/view", ReadTestBioPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/document/edit", ManageDocumentPage.class)); - mountPage("/document/edit", ManageDocumentPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/document/view", ReadDocumentPage.class)); - mountPage("/document/view", ReadDocumentPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/document/edit", ManageDocumentPage.class)); + mountPage("/document/edit", ManageDocumentPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/document/view", ReadDocumentPage.class)); + mountPage("/document/view", ReadDocumentPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/utilisateur/edit", ManageUtilisateurPage.class)); - mountPage("/utilisateur/edit", ManageUtilisateurPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/utilisateur/update", UpdateUtilisateurPage.class)); - mountPage("/utilisateur/update", UpdateUtilisateurPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/utilisateur/edit", ManageUtilisateurPage.class)); + mountPage("/utilisateur/edit", ManageUtilisateurPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/utilisateur/update", UpdateUtilisateurPage.class)); + mountPage("/utilisateur/update", UpdateUtilisateurPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/contact", ContactPage.class)); - mountPage("/contact", ContactPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/register", RegisterPage.class)); - mountPage("/register", RegisterPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/passwordLost", ResetPasswordPage.class)); - mountPage("/passwordLost", ResetPasswordPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/contact", ContactPage.class)); + mountPage("/contact", ContactPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/register", RegisterPage.class)); + mountPage("/register", RegisterPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/passwordLost", ResetPasswordPage.class)); + mountPage("/passwordLost", ResetPasswordPage.class); - getRootRequestMapperAsCompound().add(new MountedMapper("/search", SearchPage.class)); - mountPage("/search", SearchPage.class); + getRootRequestMapperAsCompound().add(new MountedMapper("/search", SearchPage.class)); + mountPage("/search", SearchPage.class); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebContext.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebContext.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/config/WebContext.java 2013-02-18 07:27:17 UTC (rev 119) @@ -78,84 +78,102 @@ * Logger */ private static final Logger LOG = LoggerFactory.getLogger(WebContext.class); - + /** * Cookie key for authentification */ public static final String AUTH_COOKIE_KEY = "LoggedIn"; + /** * Cookie max age for authentification */ public static final int AUTH_COOKIE_MAX_AGE = (int) Duration.days(1).seconds(); + /** * Countries: Locale -> country code + country name (sorted by country name) */ public static final Map<Locale, Map<String, String>> COUNTRIES; + /** * Country codes: Locale -> country code (sorted by country name) */ public static final Map<Locale, List<String>> COUNTRY_CODES; + /** * HTTP cache duraction */ public static final Duration HTTP_CACHE_DURATION = Duration.days(1); + /** * HTTP maximum upload */ public static final Bytes HTTP_MAXIMUM_UPLOAD = Bytes.megabytes(1); + /** * HTTP request logger window size */ public static final int HTTP_REQUEST_LOGGER_WINDOW_SIZE = 2000; + /** * HTTP session max page maps */ public static final int HTTP_SESSION_MAX_PAGE_MAPS = 5; + /** * HTTP time out */ public static final Duration HTTP_TIME_OUT = Duration.seconds(30); + /** * Référentiels codes */ public static final List<Integer> REFERENTIEL_CODES = new ArrayList<Integer>(DataContext.REFERENTIELS.keySet()); + /** * Percent format precision */ public static final int PERCENT_PRECISION = 2; + /** * The maximum number of digits allowed in the fraction portion of doubles * */ public static final int DOUBLE_MAX_FRACTION_DIGIT = 3; + /** * The maximum rows number displayed for a list page */ public static final int ROWS_PER_PAGE = 20; + /** * Message source for data layer */ @Resource(name = "dataMessageSource") private MessageSourceAccessor dataMessageSource; + /** * Validator factory of the data layer */ @Resource(name = "validatorFactory") private ValidatorFactory validatorFactory; + /** * Debug mode */ @Value("${app.debug}") protected boolean appDebugProperty; + /** * Optimize mode */ @Value("${app.optimize}") protected boolean appOptimizeProperty; + /** * Wicket configuration string ("development" or "deployment") */ @Value("${wicket.configuration}") protected String wicketConfiguration; + /** * Log4j configuration filepath */ @@ -163,39 +181,39 @@ protected String log4jConfig; static { - Map<Locale, Map<String, String>> countries = new HashMap<Locale, Map<String, String>>( - DataContext.LOCALES.size()); - Map<Locale, List<String>> countryCodes = new HashMap<Locale, List<String>>(DataContext.LOCALES.size()); - for (Locale locale : DataContext.LOCALES) { - // Build (country code + country name) list - List<Pair<String, Pair<String, String>>> sortedCountryList = new ArrayList<Pair<String, Pair<String, String>>>( - DataContext.COUNTRY_CODES.size()); - for (String countryCode : DataContext.COUNTRY_CODES) { - String countryName = new Locale(locale.getLanguage(), countryCode).getDisplayCountry(locale); - sortedCountryList.add(new Pair<String, Pair<String, String>>(countryCode, new Pair<String, String>( - StringTools.replaceAccents(countryName), countryName))); - } - // Sort by name (country code + country name) list - Collections.sort(sortedCountryList, new Comparator<Pair<String, Pair<String, String>>>() { - @Override - public int compare(Pair<String, Pair<String, String>> pair1, Pair<String, Pair<String, String>> pair2) { - return String.CASE_INSENSITIVE_ORDER.compare(pair1.getValue().getKey(), pair2.getValue().getKey()); - } - }); - // Build (locale -> (country code + country name)) map (sorted by - // name) - // Build (locale -> (country code)) map (sorted by name) - Map<String, String> sortedCountryMap = new LinkedHashMap<String, String>(sortedCountryList.size()); - List<String> sortedCountryCodesList = new ArrayList<String>(sortedCountryList.size()); - for (Pair<String, Pair<String, String>> countryPair : sortedCountryList) { - sortedCountryMap.put(countryPair.getKey(), countryPair.getValue().getValue()); - sortedCountryCodesList.add(countryPair.getKey()); - } - countries.put(locale, Collections.unmodifiableMap(sortedCountryMap)); - countryCodes.put(locale, Collections.unmodifiableList(sortedCountryCodesList)); - } - COUNTRIES = Collections.unmodifiableMap(countries); - COUNTRY_CODES = Collections.unmodifiableMap(countryCodes); + Map<Locale, Map<String, String>> countries = new HashMap<Locale, Map<String, String>>(DataContext.LOCALES + .size()); + Map<Locale, List<String>> countryCodes = new HashMap<Locale, List<String>>(DataContext.LOCALES.size()); + for (Locale locale : DataContext.LOCALES) { + // Build (country code + country name) list + List<Pair<String, Pair<String, String>>> sortedCountryList = new ArrayList<Pair<String, Pair<String, String>>>( + DataContext.COUNTRY_CODES.size()); + for (String countryCode : DataContext.COUNTRY_CODES) { + String countryName = new Locale(locale.getLanguage(), countryCode).getDisplayCountry(locale); + sortedCountryList.add(new Pair<String, Pair<String, String>>(countryCode, new Pair<String, String>( + StringTools.replaceAccents(countryName), countryName))); + } + // Sort by name (country code + country name) list + Collections.sort(sortedCountryList, new Comparator<Pair<String, Pair<String, String>>>() { + @Override + public int compare(Pair<String, Pair<String, String>> pair1, Pair<String, Pair<String, String>> pair2) { + return String.CASE_INSENSITIVE_ORDER.compare(pair1.getValue().getKey(), pair2.getValue().getKey()); + } + }); + // Build (locale -> (country code + country name)) map (sorted by + // name) + // Build (locale -> (country code)) map (sorted by name) + Map<String, String> sortedCountryMap = new LinkedHashMap<String, String>(sortedCountryList.size()); + List<String> sortedCountryCodesList = new ArrayList<String>(sortedCountryList.size()); + for (Pair<String, Pair<String, String>> countryPair : sortedCountryList) { + sortedCountryMap.put(countryPair.getKey(), countryPair.getValue().getValue()); + sortedCountryCodesList.add(countryPair.getKey()); + } + countries.put(locale, Collections.unmodifiableMap(sortedCountryMap)); + countryCodes.put(locale, Collections.unmodifiableList(sortedCountryCodesList)); + } + COUNTRIES = Collections.unmodifiableMap(countries); + COUNTRY_CODES = Collections.unmodifiableMap(countryCodes); } /** @@ -203,13 +221,13 @@ */ @Bean public MessageSourceAccessor webMessageSource() { - // The ResourceBundleMessageSource does not handle UTF-8, so we use the - // Reloadable one - ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource(); - source.setBasename("web"); - source.setDefaultEncoding(DataContext.ENCODING); - source.setCacheSeconds(-1); - return new MessageSourceAccessor(source); + // The ResourceBundleMessageSource does not handle UTF-8, so we use the + // Reloadable one + ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource(); + source.setBasename("web"); + source.setDefaultEncoding(DataContext.ENCODING); + source.setCacheSeconds(-1); + return new MessageSourceAccessor(source); } /** @@ -217,7 +235,7 @@ */ @Bean public ModelValidator webModelValidator() { - return new ModelValidatorImpl(validatorFactory, webMessageSource(), dataMessageSource); + return new ModelValidatorImpl(validatorFactory, webMessageSource(), dataMessageSource); } /** @@ -225,10 +243,10 @@ */ @Bean public WebApplication webApplication() { - RuntimeConfigurationType runtimeWicketConf = RuntimeConfigurationType - .valueOf(wicketConfiguration.toUpperCase()); - return new WebApplicationImpl(appDebugProperty, appOptimizeProperty, runtimeWicketConf, new WebMessages( - dataMessageSource), new WebMessages(webMessageSource())); + RuntimeConfigurationType runtimeWicketConf = RuntimeConfigurationType + .valueOf(wicketConfiguration.toUpperCase()); + return new WebApplicationImpl(appDebugProperty, appOptimizeProperty, runtimeWicketConf, new WebMessages( + dataMessageSource), new WebMessages(webMessageSource())); } /** @@ -237,18 +255,17 @@ */ @Bean public static PropertySourcesPlaceholderConfigurer properties() { - PropertySourcesPlaceholderConfigurer pspc = - new PropertySourcesPlaceholderConfigurer(); - try { - pspc.setProperties(CantharellaConfig.getProperties()); - } catch (ArgumentsParserException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - pspc.setIgnoreUnresolvablePlaceholders(true); - return pspc; + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + try { + pspc.setProperties(CantharellaConfig.getProperties()); + } catch (ArgumentsParserException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; } - + /** * Init the log4j configuration filepath * @@ -256,6 +273,6 @@ */ @PostConstruct public void initLog4j() throws FileNotFoundException { - Log4jConfigurer.initLogging(log4jConfig); + Log4jConfigurer.initLogging(log4jConfig); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/ContactPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/ContactPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/ContactPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -60,86 +60,87 @@ private PersonneService personneService; /** Validateur modèle */ - @SpringBean(name = "webModelValidator") private ModelValidator validator; + @SpringBean(name = "webModelValidator") + private ModelValidator validator; /** * Constructeur */ public ContactPage() { - super(ContactPage.class); + super(ContactPage.class); - // AuthMode = the user is authenticated, we already know his e-mail, the form is not protected with a captcha - final boolean authMode = getSession().getRole() != AuthRole.VISITOR; + // AuthMode = the user is authenticated, we already know his e-mail, the form is not protected with a captcha + final boolean authMode = getSession().getRole() != AuthRole.VISITOR; - // Models initialization - final IModel<ContactModel> contactModel = new Model<ContactModel>(new ContactModel()); - final IModel<CaptchaModel> captchaModel = new Model<CaptchaModel>(new CaptchaModel()); - if (!authMode) { - captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); - } + // Models initialization + final IModel<ContactModel> contactModel = new Model<ContactModel>(new ContactModel()); + final IModel<CaptchaModel> captchaModel = new Model<CaptchaModel>(new CaptchaModel()); + if (!authMode) { + captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); + } - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - // ContactModel fields - formView.add(new TextField<String>("ContactModel.mail", authMode ? new Model<String>(getSession() - .getUtilisateur().getCourriel()) : new PropertyModel<String>(contactModel, "mail")) - .setEnabled(!authMode)); - formView.add(new TextField<String>("ContactModel.subject", new PropertyModel<String>(contactModel, "subject"))); - formView.add(new TextArea<String>("ContactModel.message", new PropertyModel<String>(contactModel, "message"))); + // ContactModel fields + formView.add(new TextField<String>("ContactModel.mail", authMode ? new Model<String>(getSession() + .getUtilisateur().getCourriel()) : new PropertyModel<String>(contactModel, "mail")) + .setEnabled(!authMode)); + formView.add(new TextField<String>("ContactModel.subject", new PropertyModel<String>(contactModel, "subject"))); + formView.add(new TextArea<String>("ContactModel.message", new PropertyModel<String>(contactModel, "message"))); - // CaptchaModel fields - MarkupContainer captcha = new WebMarkupContainer("captcha"); - captcha.setVisibilityAllowed(!authMode); - captcha.add(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel.getObject() - .getCaptchaTextGenerated()))); - final Component captchaTextView = new TextField<String>("CaptchaModel.captchaText", new PropertyModel<String>( - captchaModel, "captchaText")); - captcha.add(captchaTextView); - formView.add(captcha); + // CaptchaModel fields + MarkupContainer captcha = new WebMarkupContainer("captcha"); + captcha.setVisibilityAllowed(!authMode); + captcha.add(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel.getObject() + .getCaptchaTextGenerated()))); + final Component captchaTextView = new TextField<String>("CaptchaModel.captchaText", new PropertyModel<String>( + captchaModel, "captchaText")); + captcha.add(captchaTextView); + formView.add(captcha); - // Action button - formView.add(new SubmittableButton(ACTION_SEND, new SubmittableButtonEvents() { + // Action button + formView.add(new SubmittableButton(ACTION_SEND, new SubmittableButtonEvents() { - @Override - public void onProcess() throws EmailException { - personneService.sendMailAdmins(contactModel.getObject().getSubject(), contactModel.getObject() - .getMessage(), contactModel.getObject().getMail()); - } + @Override + public void onProcess() throws EmailException { + personneService.sendMailAdmins(contactModel.getObject().getSubject(), contactModel.getObject() + .getMessage(), contactModel.getObject().getMail()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_SEND); + @Override + public void onSuccess() { + successNextPage(ACTION_SEND); - setResponsePage(getApplication().getHomePage()); - } + setResponsePage(getApplication().getHomePage()); + } - @Override - public void onValidate() { - // Enforce the sender e-mail in authMode - if (authMode) { - contactModel.getObject().setMail(getSession().getUtilisateur().getCourriel()); - } + @Override + public void onValidate() { + // Enforce the sender e-mail in authMode + if (authMode) { + contactModel.getObject().setMail(getSession().getUtilisateur().getCourriel()); + } - // Validate ContactModel - addValidationErrors(validator.validate(contactModel.getObject(), getSession().getLocale())); + // Validate ContactModel + addValidationErrors(validator.validate(contactModel.getObject(), getSession().getLocale())); - // Validate CaptchaModel - if (!authMode && !captchaModel.getObject().validate()) { - errorCurrentPage(captchaTextView); - } - } + // Validate CaptchaModel + if (!authMode && !captchaModel.getObject().validate()) { + errorCurrentPage(captchaTextView); + } + } - /** - * Reset the captcha, on each page reload - */ - /** - * private void resetCaptcha() { if (!authMode) { captchaModel.getObject().setCaptchaText(null); - * captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); formView.replace(new - * NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource( - * captchaModel.getObject().getCaptchaTextGenerated()))); } } - **/ - })); + /** + * Reset the captcha, on each page reload + */ + /** + * private void resetCaptcha() { if (!authMode) { captchaModel.getObject().setCaptchaText(null); + * captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); formView.replace(new + * NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource( + * captchaModel.getObject().getCaptchaTextGenerated()))); } } + **/ + })); - add(formView); + add(formView); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/HomePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/HomePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/HomePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -127,236 +127,237 @@ * Constructeur */ public HomePage() { - super(HomePage.class); - addVisitorContent(); - addUserContent(); - addAdminContent(); + super(HomePage.class); + addVisitorContent(); + addUserContent(); + addAdminContent(); } /** * Ajour du contenu administrateur */ private void addAdminContent() { - final AuthContainer adminContent = new AuthContainer("Content.ADMIN", AuthRole.ADMIN); - if (adminContent.isAuthorized()) { + final AuthContainer adminContent = new AuthContainer("Content.ADMIN", AuthRole.ADMIN); + if (adminContent.isAuthorized()) { - // Affiche les utilisateurs à valider sur la page d'accueil ADMIN - final MarkupContainer invalidUtilisateursView = new WebMarkupContainer("InvalidUtilisateurs.List"); - invalidUtilisateursView.setOutputMarkupId(true); + // Affiche les utilisateurs à valider sur la page d'accueil ADMIN + final MarkupContainer invalidUtilisateursView = new WebMarkupContainer("InvalidUtilisateurs.List"); + invalidUtilisateursView.setOutputMarkupId(true); - final List<Utilisateur> utilisateursInvalid = personneService.listUtilisateursInvalid(); - invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); - if (invalidUtilisateursView.isVisibilityAllowed()) { - invalidUtilisateursView.add(new DataView<Utilisateur>("InvalidUtilisateurs.List.Utilisateur", - new LoadableDetachableSortableListDataProvider<Utilisateur>(utilisateursInvalid, getSession() - .getLocale())) { - @Override - protected void populateItem(Item<Utilisateur> item) { - Utilisateur utilisateur = item.getModelObject(); - item.add(new Label("InvalidUtilisateurs.List.Utilisateur.Label", utilisateur.toString())); + final List<Utilisateur> utilisateursInvalid = personneService.listUtilisateursInvalid(); + invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); + if (invalidUtilisateursView.isVisibilityAllowed()) { + invalidUtilisateursView.add(new DataView<Utilisateur>("InvalidUtilisateurs.List.Utilisateur", + new LoadableDetachableSortableListDataProvider<Utilisateur>(utilisateursInvalid, getSession() + .getLocale())) { + @Override + protected void populateItem(Item<Utilisateur> item) { + Utilisateur utilisateur = item.getModelObject(); + item.add(new Label("InvalidUtilisateurs.List.Utilisateur.Label", utilisateur.toString())); - // Action : valider l'utilisateur - item.add(new AjaxFallbackLink<Utilisateur>("InvalidUtilisateurs.List.Utilisateur.Valid", - new Model<Utilisateur>(utilisateur)) { - @Override - public void onClick(AjaxRequestTarget target) { - try { - // Validation - personneService.validAndUpdateUtilisateur(getModelObject()); - successCurrentPage(ManageUtilisateurPage.class, "Update"); + // Action : valider l'utilisateur + item.add(new AjaxFallbackLink<Utilisateur>("InvalidUtilisateurs.List.Utilisateur.Valid", + new Model<Utilisateur>(utilisateur)) { + @Override + public void onClick(AjaxRequestTarget target) { + try { + // Validation + personneService.validAndUpdateUtilisateur(getModelObject()); + successCurrentPage(ManageUtilisateurPage.class, "Update"); - // Mise à jour de la liste - CollectionTools.setter(utilisateursInvalid, - personneService.listUtilisateursInvalid()); - invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); - if (target != null) { - target.add(invalidUtilisateursView); - } - } catch (DataConstraintException e) { - errorCurrentPage(ManageUtilisateurPage.class, "Update", e); - } - refreshFeedbackPage(target); - } - }); + // Mise à jour de la liste + CollectionTools.setter(utilisateursInvalid, personneService + .listUtilisateursInvalid()); + invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); + if (target != null) { + target.add(invalidUtilisateursView); + } + } catch (DataConstraintException e) { + errorCurrentPage(ManageUtilisateurPage.class, "Update", e); + } + refreshFeedbackPage(target); + } + }); - // Action : mettre à jour l'utilisateur (redirection vers le formulaire) - item.add(new Link<Utilisateur>("InvalidUtilisateurs.List.Utilisateur.Update", - new Model<Utilisateur>(utilisateur)) { - @Override - public void onClick() { - setResponsePage(new ManageUtilisateurPage(getModelObject().getIdPersonne(), - new CallerPage(HomePage.class))); - } - }); + // Action : mettre à jour l'utilisateur (redirection vers le formulaire) + item.add(new Link<Utilisateur>("InvalidUtilisateurs.List.Utilisateur.Update", + new Model<Utilisateur>(utilisateur)) { + @Override + public void onClick() { + setResponsePage(new ManageUtilisateurPage(getModelObject().getIdPersonne(), + new CallerPage(HomePage.class))); + } + }); - // Action : supprimer l'utilisateur - Link<Utilisateur> deleteLink = new AjaxFallbackLink<Utilisateur>( - "InvalidUtilisateurs.List.Utilisateur.Reject", new Model<Utilisateur>(utilisateur)) { - @Override - public void onClick(AjaxRequestTarget target) { - // Suppression - personneService.rejectUtilisateur(getModelObject()); - successCurrentPage(ManageUtilisateurPage.class, "Reject"); + // Action : supprimer l'utilisateur + Link<Utilisateur> deleteLink = new AjaxFallbackLink<Utilisateur>( + "InvalidUtilisateurs.List.Utilisateur.Reject", new Model<Utilisateur>(utilisateur)) { + @Override + public void onClick(AjaxRequestTarget target) { + // Suppression + personneService.rejectUtilisateur(getModelObject()); + successCurrentPage(ManageUtilisateurPage.class, "Reject"); - // Mise à jour de la liste - CollectionTools.setter(utilisateursInvalid, personneService.listUtilisateursInvalid()); - invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); - if (target != null) { - target.add(invalidUtilisateursView); - } - refreshFeedbackPage(target); - } - }; - deleteLink.add(new JSConfirmationBehavior(getString("Confirm"))); - item.add(deleteLink); - } - }); + // Mise à jour de la liste + CollectionTools.setter(utilisateursInvalid, personneService.listUtilisateursInvalid()); + invalidUtilisateursView.setVisibilityAllowed(!utilisateursInvalid.isEmpty()); + if (target != null) { + target.add(invalidUtilisateursView); + } + refreshFeedbackPage(target); + } + }; + deleteLink.add(new JSConfirmationBehavior(getString("Confirm"))); + item.add(deleteLink); + } + }); - } + } - adminContent.add(invalidUtilisateursView); + adminContent.add(invalidUtilisateursView); - } - add(adminContent); + } + add(adminContent); } /** * Ajour du contenu utilisateur (s'affiche également pour l'admin) */ private void addUserContent() { - AuthContainer userContent = new AuthContainer("Content.USER", AuthRole.USER, AuthRole.ADMIN); - if (userContent.isAuthorized()) { - userContent.add(new Label(getResource() + ".Statistics.Personnes", String.valueOf(personneService - .countPersonnes()))); - userContent.add(new Label(getResource() + ".Statistics.Campagnes", String.valueOf(campagneService - .countCampagnes()))); - userContent.add(new Label(getResource() + ".Statistics.Stations", String.valueOf(stationService - .countStations()))); - userContent.add(new Label(getResource() + ".Statistics.Specimens", String.valueOf(specimenService - .countSpecimens()))); - userContent.add(new Label(getResource() + ".Statistics.Lots", String.valueOf(lotService.countLots()))); - userContent.add(new Label(getResource() + ".Statistics.Extractions", String.valueOf(extractionService - .countExtractions()))); - userContent.add(new Label(getResource() + ".Statistics.Purifications", String.valueOf(purificationService - .countPurifications()))); - userContent.add(new Label(getResource() + ".Statistics.TestsBio", String.valueOf(testBioService - .countResultatsTestsBio()))); + AuthContainer userContent = new AuthContainer("Content.USER", AuthRole.USER, AuthRole.ADMIN); + if (userContent.isAuthorized()) { + userContent.add(new Label(getResource() + ".Statistics.Personnes", String.valueOf(personneService + .countPersonnes()))); + userContent.add(new Label(getResource() + ".Statistics.Campagnes", String.valueOf(campagneService + .countCampagnes()))); + userContent.add(new Label(getResource() + ".Statistics.Stations", String.valueOf(stationService + .countStations()))); + userContent.add(new Label(getResource() + ".Statistics.Specimens", String.valueOf(specimenService + .countSpecimens()))); + userContent.add(new Label(getResource() + ".Statistics.Lots", String.valueOf(lotService.countLots()))); + userContent.add(new Label(getResource() + ".Statistics.Extractions", String.valueOf(extractionService + .countExtractions()))); + userContent.add(new Label(getResource() + ".Statistics.Purifications", String.valueOf(purificationService + .countPurifications()))); + userContent.add(new Label(getResource() + ".Statistics.TestsBio", String.valueOf(testBioService + .countResultatsTestsBio()))); - // affichage du volet droits - Link<Utilisateur> detailsRight = new Link<Utilisateur>("HomePage.Rights.User.Details", - new Model<Utilisateur>(getSession().getUtilisateur())) { - @Override - public void onClick() { - setResponsePage(new ReadUtilisateurPage(getModelObject().getIdPersonne(), new CallerPage( - HomePage.this))); - } + // affichage du volet droits + Link<Utilisateur> detailsRight = new Link<Utilisateur>("HomePage.Rights.User.Details", + new Model<Utilisateur>(getSession().getUtilisateur())) { + @Override + public void onClick() { + setResponsePage(new ReadUtilisateurPage(getModelObject().getIdPersonne(), new CallerPage( + HomePage.this))); + } - /** {@inheritDoc} */ - @Override - protected CharSequence getURL() { - return super.getURL() + "#rights"; - } + /** {@inheritDoc} */ + @Override + protected CharSequence getURL() { + return super.getURL() + "#rights"; + } - }; - userContent.add(detailsRight); + }; + userContent.add(detailsRight); - if (getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - userContent.add(new Label("HomePage.Rights.User1", getString("HomePage.Rights.Admin"))); - // pas d'affichage du lien de détails - detailsRight.setVisibilityAllowed(false); - EmptyPanel rights2 = new EmptyPanel("HomePage.Rights.User2"); - rights2.setVisibilityAllowed(false); - userContent.add(rights2); - } else { - // pour l'utilisateur simple, nb de campagnes et de lots accessibles affichés - Integer nbCampagnesDroits = getSession().getUtilisateur().getCampagnesDroits().size(); - Integer nbLotsDroits = getSession().getUtilisateur().getLotsDroits().size(); - String msgRights = MessageFormat.format(getString("HomePage.Rights.User"), nbCampagnesDroits, - nbLotsDroits); - userContent.add(new Label("HomePage.Rights.User1", msgRights)); + if (getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + userContent.add(new Label("HomePage.Rights.User1", getString("HomePage.Rights.Admin"))); + // pas d'affichage du lien de détails + detailsRight.setVisibilityAllowed(false); + EmptyPanel rights2 = new EmptyPanel("HomePage.Rights.User2"); + rights2.setVisibilityAllowed(false); + userContent.add(rights2); + } else { + // pour l'utilisateur simple, nb de campagnes et de lots accessibles affichés + Integer nbCampagnesDroits = getSession().getUtilisateur().getCampagnesDroits().size(); + Integer nbLotsDroits = getSession().getUtilisateur().getLotsDroits().size(); + String msgRights = MessageFormat.format(getString("HomePage.Rights.User"), nbCampagnesDroits, + nbLotsDroits); + userContent.add(new Label("HomePage.Rights.User1", msgRights)); - Integer nbCampagnesCrees = getSession().getUtilisateur().getCampagnesCreees().size(); - String msgRights2 = MessageFormat.format(getString("HomePage.Rights.User2"), nbCampagnesCrees); - Label rights2 = new Label("HomePage.Rights.User2", msgRights2); - rights2.setVisibilityAllowed(nbCampagnesCrees != 0); - userContent.add(rights2); - } - } - add(userContent); + Integer nbCampagnesCrees = getSession().getUtilisateur().getCampagnesCreees().size(); + String msgRights2 = MessageFormat.format(getString("HomePage.Rights.User2"), nbCampagnesCrees); + Label rights2 = new Label("HomePage.Rights.User2", msgRights2); + rights2.setVisibilityAllowed(nbCampagnesCrees != 0); + userContent.add(rights2); + } + } + add(userContent); } /** * Ajout du contenu visiteur */ private void addVisitorContent() { - AuthContainer visitorContent = new AuthContainer("Content.VISITOR", AuthRole.VISITOR); - if (visitorContent.isAuthorized()) { + AuthContainer visitorContent = new AuthContainer("Content.VISITOR", AuthRole.VISITOR); + if (visitorContent.isAuthorized()) { - // Initialisation des modèles pour la connexion - final IModel<LoginModel> loginModel = new Model<LoginModel>(new LoginModel()); - final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); + // Initialisation des modèles pour la connexion + final IModel<LoginModel> loginModel = new Model<LoginModel>(new LoginModel()); + final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); - // Formulaire de connexion - final Form<Void> formView = new Form<Void>("Form"); + // Formulaire de connexion + final Form<Void> formView = new Form<Void>("Form"); - // Champs du formulaire - formView.add(new TextField<String>("Personne.courriel", new PropertyModel<String>(utilisateurModel, - "courriel"))); - formView.add(new PasswordTextField("LoginModel.password", new PropertyModel<String>(loginModel, "password")) - .setRequired(false)); - formView.add(new CheckBox("LoginModel.rememberMe", new PropertyModel<Boolean>(loginModel, "rememberMe"))); + // Champs du formulaire + formView.add(new TextField<String>("Personne.courriel", new PropertyModel<String>(utilisateurModel, + "courriel"))); + formView + .add(new PasswordTextField("LoginModel.password", new PropertyModel<String>(loginModel, "password")) + .setRequired(false)); + formView.add(new CheckBox("LoginModel.rememberMe", new PropertyModel<Boolean>(loginModel, "rememberMe"))); - // Action : connexion - formView.add(new SubmittableButton(ACTION_LOGIN, new SubmittableButtonEvents() { + // Action : connexion + formView.add(new SubmittableButton(ACTION_LOGIN, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataNotFoundException, DataConstraintException { - if (getSession().authenticate(utilisateurModel.getObject().getCourriel(), - personneService.hashPassword(loginModel.getObject().getPassword()))) { - Utilisateur user = personneService.loadUtilisateur(utilisateurModel.getObject().getCourriel()); - getSession().connectUser(user, loginModel.getObject().getRememberMe()); - LOG.info("connexion de l'utilisateur : " + user.getPrenom() + " " + user.getNom()); - } else { - // si échec dans l'authentification - if (CollectionTools.containsWithValue(personneService.listUtilisateursInvalid(), "courriel", - AccessType.GETTER, utilisateurModel.getObject().getCourriel())) { - // si le courriel est celui d'un utilisateur non validé, message d'erreur approprié - error(getString("HomePage.Login.NotYetValid")); - } else { - error(getString("HomePage.Login.KO")); - } - // Ràz du mot de passe - loginModel.getObject().setPassword(null); - } - } + @Override + public void onProcess() throws DataNotFoundException, DataConstraintException { + if (getSession().authenticate(utilisateurModel.getObject().getCourriel(), + personneService.hashPassword(loginModel.getObject().getPassword()))) { + Utilisateur user = personneService.loadUtilisateur(utilisateurModel.getObject().getCourriel()); + getSession().connectUser(user, loginModel.getObject().getRememberMe()); + LOG.info("connexion de l'utilisateur : " + user.getPrenom() + " " + user.getNom()); + } else { + // si échec dans l'authentification + if (CollectionTools.containsWithValue(personneService.listUtilisateursInvalid(), "courriel", + AccessType.GETTER, utilisateurModel.getObject().getCourriel())) { + // si le courriel est celui d'un utilisateur non validé, message d'erreur approprié + error(getString("HomePage.Login.NotYetValid")); + } else { + error(getString("HomePage.Login.KO")); + } + // Ràz du mot de passe + loginModel.getObject().setPassword(null); + } + } - @Override - public void onSuccess() { - successNextPage(ACTION_LOGIN); - setResponsePage(getApplication().getHomePage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_LOGIN); + setResponsePage(getApplication().getHomePage()); + } - @Override - public void onValidate() { - // Validate Utilisateur - addValidationErrors(validator.validate(utilisateurModel.getObject(), getSession().getLocale(), - "courriel")); - // Validate LoginModel - addValidationErrors(validator.validate(loginModel.getObject(), getSession().getLocale(), - "password", "rememberMe")); - } - })); + @Override + public void onValidate() { + // Validate Utilisateur + addValidationErrors(validator.validate(utilisateurModel.getObject(), getSession().getLocale(), + "courriel")); + // Validate LoginModel + addValidationErrors(validator.validate(loginModel.getObject(), getSession().getLocale(), + "password", "rememberMe")); + } + })); - // Lien pour regénérer le mot de passe - formView.add(new BookmarkablePageLink<Void>(ResetPasswordPage.class.getSimpleName(), - ResetPasswordPage.class)); + // Lien pour regénérer le mot de passe + formView.add(new BookmarkablePageLink<Void>(ResetPasswordPage.class.getSimpleName(), + ResetPasswordPage.class)); - // Lien pour s'enregistrer - visitorContent.add(new BookmarkablePageLink<Void>(RegisterPage.class.getSimpleName(), RegisterPage.class)); + // Lien pour s'enregistrer + visitorContent.add(new BookmarkablePageLink<Void>(RegisterPage.class.getSimpleName(), RegisterPage.class)); - visitorContent.add(formView); + visitorContent.add(formView); - } - add(visitorContent); + } + add(visitorContent); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/TemplatePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/TemplatePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/TemplatePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -117,58 +117,58 @@ * @param page Page (permet de construire la "resource" qui servira d'identifiant à la page) */ protected TemplatePage(Class<? extends TemplatePage> page) { - super(new PageParameters()); - AssertTools.assertNotNull(page); - resource = page.getSimpleName(); - addPageTitles(); - add(new BookmarkablePageLink<Void>(HomePage.class.getSimpleName(), getApplication().getHomePage())); - add(createUserSatellite()); - add(createUserSearch()); - add(createVisitorMenu()); - add(createUserMenu()); - createLanguageLinks(); - feedbackPanelContainer = new WebMarkupContainer("FeedbackPageContainer"); - feedbackPanelContainer.add(new FeedbackPanel("FeedbackPage")); - feedbackPanelContainer.setOutputMarkupId(true); - add(feedbackPanelContainer); - add(new Label("Year", YEAR)); - add(new BookmarkablePageLink<Void>(ContactPage.class.getSimpleName(), ContactPage.class)); - setVersioned(true); + super(new PageParameters()); + AssertTools.assertNotNull(page); + resource = page.getSimpleName(); + addPageTitles(); + add(new BookmarkablePageLink<Void>(HomePage.class.getSimpleName(), getApplication().getHomePage())); + add(createUserSatellite()); + add(createUserSearch()); + add(createVisitorMenu()); + add(createUserMenu()); + createLanguageLinks(); + feedbackPanelContainer = new WebMarkupContainer("FeedbackPageContainer"); + feedbackPanelContainer.add(new FeedbackPanel("FeedbackPage")); + feedbackPanelContainer.setOutputMarkupId(true); + add(feedbackPanelContainer); + add(new Label("Year", YEAR)); + add(new BookmarkablePageLink<Void>(ContactPage.class.getSimpleName(), ContactPage.class)); + setVersioned(true); } /** {@inheritDoc} */ public void renderHead(IHeaderResponse response) { - // dynamic declaration of the menu Css due to the internationalization - response.render(CssHeaderItem.forUrl(getString("TemplatePage.Css.Menu"))); + // dynamic declaration of the menu Css due to the internationalization + response.render(CssHeaderItem.forUrl(getString("TemplatePage.Css.Menu"))); - // scroll up to the anchor if any feedback message - if (!getSession().getFeedbackMessages().isEmpty()) { - response.render(OnDomReadyHeaderItem.forScript("location.hash='header'")); - // LOG.debug("session FeedbackMessages is not empty"); - // for (FeedbackMessage msg : getSession().getFeedbackMessages()) { - // LOG.debug(msg.getLevelAsString() + " : " + msg.getMessage() + ", from : " + msg.getReporter()); - // } - } + // scroll up to the anchor if any feedback message + if (!getSession().getFeedbackMessages().isEmpty()) { + response.render(OnDomReadyHeaderItem.forScript("location.hash='header'")); + // LOG.debug("session FeedbackMessages is not empty"); + // for (FeedbackMessage msg : getSession().getFeedbackMessages()) { + // LOG.debug(msg.getLevelAsString() + " : " + msg.getMessage() + ", from : " + msg.getReporter()); + // } + } } /** * Création des liens vers les sélections de langue */ private void createLanguageLinks() { - this.add(new Link<Void>("SelectFrenchLang") { - // Cas où on clique sur le drapeau français - @Override - public void onClick() { - this.getSession().setLocale(Locale.FRENCH); - } - }); - this.add(new Link<Void>("SelectEnglishLang") { - // Cas où on clique sur le drapeau anglais - @Override - public void onClick() { - this.getSession().setLocale(Locale.ENGLISH); - } - }); + this.add(new Link<Void>("SelectFrenchLang") { + // Cas où on clique sur le drapeau français + @Override + public void onClick() { + this.getSession().setLocale(Locale.FRENCH); + } + }); + this.add(new Link<Void>("SelectEnglishLang") { + // Cas où on clique sur le drapeau anglais + @Override + public void onClick() { + this.getSession().setLocale(Locale.ENGLISH); + } + }); } /** @@ -176,23 +176,23 @@ * @return Le conteneur */ private AuthContainer createUserSatellite() { - AuthContainer userSatellite = new AuthContainer("Satellite.USER", AuthRole.USER, AuthRole.ADMIN); - if (userSatellite.isAuthorized()) { - Link<Void> link = new BookmarkablePageLink<Void>(UpdateUtilisateurPage.class.getSimpleName(), - UpdateUtilisateurPage.class); + AuthContainer userSatellite = new AuthContainer("Satellite.USER", AuthRole.USER, AuthRole.ADMIN); + if (userSatellite.isAuthorized()) { + Link<Void> link = new BookmarkablePageLink<Void>(UpdateUtilisateurPage.class.getSimpleName(), + UpdateUtilisateurPage.class); - link.add(new Label("Utilisateur", new PropertyModel<String>(this, "session.utilisateur"))); - userSatellite.add(link); - userSatellite.add(new Link<Void>(TemplatePage.class.getSimpleName() + "." + ACTION_LOGOUT) { - @Override - public void onClick() { - ((AuthSession) getSession()).logout(); - successNextPage(TemplatePage.class, ACTION_LOGOUT); - setResponsePage(getApplication().getHomePage()); - } - }); - } - return userSatellite; + link.add(new Label("Utilisateur", new PropertyModel<String>(this, "session.utilisateur"))); + userSatellite.add(link); + userSatellite.add(new Link<Void>(TemplatePage.class.getSimpleName() + "." + ACTION_LOGOUT) { + @Override + public void onClick() { + ((AuthSession) getSession()).logout(); + successNextPage(TemplatePage.class, ACTION_LOGOUT); + setResponsePage(getApplication().getHomePage()); + } + }); + } + return userSatellite; } /** @@ -200,20 +200,21 @@ * @return Le conteneur */ private AuthContainer createUserSearch() { - AuthContainer userSatellite = new AuthContainer("Search.USER", AuthRole.USER, AuthRole.ADMIN); + AuthContainer userSatellite = new AuthContainer("Search.USER", AuthRole.USER, AuthRole.ADMIN); - Form<ValueMap> searchForm = new Form<ValueMap>("Search.FORM", new CompoundPropertyModel<ValueMap>(new ValueMap())) { - protected void onSubmit() { - ValueMap values = getModelObject(); - - String query = values.getString("query"); - setResponsePage(new SearchPage(query)); - } - }; - searchForm.add(new TextField<String>("query").setType(String.class)); + Form<ValueMap> searchForm = new Form<ValueMap>("Search.FORM", new CompoundPropertyModel<ValueMap>( + new ValueMap())) { + protected void onSubmit() { + ValueMap values = getModelObject(); - userSatellite.add(searchForm); - return userSatellite; + String query = values.getString("query"); + setResponsePage(new SearchPage(query)); + } + }; + searchForm.add(new TextField<String>("query").setType(String.class)); + + userSatellite.add(searchForm); + return userSatellite; } /** @@ -221,8 +222,8 @@ * @return Le conteneur */ private AuthContainer createVisitorMenu() { - AuthContainer visitorMenu = new AuthContainer("Menu.VISITOR", AuthRole.VISITOR); - return visitorMenu; + AuthContainer visitorMenu = new AuthContainer("Menu.VISITOR", AuthRole.VISITOR); + return visitorMenu; } /** @@ -230,29 +231,32 @@ * @return Le conteneur */ private AuthContainer createUserMenu() { - AuthContainer userMenu = new AuthContainer("Menu.USER", AuthRole.USER, AuthRole.ADMIN); - if (userMenu.isAuthorized()) { + AuthContainer userMenu = new AuthContainer("Menu.USER", AuthRole.USER, AuthRole.ADMIN); + if (userMenu.isAuthorized()) { - userMenu.add(createAdminMenu()); + userMenu.add(createAdminMenu()); - userMenu.add(new BookmarkablePageLink<Void>(ListPersonnesPage.class.getSimpleName(), - ListPersonnesPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListCampagnesPage.class.getSimpleName(), - ListCampagnesPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListStationsPage.class.getSimpleName(), ListStationsPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListLotsPage.class.getSimpleName(), ListLotsPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListSpecimensPage.class.getSimpleName(), - ListSpecimensPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListExtractionsPage.class.getSimpleName(), - ListExtractionsPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListPurificationsPage.class.getSimpleName(), - ListPurificationsPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListMoleculesPage.class.getSimpleName(), ListMoleculesPage.class)); - userMenu.add(new BookmarkablePageLink<Void>(ListTestsBioPage.class.getSimpleName(), ListTestsBioPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListPersonnesPage.class.getSimpleName(), + ListPersonnesPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListCampagnesPage.class.getSimpleName(), + ListCampagnesPage.class)); + userMenu + .add(new BookmarkablePageLink<Void>(ListStationsPage.class.getSimpleName(), ListStationsPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListLotsPage.class.getSimpleName(), ListLotsPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListSpecimensPage.class.getSimpleName(), + ListSpecimensPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListExtractionsPage.class.getSimpleName(), + ListExtractionsPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListPurificationsPage.class.getSimpleName(), + ListPurificationsPage.class)); + userMenu.add(new BookmarkablePageLink<Void>(ListMoleculesPage.class.getSimpleName(), + ListMoleculesPage.class)); + userMenu + .add(new BookmarkablePageLink<Void>(ListTestsBioPage.class.getSimpleName(), ListTestsBioPage.class)); - // userMenu.add(new BookmarkablePageLink<Void>(SandboxPage.class.getSimpleName(), SandboxPage.class)); - } - return userMenu; + // userMenu.add(new BookmarkablePageLink<Void>(SandboxPage.class.getSimpleName(), SandboxPage.class)); + } + return userMenu; } /** @@ -260,22 +264,22 @@ * @return Le conteneur */ private AuthContainer createAdminMenu() { - AuthContainer adminMenu = new AuthContainer("Menu.ADMIN", AuthRole.ADMIN); - if (adminMenu.isAuthorized()) { - adminMenu.add(new BookmarkablePageLink<Void>(ListConfigurationPage.class.getSimpleName(), - ListConfigurationPage.class)); - } - return adminMenu; + AuthContainer adminMenu = new AuthContainer("Menu.ADMIN", AuthRole.ADMIN); + if (adminMenu.isAuthorized()) { + adminMenu.add(new BookmarkablePageLink<Void>(ListConfigurationPage.class.getSimpleName(), + ListConfigurationPage.class)); + } + return adminMenu; } /** * Add page titles (in head and body) */ private void addPageTitles() { - String page = getString(getResource()); + String page = getString(getResource()); - add(new Label("PageTitleHead", String.format(PATTERN_PANEL_PAGE_TITLE_HEAD, page))); - add(new Label("PageTitleBody", page)); + add(new Label("PageTitleHead", String.format(PATTERN_PANEL_PAGE_TITLE_HEAD, page))); + add(new Label("PageTitleBody", page)); } /** @@ -283,9 +287,9 @@ * @param violations Violations */ public final void addValidationErrors(Collection<String> violations) { - for (String violation : violations) { - error(violation); - } + for (String violation : violations) { + error(violation); + } } /** @@ -293,15 +297,15 @@ * @param violations Violations */ public final void addValidationErrors(List<Pair<String, String>> violations) { - for (Pair<String, String> violation : violations) { - String label = violation.getKey(); - try { - label = getString(label); - } catch (MissingResourceException e) { - // - } - error(String.format(PATTERN_ERROR_MESSAGE_VALIDATOR, label, violation.getValue())); - } + for (Pair<String, String> violation : violations) { + String label = violation.getKey(); + try { + label = getString(label); + } catch (MissingResourceException e) { + // + } + error(String.format(PATTERN_ERROR_MESSAGE_VALIDATOR, label, violation.getValue())); + } } /** @@ -311,13 +315,13 @@ * @param exception Exception */ public final void errorCurrentPage(Class<? extends TemplatePage> pageClass, String action, Exception exception) { - AssertTools.assertNotNull(pageClass); - AssertTools.assertNotEmpty(action); - AssertTools.assertNotNull(exception); - String errorMessage = getString(String.format(PATTERN_ERROR_ACTION_EXCEPTION, pageClass.getSimpleName(), - action, exception.getClass().getSimpleName())); - LOG.warn(errorMessage); - error(errorMessage); + AssertTools.assertNotNull(pageClass); + AssertTools.assertNotEmpty(action); + AssertTools.assertNotNull(exception); + String errorMessage = getString(String.format(PATTERN_ERROR_ACTION_EXCEPTION, pageClass.getSimpleName(), + action, exception.getClass().getSimpleName())); + LOG.warn(errorMessage); + error(errorMessage); } /** @@ -325,15 +329,15 @@ * @param component Component */ public final void errorCurrentPage(Component component) { - AssertTools.assertNotNull(component); - String errorMessage = String.format(PATTERN_ERROR_MESSAGE, component.getId()); - try { - errorMessage = getString(errorMessage); - } catch (MissingResourceException e) { - // - } - LOG.warn(errorMessage); - error(errorMessage); + AssertTools.assertNotNull(component); + String errorMessage = String.format(PATTERN_ERROR_MESSAGE, component.getId()); + try { + errorMessage = getString(errorMessage); + } catch (MissingResourceException e) { + // + } + LOG.warn(errorMessage); + error(errorMessage); } /** @@ -342,18 +346,18 @@ * @param exception Exception */ public final void errorCurrentPage(String action, Exception exception) { - AssertTools.assertNotEmpty(action); - AssertTools.assertNotNull(exception); - String errorMessage = getString(String.format(PATTERN_ERROR_ACTION_EXCEPTION, getResource(), action, exception - .getClass().getSimpleName())); - LOG.warn(errorMessage); - error(errorMessage); + AssertTools.assertNotEmpty(action); + AssertTools.assertNotNull(exception); + String errorMessage = getString(String.format(PATTERN_ERROR_ACTION_EXCEPTION, getResource(), action, exception + .getClass().getSimpleName())); + LOG.warn(errorMessage); + error(errorMessage); } /** {@inheritDoc} */ @Override public final String getAjaxIndicatorMarkupId() { - return ID_AJAX_INDICATOR; + return ID_AJAX_INDICATOR; } /** @@ -361,13 +365,13 @@ * @return resource */ protected final String getResource() { - return resource; + return resource; } /** {@inheritDoc} */ @Override public final AuthSession getSession() { - return (AuthSession) super.getSession(); + return (AuthSession) super.getSession(); } /** @@ -375,16 +379,16 @@ * @param target Ajax target */ protected final void refreshFeedbackPage(AjaxRequestTarget target) { - if (target != null) { - target.add(feedbackPanelContainer); - // scroll up to the anchor if any feedback message - if (!getSession().getFeedbackMessages().isEmpty()) { - LOG.debug("REFRESH FEEDBACK BY AJAX"); - target.appendJavaScript("window.location.hash = '#header';"); - // unless go back to button after scrolling up to the anchor - target.focusComponent(feedbackPanelContainer); - } - } + if (target != null) { + target.add(feedbackPanelContainer); + // scroll up to the anchor if any feedback message + if (!getSession().getFeedbackMessages().isEmpty()) { + LOG.debug("REFRESH FEEDBACK BY AJAX"); + target.appendJavaScript("window.location.hash = '#header';"); + // unless go back to button after scrolling up to the anchor + target.focusComponent(feedbackPanelContainer); + } + } } /** @@ -393,7 +397,7 @@ * @param action Action */ public final void successCurrentPage(Class<? extends TemplatePage> pageClass, String action) { - info(successMessage(pageClass, action)); + info(successMessage(pageClass, action)); } /** @@ -401,7 +405,7 @@ * @param action Action */ public final void successCurrentPage(String action) { - info(successMessage(action)); + info(successMessage(action)); } /** @@ -411,9 +415,9 @@ * @return Success message */ private String successMessage(Class<? extends TemplatePage> pageClass, String action) { - AssertTools.assertNotNull(pageClass); - AssertTools.assertNotEmpty(action); - return getString(String.format(PATTERN_SUCCESS_ACTION_MESSAGE, pageClass.getSimpleName(), action)); + AssertTools.assertNotNull(pageClass); + AssertTools.assertNotEmpty(action); + return getString(String.format(PATTERN_SUCCESS_ACTION_MESSAGE, pageClass.getSimpleName(), action)); } /** @@ -422,8 +426,8 @@ * @return Success message */ private String successMessage(String action) { - AssertTools.assertNotEmpty(action); - return getString(String.format(PATTERN_SUCCESS_ACTION_MESSAGE, getResource(), action)); + AssertTools.assertNotEmpty(action); + return getString(String.format(PATTERN_SUCCESS_ACTION_MESSAGE, getResource(), action)); } /** @@ -432,7 +436,7 @@ * @param action Action */ public final void successNextPage(Class<? extends TemplatePage> pageClass, String action) { - getSession().info(successMessage(pageClass, action)); + getSession().info(successMessage(pageClass, action)); } /** @@ -440,7 +444,7 @@ * @param action Action */ public final void successNextPage(String action) { - getSession().info(successMessage(action)); + getSession().info(successMessage(action)); } /** @@ -450,13 +454,13 @@ * @return Enum value message */ public final <E extends Enum<?>> String enumValueMessage(E enumValue) { - if (enumValue == null) { - return null; - } - String enumValueMessage = String.format(PATTERN_ENUM_VALUE_LABEL, enumValue.getClass().getSimpleName(), - enumValue.toString()); + if (enumValue == null) { + return null; + } + String enumValueMessage = String.format(PATTERN_ENUM_VALUE_LABEL, enumValue.getClass().getSimpleName(), + enumValue.toString()); - return getString(enumValueMessage); + return getString(enumValueMessage); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/LinkProduitPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/LinkProduitPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/LinkProduitPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,41 +54,41 @@ * @param page page used to get messages */ public LinkProduitPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - TemplatePage page) { - super(displayModel, sortProperty, propertyExpression); - this.page = page; + TemplatePage page) { + super(displayModel, sortProperty, propertyExpression); + this.page = page; } /** {@inheritDoc} */ @Override public void onClick(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { - if (model.getObject() != null) { - Produit prod = (Produit) BeanTools.getValue(model.getObject(), AccessType.GETTER, "produit"); + if (model.getObject() != null) { + Produit prod = (Produit) BeanTools.getValue(model.getObject(), AccessType.GETTER, "produit"); - if (prod.isExtrait()) { - Extrait extrait = (Extrait) prod; - onClickIfExtrait(extrait); - } else { - // le produit est une fraction - Fraction fraction = (Fraction) prod; - onClickIfFraction(fraction); - } - } + if (prod.isExtrait()) { + Extrait extrait = (Extrait) prod; + onClickIfExtrait(extrait); + } else { + // le produit est une fraction + Fraction fraction = (Fraction) prod; + onClickIfFraction(fraction); + } + } } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { - if (model.getObject() != null) { - // title différent suivant si le produit provient d'une extraction ou d'une purification - Produit prod = (Produit) BeanTools.getValue(model.getObject(), AccessType.GETTER, "produit"); - if (prod.isExtrait()) { - linkTitle = page.getString("ReadExtraction"); - } else { - linkTitle = page.getString("ReadPurification"); - } - } - super.populateItem(item, componentId, model); + if (model.getObject() != null) { + // title différent suivant si le produit provient d'une extraction ou d'une purification + Produit prod = (Produit) BeanTools.getValue(model.getObject(), AccessType.GETTER, "produit"); + if (prod.isExtrait()) { + linkTitle = page.getString("ReadExtraction"); + } else { + linkTitle = page.getString("ReadPurification"); + } + } + super.populateItem(item, componentId, model); } /** Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/TaxonomyPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/TaxonomyPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/columns/TaxonomyPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,7 +44,7 @@ * @param propertyExpression Property expression */ public TaxonomyPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression) { - super(displayModel, sortProperty, propertyExpression); + super(displayModel, sortProperty, propertyExpression); } /** @@ -53,14 +53,14 @@ * @param propertyExpression Property expression */ public TaxonomyPropertyColumn(IModel<String> displayModel, String propertyExpression) { - super(displayModel, propertyExpression); + super(displayModel, propertyExpression); } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> rowModel) { - Label label = new Label(componentId, getDataModel(rowModel)); - label.add(new AttributeModifier("class", new Model<String>("taxonomy"))); - item.add(label); + Label label = new Label(componentId, getDataModel(rowModel)); + label.add(new AttributeModifier("class", new Model<String>("taxonomy"))); + item.add(label); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ListCampagnesPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ListCampagnesPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ListCampagnesPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -68,79 +68,82 @@ * Constructeur */ public ListCampagnesPage() { - super(ListCampagnesPage.class); + super(ListCampagnesPage.class); - final CallerPage currentPage = new CallerPage(ListCampagnesPage.class); + final CallerPage currentPage = new CallerPage(ListCampagnesPage.class); - // Lien pour l'age d'une nouvelle campagne - add(new Link<Void>(getResource() + ".NewCampagne") { - @Override - public void onClick() { - setResponsePage(new ManageCampagnePage(currentPage, true)); - } + // Lien pour l'age d'une nouvelle campagne + add(new Link<Void>(getResource() + ".NewCampagne") { + @Override + public void onClick() { + setResponsePage(new ManageCampagnePage(currentPage, true)); + } - }); + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer campagnesRefresh = new WebMarkupContainer(getResource() + ".Campagnes.Refresh"); - campagnesRefresh.setOutputMarkupId(true); - add(campagnesRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer campagnesRefresh = new WebMarkupContainer(getResource() + ".Campagnes.Refresh"); + campagnesRefresh.setOutputMarkupId(true); + add(campagnesRefresh); - // Liste des campagnes - final List<Campagne> campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); + // Liste des campagnes + final List<Campagne> campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); - LoadableDetachableSortableListDataProvider<Campagne> campagnesDataProvider = new LoadableDetachableSortableListDataProvider<Campagne>( - campagnes, getSession().getLocale()); + LoadableDetachableSortableListDataProvider<Campagne> campagnesDataProvider = new LoadableDetachableSortableListDataProvider<Campagne>( + campagnes, getSession().getLocale()); - List<IColumn<Campagne, String>> columns = new ArrayList<IColumn<Campagne, String>>(); + List<IColumn<Campagne, String>> columns = new ArrayList<IColumn<Campagne, String>>(); - columns.add(new LinkableImagePropertyColumn<Campagne, String>("images/read.png", getString("Read"), getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { - setResponsePage(new ReadCampagnePage(model.getObject().getIdCampagne(), currentPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Campagne, String>("images/read.png", getString("Read"), + getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { + setResponsePage(new ReadCampagnePage(model.getObject().getIdCampagne(), currentPage)); + } + }); - columns.add(new LinkPropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.nom")), "nom", "nom", - getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { - setResponsePage(new ReadCampagnePage(model.getObject().getIdCampagne(), currentPage)); - } - }); + columns.add(new LinkPropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.nom")), "nom", + "nom", getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { + setResponsePage(new ReadCampagnePage(model.getObject().getIdCampagne(), currentPage)); + } + }); - columns.add(new ShortDatePropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.dateDeb")), "dateDeb", - "dateDeb", getLocale())); + columns.add(new ShortDatePropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.dateDeb")), + "dateDeb", "dateDeb", getLocale())); - columns.add(new ShortDatePropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.dateFin")), "dateFin", - "dateFin", getLocale())); + columns.add(new ShortDatePropertyColumn<Campagne, String>(new Model<String>(getString("Campagne.dateFin")), + "dateFin", "dateFin", getLocale())); - columns.add(new MapValuePropertyColumn<Campagne, String, String>(new Model<String>(getString("Campagne.codePays")), - "codePays", "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))); + columns.add(new MapValuePropertyColumn<Campagne, String, String>(new Model<String>( + getString("Campagne.codePays")), "codePays", "codePays", WebContext.COUNTRIES.get(getSession() + .getLocale()))); - columns.add(new LinkableImagePropertyColumn<Campagne, String>("images/edit.png", getString("Update"), - getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { - if (campagneService.updateOrdeleteCampagneEnabled(model.getObject(), getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + columns.add(new LinkableImagePropertyColumn<Campagne, String>("images/edit.png", getString("Update"), + getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { + if (campagneService.updateOrdeleteCampagneEnabled(model.getObject(), getSession().getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { - setResponsePage(new ManageCampagnePage(model.getObject().getIdCampagne(), currentPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<Campagne>> item, String componentId, IModel<Campagne> model) { + setResponsePage(new ManageCampagnePage(model.getObject().getIdCampagne(), currentPage)); + } + }); - final DataTable<Campagne, String> campagnesDataTable = new AjaxFallbackDefaultDataTable<Campagne, String>( - "ListCampagnesPage.Campagnes", columns, campagnesDataProvider, WebContext.ROWS_PER_PAGE); - campagnesDataTable.addBottomToolbar(new TableExportToolbar(campagnesDataTable, "campagnes", getSession().getLocale())); - campagnesRefresh.add(campagnesDataTable); + final DataTable<Campagne, String> campagnesDataTable = new AjaxFallbackDefaultDataTable<Campagne, String>( + "ListCampagnesPage.Campagnes", columns, campagnesDataProvider, WebContext.ROWS_PER_PAGE); + campagnesDataTable.addBottomToolbar(new TableExportToolbar(campagnesDataTable, "campagnes", getSession() + .getLocale())); + campagnesRefresh.add(campagnesDataTable); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ManageCampagnePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ManageCampagnePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ManageCampagnePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -89,7 +89,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManageCampagnePage extends TemplatePage { /** Action : create */ @@ -162,7 +162,7 @@ * @param multipleEntry Saisie multiple */ public ManageCampagnePage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -171,7 +171,7 @@ * @param callerPage Page appelante */ public ManageCampagnePage(Integer idCampagne, CallerPage callerPage) { - this(idCampagne, null, callerPage, false); + this(idCampagne, null, callerPage, false); } /** @@ -180,7 +180,7 @@ * @param callerPage Page appelante */ public ManageCampagnePage(Campagne campagne, CallerPage callerPage) { - this(null, campagne, callerPage, true); + this(null, campagne, callerPage, true); } /** @@ -193,147 +193,148 @@ * @param multipleEntry Saisie multiple */ private ManageCampagnePage(Integer idCampagne, Campagne campagne, final CallerPage callerPage, boolean multipleEntry) { - super(ManageCampagnePage.class); - assert idCampagne == null || campagne == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManageCampagnePage.class); + assert idCampagne == null || campagne == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - // Initialisation des modèles - try { - campagneModel = new Model<Campagne>(idCampagne == null && campagne == null ? new Campagne() - : campagne != null ? campagne : campagneService.loadCampagne(idCampagne)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - boolean createMode = idCampagne == null; - if (createMode) { - campagneModel.getObject().setCreateur(getSession().getUtilisateur()); - } - participantModel = new Model<CampagnePersonneParticipant>(new CampagnePersonneParticipant()); - participantModel.getObject().getId().setPk1(campagneModel.getObject()); - stationModel = new Model<Station>(new Station()); + // Initialisation des modèles + try { + campagneModel = new Model<Campagne>(idCampagne == null && campagne == null ? new Campagne() + : campagne != null ? campagne : campagneService.loadCampagne(idCampagne)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + boolean createMode = idCampagne == null; + if (createMode) { + campagneModel.getObject().setCreateur(getSession().getUtilisateur()); + } + participantModel = new Model<CampagnePersonneParticipant>(new CampagnePersonneParticipant()); + participantModel.getObject().getId().setPk1(campagneModel.getObject()); + stationModel = new Model<Station>(new Station()); - // Initialisation des listes - List<String> programmes = campagneService.listCampagneProgrammes(); - personnes = personneService.listPersonnes(); - stations = stationService.listStations(getSession().getUtilisateur()); + // Initialisation des listes + List<String> programmes = campagneService.listCampagneProgrammes(); + personnes = personneService.listPersonnes(); + stations = stationService.listStations(getSession().getUtilisateur()); - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("Campagne.nom", new PropertyModel<String>(campagneModel, "nom"))); + formView.add(new TextField<String>("Campagne.nom", new PropertyModel<String>(campagneModel, "nom"))); - // Choix du code pays - formView.add(new DropDownChoice<String>("Campagne.codePays", new PropertyModel<String>(campagneModel, - "codePays"), WebContext.COUNTRY_CODES.get(getSession().getLocale()), - new MapChoiceRenderer<String, String>(WebContext.COUNTRIES.get(getSession().getLocale())))); - if (campagneModel.getObject().getCodePays() == null) { - campagneModel.getObject().setCodePays( - WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); - } + // Choix du code pays + formView.add(new DropDownChoice<String>("Campagne.codePays", new PropertyModel<String>(campagneModel, + "codePays"), WebContext.COUNTRY_CODES.get(getSession().getLocale()), + new MapChoiceRenderer<String, String>(WebContext.COUNTRIES.get(getSession().getLocale())))); + if (campagneModel.getObject().getCodePays() == null) { + campagneModel.getObject().setCodePays( + WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); + } - // Champs de type Date - formView.add(new DateTextField("Campagne.dateDeb", new PropertyModel<Date>(campagneModel, "dateDeb")) - .add(new DatePicker())); + // Champs de type Date + formView.add(new DateTextField("Campagne.dateDeb", new PropertyModel<Date>(campagneModel, "dateDeb")) + .add(new DatePicker())); - formView.add(new DateTextField("Campagne.dateFin", new PropertyModel<Date>(campagneModel, "dateFin")) - .add(new DatePicker())); + formView.add(new DateTextField("Campagne.dateFin", new PropertyModel<Date>(campagneModel, "dateFin")) + .add(new DatePicker())); - formView.add(new TextArea<String>("Campagne.mentionLegale", new PropertyModel<String>(campagneModel, - "mentionLegale"))); - formView.add(new SimpleTooltipPanel("Campagne.mentionLegale.info", new Model<String>( - getString("Campagne.mentionLegale.info")))); + formView.add(new TextArea<String>("Campagne.mentionLegale", new PropertyModel<String>(campagneModel, + "mentionLegale"))); + formView.add(new SimpleTooltipPanel("Campagne.mentionLegale.info", new Model<String>( + getString("Campagne.mentionLegale.info")))); - formView.add(new TextArea<String>("Campagne.complement", new PropertyModel<String>(campagneModel, "complement"))); - formView.add(new SimpleTooltipPanel("Campagne.complement.info", new Model<String>( - getString("Campagne.complement.info")))); + formView + .add(new TextArea<String>("Campagne.complement", new PropertyModel<String>(campagneModel, "complement"))); + formView.add(new SimpleTooltipPanel("Campagne.complement.info", new Model<String>( + getString("Campagne.complement.info")))); - formView.add(new TextField<String>("Campagne.createur", new PropertyModel<String>(campagneModel, "createur")) - .setEnabled(false)); + formView.add(new TextField<String>("Campagne.createur", new PropertyModel<String>(campagneModel, "createur")) + .setEnabled(false)); - // Champs en lecture seule - formView.add(new AutoCompleteTextFieldString("Campagne.programme", new PropertyModel<String>(campagneModel, - "programme"), programmes, ComparisonMode.CONTAINS)); + // Champs en lecture seule + formView.add(new AutoCompleteTextFieldString("Campagne.programme", new PropertyModel<String>(campagneModel, + "programme"), programmes, ComparisonMode.CONTAINS)); - initParticipantsFields(formView); - initStationsFields(formView); + initParticipantsFields(formView); + initStationsFields(formView); - // Action : création de la campagne - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - campagneService.createCampagne(campagneModel.getObject()); - } + // Action : création de la campagne + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + campagneService.createCampagne(campagneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : mise à jour de la campagne - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - campagneService.updateCampagne(campagneModel.getObject()); - } + // Action : mise à jour de la campagne + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + campagneService.updateCampagne(campagneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode - && campagneService.updateOrdeleteCampagneEnabled(campagneModel.getObject(), getSession() - .getUtilisateur())); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode + && campagneService.updateOrdeleteCampagneEnabled(campagneModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateButton); - // Action : suppression de la campagne - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - campagneService.deleteCampagne(campagneModel.getObject()); - } + // Action : suppression de la campagne + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + campagneService.deleteCampagne(campagneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(!createMode - && campagneService.updateOrdeleteCampagneEnabled(campagneModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(!createMode + && campagneService.updateOrdeleteCampagneEnabled(campagneModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - // Action : annulation (lien) - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) this.getPage()); - } - }); + // Action : annulation (lien) + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) this.getPage()); + } + }); - cleanPersonnesChoice(); - cleanStationsChoice(); - add(formView); + cleanPersonnesChoice(); + cleanStationsChoice(); + add(formView); } /** @@ -341,112 +342,112 @@ * @param formView The form view */ private void initParticipantsFields(final Form<Void> formView) { - // Tableau des participants - final MarkupContainer participantsTable = new WebMarkupContainer("Campagne.participants.Table"); - participantsTable.setOutputMarkupId(true); + // Tableau des participants + final MarkupContainer participantsTable = new WebMarkupContainer("Campagne.participants.Table"); + participantsTable.setOutputMarkupId(true); - // Liste des participants ajoutés - participantsTable.add(new ListView<CampagnePersonneParticipant>("Campagne.participants.List", - new PropertyModel<List<CampagnePersonneParticipant>>(campagneModel, "participants")) { - @Override - protected void populateItem(ListItem<CampagnePersonneParticipant> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des participants ajoutés + participantsTable.add(new ListView<CampagnePersonneParticipant>("Campagne.participants.List", + new PropertyModel<List<CampagnePersonneParticipant>>(campagneModel, "participants")) { + @Override + protected void populateItem(ListItem<CampagnePersonneParticipant> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final CampagnePersonneParticipant participant = item.getModelObject(); - // Colonnes - item.add(new Label("Campagne.participants.List.personne", new PropertyModel<String>(participant, - "id.pk2"))); - item.add(new Label("Campagne.participants.List.complement", new PropertyModel<String>(participant, - "complement"))); + final CampagnePersonneParticipant participant = item.getModelObject(); + // Colonnes + item.add(new Label("Campagne.participants.List.personne", new PropertyModel<String>(participant, + "id.pk2"))); + item.add(new Label("Campagne.participants.List.complement", new PropertyModel<String>(participant, + "complement"))); - // Action : suppression d'un participant - Button deleteButton = new AjaxFallbackButton("Campagne.participants.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - campagneModel.getObject().getParticipants().remove(participant); - cleanPersonnesChoice(); + // Action : suppression d'un participant + Button deleteButton = new AjaxFallbackButton("Campagne.participants.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + campagneModel.getObject().getParticipants().remove(participant); + cleanPersonnesChoice(); - // Mise à jour des listes - refreshModel(); - if (target != null) { - target.add(participantsTable, availablePersonnes); - } - } + // Mise à jour des listes + refreshModel(); + if (target != null) { + target.add(participantsTable, availablePersonnes); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - // Liste des personnes "disponibles" (non encore ajoutées dans la liste des participants) - availablePersonnes = new DropDownChoice<Personne>("Campagne.participant", new PropertyModel<Personne>( - participantModel, "id.pk2"), new ArrayList<Personne>(), new PersonneRenderer()); - availablePersonnes.setNullValid(false); - availablePersonnes.setOutputMarkupId(true); + // Liste des personnes "disponibles" (non encore ajoutées dans la liste des participants) + availablePersonnes = new DropDownChoice<Personne>("Campagne.participant", new PropertyModel<Personne>( + participantModel, "id.pk2"), new ArrayList<Personne>(), new PersonneRenderer()); + availablePersonnes.setNullValid(false); + availablePersonnes.setOutputMarkupId(true); - participantsTable.add(availablePersonnes); + participantsTable.add(availablePersonnes); - complementView = new TextField<String>("CampagnePersonneParticipant.complement", new PropertyModel<String>( - participantModel, "complement")); - participantsTable.add(complementView); + complementView = new TextField<String>("CampagnePersonneParticipant.complement", new PropertyModel<String>( + participantModel, "complement")); + participantsTable.add(complementView); - // Bouton AJAX pour ajouter un participant - addParticipant = new AjaxFallbackButton("Campagne.participants.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - if (participantModel.getObject().getId().getPk2() != null) { - try { - // Ajout du participant - campagneModel.getObject().getParticipants().add(participantModel.getObject().clone()); - cleanPersonnesChoice(); - // réinit de la ligne d'ajout - participantModel.getObject().getId().setPk2(null); - participantModel.getObject().setComplement(null); - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Bouton AJAX pour ajouter un participant + addParticipant = new AjaxFallbackButton("Campagne.participants.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + if (participantModel.getObject().getId().getPk2() != null) { + try { + // Ajout du participant + campagneModel.getObject().getParticipants().add(participantModel.getObject().clone()); + cleanPersonnesChoice(); + // réinit de la ligne d'ajout + participantModel.getObject().getId().setPk2(null); + participantModel.getObject().setComplement(null); + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - // Mise à jour des listes - refreshModel(); - if (target != null) { - target.add(participantsTable, availablePersonnes); - } - } - } + // Mise à jour des listes + refreshModel(); + if (target != null) { + target.add(participantsTable, availablePersonnes); + } + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - participantsTable.add(addParticipant); + }; + participantsTable.add(addParticipant); - formView.add(participantsTable); + formView.add(participantsTable); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - participantsTable.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + participantsTable.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } + }); } /** @@ -454,211 +455,211 @@ * @param formView The form view */ private void initStationsFields(final Form<Void> formView) { - // Tableau des participants - final MarkupContainer stationsTable = new WebMarkupContainer("Campagne.stations.Table"); - stationsTable.setOutputMarkupId(true); + // Tableau des participants + final MarkupContainer stationsTable = new WebMarkupContainer("Campagne.stations.Table"); + stationsTable.setOutputMarkupId(true); - // Liste des stations ajoutées - stationsTable.add(new ListView<Station>("Campagne.stations.List", new PropertyModel<List<Station>>( - campagneModel, "sortedStations")) { - @Override - protected void populateItem(ListItem<Station> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des stations ajoutées + stationsTable.add(new ListView<Station>("Campagne.stations.List", new PropertyModel<List<Station>>( + campagneModel, "sortedStations")) { + @Override + protected void populateItem(ListItem<Station> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final Station station = item.getModelObject(); - // Colonnes - item.add(new Label("Campagne.stations.List.station", new PropertyModel<String>(station, "nom")) - .add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.codePays", new DisplayMapValuePropertyModel<String>(station, - "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))) - .add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.localite", new PropertyModel<String>(station, "localite")) - .add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.latitude", new PropertyModel<String>(station, "latitude")) - .add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.longitude", new PropertyModel<String>(station, "longitude")) - .add(new ReplaceEmptyLabelBehavior())); + final Station station = item.getModelObject(); + // Colonnes + item.add(new Label("Campagne.stations.List.station", new PropertyModel<String>(station, "nom")) + .add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.codePays", new DisplayMapValuePropertyModel<String>(station, + "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))) + .add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.localite", new PropertyModel<String>(station, "localite")) + .add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.latitude", new PropertyModel<String>(station, "latitude")) + .add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.longitude", new PropertyModel<String>(station, "longitude")) + .add(new ReplaceEmptyLabelBehavior())); - // Action : suppression d'une station - Button deleteButton = new AjaxFallbackButton("Campagne.stations.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - campagneModel.getObject().getStations().remove(station); - cleanStationsChoice(); + // Action : suppression d'une station + Button deleteButton = new AjaxFallbackButton("Campagne.stations.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + campagneModel.getObject().getStations().remove(station); + cleanStationsChoice(); - // Mise à jour des listes - refreshModel(); - if (target != null) { - target.add(stationsTable, availableStations); - } - } + // Mise à jour des listes + refreshModel(); + if (target != null) { + target.add(stationsTable, availableStations); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - // Liste des stations "disponibles" (non encore ajoutées dans la liste des stations) - availableStations = new DropDownChoice<Station>("Campagne.station", stationModel, new ArrayList<Station>()); - availableStations.setNullValid(false); - availableStations.setOutputMarkupId(true); + // Liste des stations "disponibles" (non encore ajoutées dans la liste des stations) + availableStations = new DropDownChoice<Station>("Campagne.station", stationModel, new ArrayList<Station>()); + availableStations.setNullValid(false); + availableStations.setOutputMarkupId(true); - stationsTable.add(availableStations); + stationsTable.add(availableStations); - final Label codePaysLabel = new Label("Campagne.station.codePays", new DisplayMapValuePropertyModel<String>( - stationModel, "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))); - codePaysLabel.setOutputMarkupId(true); - stationsTable.add(codePaysLabel); + final Label codePaysLabel = new Label("Campagne.station.codePays", new DisplayMapValuePropertyModel<String>( + stationModel, "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))); + codePaysLabel.setOutputMarkupId(true); + stationsTable.add(codePaysLabel); - final Label localiteLabel = new Label("Campagne.station.localite", new PropertyModel<String>(stationModel, - "localite")); - localiteLabel.setOutputMarkupId(true); - stationsTable.add(localiteLabel); + final Label localiteLabel = new Label("Campagne.station.localite", new PropertyModel<String>(stationModel, + "localite")); + localiteLabel.setOutputMarkupId(true); + stationsTable.add(localiteLabel); - final Label latitudeLabel = new Label("Campagne.station.latitude", new PropertyModel<String>(stationModel, - "latitude")); - latitudeLabel.setOutputMarkupId(true); - stationsTable.add(latitudeLabel); + final Label latitudeLabel = new Label("Campagne.station.latitude", new PropertyModel<String>(stationModel, + "latitude")); + latitudeLabel.setOutputMarkupId(true); + stationsTable.add(latitudeLabel); - final Label longitudeLabel = new Label("Campagne.station.longitude", new PropertyModel<String>(stationModel, - "longitude")); - longitudeLabel.setOutputMarkupId(true); - stationsTable.add(longitudeLabel); + final Label longitudeLabel = new Label("Campagne.station.longitude", new PropertyModel<String>(stationModel, + "longitude")); + longitudeLabel.setOutputMarkupId(true); + stationsTable.add(longitudeLabel); - availableStations.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - target.add(codePaysLabel, localiteLabel, latitudeLabel, longitudeLabel); - } - }); + availableStations.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + target.add(codePaysLabel, localiteLabel, latitudeLabel, longitudeLabel); + } + }); - // Bouton AJAX pour ajouter une station - addStation = new AjaxFallbackButton("Campagne.stations.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - if (stationModel.getObject() != null) { - try { - // Ajout du participant - participantModel.getObject().setComplement(complementView.getValue()); - campagneModel.getObject().getStations().add(stationModel.getObject().clone()); - cleanStationsChoice(); - // réinit de la ligne d'ajout - stationModel.setObject(new Station()); - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Bouton AJAX pour ajouter une station + addStation = new AjaxFallbackButton("Campagne.stations.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + if (stationModel.getObject() != null) { + try { + // Ajout du participant + participantModel.getObject().setComplement(complementView.getValue()); + campagneModel.getObject().getStations().add(stationModel.getObject().clone()); + cleanStationsChoice(); + // réinit de la ligne d'ajout + stationModel.setObject(new Station()); + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - // Mise à jour des listes - refreshModel(); - if (target != null) { - target.add(stationsTable, availableStations); - } - } - } + // Mise à jour des listes + refreshModel(); + if (target != null) { + target.add(stationsTable, availableStations); + } + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - stationsTable.add(addStation); + }; + stationsTable.add(addStation); - formView.add(stationsTable); + formView.add(stationsTable); - // Action : création d'une nouvelle station - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - stationsTable.add(new AjaxSubmitLink("NewStation") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManageStationPage(new CallerPage((TemplatePage) getPage()), false)); - } + // Action : création d'une nouvelle station + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + stationsTable.add(new AjaxSubmitLink("NewStation") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManageStationPage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageStationPage(new CallerPage((TemplatePage) getPage()), false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageStationPage(new CallerPage((TemplatePage) getPage()), false)); + } + }); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Station, Spécimen ou Campagne) - refreshModel(); - super.onBeforeRender(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Station, Spécimen ou Campagne) + refreshModel(); + super.onBeforeRender(); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection vers l'écran de saisie d'une nouvelle campagne, en fournissant déjà quelques données - Campagne nextCampagne = new Campagne(); + if (multipleEntry) { + // Redirection vers l'écran de saisie d'une nouvelle campagne, en fournissant déjà quelques données + Campagne nextCampagne = new Campagne(); - nextCampagne.setCodePays(campagneModel.getObject().getCodePays()); - nextCampagne.setProgramme(campagneModel.getObject().getProgramme()); - nextCampagne.setMentionLegale(campagneModel.getObject().getMentionLegale()); - setResponsePage(new ManageCampagnePage(nextCampagne, callerPage)); - } else if (callerPage != null) { - // On passe la campagne associée à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Campagne.class.getSimpleName(), campagneModel.getObject().getIdCampagne()); - callerPage.responsePage(this); - } + nextCampagne.setCodePays(campagneModel.getObject().getCodePays()); + nextCampagne.setProgramme(campagneModel.getObject().getProgramme()); + nextCampagne.setMentionLegale(campagneModel.getObject().getMentionLegale()); + setResponsePage(new ManageCampagnePage(nextCampagne, callerPage)); + } else if (callerPage != null) { + // On passe la campagne associée à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Campagne.class.getSimpleName(), campagneModel.getObject().getIdCampagne()); + callerPage.responsePage(this); + } } /** * Mets à jour les personnes disponibles (non encore ajoutées) */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Personne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(personnes, personneService.listPersonnes()); - cleanPersonnesChoice(); - try { - Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); - participantModel.getObject().getId().setPk2(createdPersonne); + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Personne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(personnes, personneService.listPersonnes()); + cleanPersonnesChoice(); + try { + Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); + participantModel.getObject().getId().setPk2(createdPersonne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } - key = Station.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(stations, stationService.listStations(getSession().getUtilisateur())); - cleanStationsChoice(); - try { - Station createdStation = stationService.loadStation(getPageParameters().get(key).toInt()); - stationModel.setObject(createdStation); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + key = Station.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(stations, stationService.listStations(getSession().getUtilisateur())); + cleanStationsChoice(); + try { + Station createdStation = stationService.loadStation(getPageParameters().get(key).toInt()); + stationModel.setObject(createdStation); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } } @@ -666,18 +667,18 @@ * Suprimme de la liste des personnes proposées, les personnes qui sont déjà ajoutées comme participant */ private void cleanPersonnesChoice() { - List<Personne> choices = new ArrayList<Personne>(personnes); - for (CampagnePersonneParticipant participant : campagneModel.getObject().getParticipants()) { - for (Personne personne : personnes) { - if (participant.getId().getPk2().getIdPersonne() == personne.getIdPersonne()) { - choices.remove(personne); - } - } - } - availablePersonnes.setChoices(choices); - availablePersonnes.setEnabled(!choices.isEmpty()); - addParticipant.setEnabled(!choices.isEmpty()); - complementView.setEnabled(!choices.isEmpty()); + List<Personne> choices = new ArrayList<Personne>(personnes); + for (CampagnePersonneParticipant participant : campagneModel.getObject().getParticipants()) { + for (Personne personne : personnes) { + if (participant.getId().getPk2().getIdPersonne() == personne.getIdPersonne()) { + choices.remove(personne); + } + } + } + availablePersonnes.setChoices(choices); + availablePersonnes.setEnabled(!choices.isEmpty()); + addParticipant.setEnabled(!choices.isEmpty()); + complementView.setEnabled(!choices.isEmpty()); } @@ -685,36 +686,36 @@ * Suprimme de la liste des stations proposées, les stations qui sont déjà ajoutées comme station prospectée */ private void cleanStationsChoice() { - List<Station> choices = new ArrayList<Station>(stations); - for (Station curStationAdded : campagneModel.getObject().getStations()) { - for (Station curStation : stations) { - if (curStationAdded.getIdStation() == curStation.getIdStation()) { - choices.remove(curStation); - } - } - } - availableStations.setChoices(choices); - availableStations.setEnabled(!choices.isEmpty()); - addStation.setEnabled(!choices.isEmpty()); - availableStations.setEnabled(!choices.isEmpty()); + List<Station> choices = new ArrayList<Station>(stations); + for (Station curStationAdded : campagneModel.getObject().getStations()) { + for (Station curStation : stations) { + if (curStationAdded.getIdStation() == curStation.getIdStation()) { + choices.remove(curStation); + } + } + } + availableStations.setChoices(choices); + availableStations.setEnabled(!choices.isEmpty()); + addStation.setEnabled(!choices.isEmpty()); + availableStations.setEnabled(!choices.isEmpty()); } /** * Validate the campagne model (for update & create) */ private void validateModel() { - if (campagneModel.getObject().getCreateur() == null) { - campagneModel.getObject().setCreateur(getSession().getUtilisateur()); - } - addValidationErrors(validator.validate(campagneModel.getObject(), getSession().getLocale(), "nom", "codePays", - "programme", "complement", "createur")); - List<String> dateErrors = validator.validate(campagneModel.getObject(), getSession().getLocale(), "dateDeb", - "dateFin"); - addValidationErrors(dateErrors); - if (dateErrors.isEmpty() - && (campagneModel.getObject().getDateDeb() == null || campagneModel.getObject().getDateFin() == null || !campagneModel - .getObject().getDateDeb().before(campagneModel.getObject().getDateFin()))) { - getPage().error(getString("Campagne.dates.KO")); - } + if (campagneModel.getObject().getCreateur() == null) { + campagneModel.getObject().setCreateur(getSession().getUtilisateur()); + } + addValidationErrors(validator.validate(campagneModel.getObject(), getSession().getLocale(), "nom", "codePays", + "programme", "complement", "createur")); + List<String> dateErrors = validator.validate(campagneModel.getObject(), getSession().getLocale(), "dateDeb", + "dateFin"); + addValidationErrors(dateErrors); + if (dateErrors.isEmpty() + && (campagneModel.getObject().getDateDeb() == null || campagneModel.getObject().getDateFin() == null || !campagneModel + .getObject().getDateDeb().before(campagneModel.getObject().getDateFin()))) { + getPage().error(getString("Campagne.dates.KO")); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ReadCampagnePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ReadCampagnePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/campagne/ReadCampagnePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -94,88 +94,88 @@ */ public ReadCampagnePage(Integer idCampagne, final CallerPage callerPage) { - super(ReadCampagnePage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + super(ReadCampagnePage.class); + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation des modèles - campagneModel = new GenericLoadableDetachableModel<Campagne>(Campagne.class, idCampagne); + // Initialisation des modèles + campagneModel = new GenericLoadableDetachableModel<Campagne>(Campagne.class, idCampagne); - final Campagne campagne = campagneModel.getObject(); + final Campagne campagne = campagneModel.getObject(); - // Mapping des champs du modèle - add(new Label("Campagne.nom", new PropertyModel<String>(campagneModel, "nom")) - .add(new ReplaceEmptyLabelBehavior())); + // Mapping des champs du modèle + add(new Label("Campagne.nom", new PropertyModel<String>(campagneModel, "nom")) + .add(new ReplaceEmptyLabelBehavior())); - // Affichage du pays - add(new Label("Campagne.codePays", new DisplayMapValuePropertyModel<String>(campagneModel, "codePays", - WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Campagne.dateDeb", new PropertyModel<String>(campagneModel, "dateDeb")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Campagne.dateFin", new PropertyModel<String>(campagneModel, "dateFin")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Campagne.programme", new PropertyModel<String>(campagneModel, "programme")) - .add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Campagne.mentionLegale", new PropertyModel<String>(campagneModel, "mentionLegale")) - .add(new ReplaceEmptyLabelBehavior())); - add(new SimpleTooltipPanel("Campagne.mentionLegale.info", new Model<String>( - getString("Campagne.mentionLegale.info2")))); - add(new MultiLineLabel("Campagne.complement", new PropertyModel<String>(campagneModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); + // Affichage du pays + add(new Label("Campagne.codePays", new DisplayMapValuePropertyModel<String>(campagneModel, "codePays", + WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Campagne.dateDeb", new PropertyModel<String>(campagneModel, "dateDeb")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Campagne.dateFin", new PropertyModel<String>(campagneModel, "dateFin")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Campagne.programme", new PropertyModel<String>(campagneModel, "programme")) + .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Campagne.mentionLegale", new PropertyModel<String>(campagneModel, "mentionLegale")) + .add(new ReplaceEmptyLabelBehavior())); + add(new SimpleTooltipPanel("Campagne.mentionLegale.info", new Model<String>( + getString("Campagne.mentionLegale.info2")))); + add(new MultiLineLabel("Campagne.complement", new PropertyModel<String>(campagneModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Campagne.createur", new PropertyModel<Personne>(campagneModel, - "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Campagne.createur", new PropertyModel<Personne>(campagneModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - initParticipantsFields(currentPage); - initStationsFields(currentPage); + initParticipantsFields(currentPage); + initStationsFields(currentPage); - // Ajout du formulaire pour les actions - final Form<Void> formView = new Form<Void>("Form"); + // Ajout du formulaire pour les actions + final Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<Campagne> updateLink = new Link<Campagne>(getResource() + ".Campagne.Update", - new Model<Campagne>(campagne)) { - @Override - public void onClick() { - setResponsePage(new ManageCampagnePage(getModelObject().getIdCampagne(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(campagneService.updateOrdeleteCampagneEnabled(campagne, getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Campagne> updateLink = new Link<Campagne>(getResource() + ".Campagne.Update", + new Model<Campagne>(campagne)) { + @Override + public void onClick() { + setResponsePage(new ManageCampagnePage(getModelObject().getIdCampagne(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(campagneService.updateOrdeleteCampagneEnabled(campagne, getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : retour à la page précédente - formView.add(new Link<Void>(getResource() + ".Campagne.Back") { - @Override - public void onClick() { - redirect(); - } - }); + // Action : retour à la page précédente + formView.add(new Link<Void>(getResource() + ".Campagne.Back") { + @Override + public void onClick() { + redirect(); + } + }); - // Action : suppression de la campagne - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageCampagnePage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - campagneService.deleteCampagne(campagne); - } + // Action : suppression de la campagne + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageCampagnePage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + campagneService.deleteCampagne(campagne); + } - @Override - public void onSuccess() { - successNextPage(ManageCampagnePage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(campagneService.updateOrdeleteCampagneEnabled(campagne, getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManageCampagnePage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(campagneService.updateOrdeleteCampagneEnabled(campagne, getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); + add(formView); } /** @@ -183,47 +183,47 @@ * @param currentPage The current page */ private void initParticipantsFields(final CallerPage currentPage) { - ListView<CampagnePersonneParticipant> campagneParticipants = new ListView<CampagnePersonneParticipant>( - "Campagne.participants.List", new PropertyModel<List<CampagnePersonneParticipant>>(campagneModel, - "participants")) { - @Override - protected void populateItem(ListItem<CampagnePersonneParticipant> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + ListView<CampagnePersonneParticipant> campagneParticipants = new ListView<CampagnePersonneParticipant>( + "Campagne.participants.List", new PropertyModel<List<CampagnePersonneParticipant>>(campagneModel, + "participants")) { + @Override + protected void populateItem(ListItem<CampagnePersonneParticipant> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - CampagnePersonneParticipant participant = item.getModelObject(); - // affichage + lien vers la fiche - item.add(new PropertyLabelLinkPanel<Personne>("Campagne.participants.List.personne", - new Model<Personne>(participant.getId().getPk2()), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); - item.add(new Label("Campagne.participants.List.complement", new PropertyModel<String>(participant, - "complement"))); - } - }; + CampagnePersonneParticipant participant = item.getModelObject(); + // affichage + lien vers la fiche + item.add(new PropertyLabelLinkPanel<Personne>("Campagne.participants.List.personne", + new Model<Personne>(participant.getId().getPk2()), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); + item.add(new Label("Campagne.participants.List.complement", new PropertyModel<String>(participant, + "complement"))); + } + }; - // Selon l'existence d'elements dans la liste on affiche la table - MarkupContainer tableParticipants = new WebMarkupContainer("Campagne.participants.Table") { - @Override - public boolean isVisible() { - return campagneModel.getObject().getParticipants().size() != 0; - } - }; - tableParticipants.add(campagneParticipants); - add(tableParticipants); + // Selon l'existence d'elements dans la liste on affiche la table + MarkupContainer tableParticipants = new WebMarkupContainer("Campagne.participants.Table") { + @Override + public boolean isVisible() { + return campagneModel.getObject().getParticipants().size() != 0; + } + }; + tableParticipants.add(campagneParticipants); + add(tableParticipants); - // Selon la non existence d'elements dans la liste on affiche le span - MarkupContainer noTableParticipants = new WebMarkupContainer("Campagne.participants.NoTable") { - @Override - public boolean isVisible() { - return campagneModel.getObject().getParticipants().size() == 0; - } - }; - add(noTableParticipants); + // Selon la non existence d'elements dans la liste on affiche le span + MarkupContainer noTableParticipants = new WebMarkupContainer("Campagne.participants.NoTable") { + @Override + public boolean isVisible() { + return campagneModel.getObject().getParticipants().size() == 0; + } + }; + add(noTableParticipants); } /** @@ -232,88 +232,88 @@ */ private void initStationsFields(final CallerPage currentPage) { - // Selon l'existence d'elements dans la liste on affiche la table - MarkupContainer tableStations = new WebMarkupContainer("Campagne.stations.Table") { - @Override - public boolean isVisible() { - return !campagneModel.getObject().getStations().isEmpty(); - } - }; - add(tableStations); + // Selon l'existence d'elements dans la liste on affiche la table + MarkupContainer tableStations = new WebMarkupContainer("Campagne.stations.Table") { + @Override + public boolean isVisible() { + return !campagneModel.getObject().getStations().isEmpty(); + } + }; + add(tableStations); - final WebMarkupContainer stationsNotAccessiblesCont = new WebMarkupContainer( - "Campagne.stations.stationsNotAccessibles"); - stationsNotAccessiblesCont.setOutputMarkupPlaceholderTag(true); - tableStations.add(stationsNotAccessiblesCont); + final WebMarkupContainer stationsNotAccessiblesCont = new WebMarkupContainer( + "Campagne.stations.stationsNotAccessibles"); + stationsNotAccessiblesCont.setOutputMarkupPlaceholderTag(true); + tableStations.add(stationsNotAccessiblesCont); - // Model de liste des stations - final LoadableDetachableModel<List<Station>> listStationsModel = new LoadableDetachableModel<List<Station>>() { - @Override - protected List<Station> load() { - boolean isOneResultNotAccessible = false; - final List<Station> accessiblesStations = stationService.listStations(getSession().getUtilisateur()); + // Model de liste des stations + final LoadableDetachableModel<List<Station>> listStationsModel = new LoadableDetachableModel<List<Station>>() { + @Override + protected List<Station> load() { + boolean isOneResultNotAccessible = false; + final List<Station> accessiblesStations = stationService.listStations(getSession().getUtilisateur()); - List<Station> listStations = new ArrayList<Station>(); + List<Station> listStations = new ArrayList<Station>(); - for (Station st : campagneModel.getObject().getSortedStations()) { + for (Station st : campagneModel.getObject().getSortedStations()) { - if (accessiblesStations.contains(st)) { - listStations.add(st); - } else { - isOneResultNotAccessible = true; - } - } - // si une des stations non accessibles, on rend visible le message d'avertissement - stationsNotAccessiblesCont.setVisibilityAllowed(isOneResultNotAccessible); - return listStations; - } - }; + if (accessiblesStations.contains(st)) { + listStations.add(st); + } else { + isOneResultNotAccessible = true; + } + } + // si une des stations non accessibles, on rend visible le message d'avertissement + stationsNotAccessiblesCont.setVisibilityAllowed(isOneResultNotAccessible); + return listStations; + } + }; - ListView<Station> stationsListView = new ListView<Station>("Campagne.stations.List", listStationsModel) { - @Override - protected void populateItem(ListItem<Station> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + ListView<Station> stationsListView = new ListView<Station>("Campagne.stations.List", listStationsModel) { + @Override + protected void populateItem(ListItem<Station> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - IModel<Station> stationModel = item.getModel(); - // affichage + lien vers la fiche - item.add(new PropertyLabelLinkPanel<Station>("Campagne.stations.List.station", item.getModel(), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); - } - }); + IModel<Station> stationModel = item.getModel(); + // affichage + lien vers la fiche + item.add(new PropertyLabelLinkPanel<Station>("Campagne.stations.List.station", item.getModel(), + getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); + } + }); - item.add(new Label("Campagne.stations.List.codePays", new DisplayMapValuePropertyModel<String>( - stationModel, "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))) - .add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.localite", new PropertyModel<String>(stationModel, - "localite")).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.latitude", new PropertyModel<String>(stationModel, - "latitude")).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Campagne.stations.List.longitude", new PropertyModel<String>(stationModel, - "longitude")).add(new ReplaceEmptyLabelBehavior())); - } - }; - tableStations.add(stationsListView); + item.add(new Label("Campagne.stations.List.codePays", new DisplayMapValuePropertyModel<String>( + stationModel, "codePays", WebContext.COUNTRIES.get(getSession().getLocale()))) + .add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.localite", new PropertyModel<String>(stationModel, + "localite")).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.latitude", new PropertyModel<String>(stationModel, + "latitude")).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Campagne.stations.List.longitude", new PropertyModel<String>(stationModel, + "longitude")).add(new ReplaceEmptyLabelBehavior())); + } + }; + tableStations.add(stationsListView); - // Selon la non existence d'elements dans la liste on affiche le span - MarkupContainer noTableStations = new WebMarkupContainer("Campagne.stations.NoTable") { - @Override - public boolean isVisible() { - return campagneModel.getObject().getStations().isEmpty(); - } - }; - add(noTableStations); + // Selon la non existence d'elements dans la liste on affiche le span + MarkupContainer noTableStations = new WebMarkupContainer("Campagne.stations.NoTable") { + @Override + public boolean isVisible() { + return campagneModel.getObject().getStations().isEmpty(); + } + }; + add(noTableStations); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ListConfigurationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ListConfigurationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ListConfigurationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -41,7 +41,7 @@ * Consulting of the Information System configuration * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ListConfigurationPage extends TemplatePage { /** The opened param value */ @@ -52,81 +52,81 @@ * @param params The page parameters */ public ListConfigurationPage(PageParameters params) { - super(ListConfigurationPage.class); + super(ListConfigurationPage.class); - // check the parameters to know which panel must be opened - boolean partieOpened = checkIfPanelOpened(params, "partie"); - boolean methExtrOpened = checkIfPanelOpened(params, "methodeExtraction"); - boolean methPuriOpened = checkIfPanelOpened(params, "methodePurification"); - boolean methTestOpened = checkIfPanelOpened(params, "methodeTestBio"); - boolean errTestOpened = checkIfPanelOpened(params, "erreurTestBio"); - boolean rebIndexOpened = checkIfPanelOpened(params, "rebuildLuceneIndex"); + // check the parameters to know which panel must be opened + boolean partieOpened = checkIfPanelOpened(params, "partie"); + boolean methExtrOpened = checkIfPanelOpened(params, "methodeExtraction"); + boolean methPuriOpened = checkIfPanelOpened(params, "methodePurification"); + boolean methTestOpened = checkIfPanelOpened(params, "methodeTestBio"); + boolean errTestOpened = checkIfPanelOpened(params, "erreurTestBio"); + boolean rebIndexOpened = checkIfPanelOpened(params, "rebuildLuceneIndex"); - if (params.get("openedTab").equals("partie")) { - partieOpened = true; - } else if (params.get("openedTab").equals("methodeExtraction")) { - methExtrOpened = true; - } else { + if (params.get("openedTab").equals("partie")) { + partieOpened = true; + } else if (params.get("openedTab").equals("methodeExtraction")) { + methExtrOpened = true; + } else { - // initialize the Partie panel - add(new CollapsiblePanel(getResource() + ".ListPartiePanel", new Model<String>( - getString("ListConfigurationPage.Parties")), partieOpened) { + // initialize the Partie panel + add(new CollapsiblePanel(getResource() + ".ListPartiePanel", new Model<String>( + getString("ListConfigurationPage.Parties")), partieOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new ListPartiePanel(markupId); - } - }); - } + @Override + protected Panel getInnerPanel(String markupId) { + return new ListPartiePanel(markupId); + } + }); + } - // initialize the MethodeExtraction panel - add(new CollapsiblePanel(getResource() + ".ListMethodeExtractionPanel", new Model<String>( - getString("ListConfigurationPage.MethodesExtraction")), methExtrOpened) { + // initialize the MethodeExtraction panel + add(new CollapsiblePanel(getResource() + ".ListMethodeExtractionPanel", new Model<String>( + getString("ListConfigurationPage.MethodesExtraction")), methExtrOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new ListMethodeExtractionPanel(markupId); - } - }); + @Override + protected Panel getInnerPanel(String markupId) { + return new ListMethodeExtractionPanel(markupId); + } + }); - // initialize the MethodePurification panel - add(new CollapsiblePanel(getResource() + ".ListMethodePurificationPanel", new Model<String>( - getString("ListConfigurationPage.MethodesPurification")), methPuriOpened) { + // initialize the MethodePurification panel + add(new CollapsiblePanel(getResource() + ".ListMethodePurificationPanel", new Model<String>( + getString("ListConfigurationPage.MethodesPurification")), methPuriOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new ListMethodePurificationPanel(markupId); - } - }); + @Override + protected Panel getInnerPanel(String markupId) { + return new ListMethodePurificationPanel(markupId); + } + }); - // initialize the MethodeTest panel - add(new CollapsiblePanel(getResource() + ".ListMethodeTestBioPanel", new Model<String>( - getString("ListConfigurationPage.MethodesTestBio")), methTestOpened) { + // initialize the MethodeTest panel + add(new CollapsiblePanel(getResource() + ".ListMethodeTestBioPanel", new Model<String>( + getString("ListConfigurationPage.MethodesTestBio")), methTestOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new ListMethodeTestBioPanel(markupId); - } - }); + @Override + protected Panel getInnerPanel(String markupId) { + return new ListMethodeTestBioPanel(markupId); + } + }); - // initialize the TestErreur panel - add(new CollapsiblePanel(getResource() + ".ListErreurTestBioPanel", new Model<String>( - getString("ListConfigurationPage.ErreursTestBio")), errTestOpened) { + // initialize the TestErreur panel + add(new CollapsiblePanel(getResource() + ".ListErreurTestBioPanel", new Model<String>( + getString("ListConfigurationPage.ErreursTestBio")), errTestOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new ListErreurTestBioPanel(markupId); - } - }); - - // initialize the RebuidLuceneIndex panel - add(new CollapsiblePanel(getResource() + ".RebuildLuceneIndexPanel", new Model<String>( - getString("ListConfigurationPage.RebuildLuceneIndex")), rebIndexOpened) { - @Override - protected Panel getInnerPanel(String markupId) { - return new RebuildLuceneIndexPanel(markupId); - } - }); + @Override + protected Panel getInnerPanel(String markupId) { + return new ListErreurTestBioPanel(markupId); + } + }); + + // initialize the RebuidLuceneIndex panel + add(new CollapsiblePanel(getResource() + ".RebuildLuceneIndexPanel", new Model<String>( + getString("ListConfigurationPage.RebuildLuceneIndex")), rebIndexOpened) { + @Override + protected Panel getInnerPanel(String markupId) { + return new RebuildLuceneIndexPanel(markupId); + } + }); } /** @@ -136,6 +136,6 @@ * @return the answer */ private boolean checkIfPanelOpened(PageParameters params, String paramName) { - return params.get(paramName) != null && OPENED_PARAM_VALUE.equals(params.get(paramName).toString()); + return params.get(paramName) != null && OPENED_PARAM_VALUE.equals(params.get(paramName).toString()); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageErreurTestBioPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageErreurTestBioPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageErreurTestBioPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,7 +53,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManageErreurTestBioPage extends TemplatePage { /** Action : create */ @@ -86,7 +86,7 @@ * Constructor */ public ManageErreurTestBioPage() { - this(null); + this(null); } /** @@ -94,114 +94,114 @@ * @param idErreurTest The ID of the erreurTest */ public ManageErreurTestBioPage(Integer idErreurTest) { - super(ManageErreurTestBioPage.class); + super(ManageErreurTestBioPage.class); - boolean createMode; + boolean createMode; - // model initialization - if (idErreurTest == null) { - // creation mode - erreurTestModel = new Model<ErreurTestBio>(new ErreurTestBio()); - createMode = true; - } else { - try { - erreurTestModel = new Model<ErreurTestBio>(testService.loadErreurTestBio(idErreurTest)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - createMode = false; - } + // model initialization + if (idErreurTest == null) { + // creation mode + erreurTestModel = new Model<ErreurTestBio>(new ErreurTestBio()); + createMode = true; + } else { + try { + erreurTestModel = new Model<ErreurTestBio>(testService.loadErreurTestBio(idErreurTest)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + createMode = false; + } - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("ErreurTestBio.nom", new PropertyModel<String>(erreurTestModel, "nom"))); - formView.add(new TextArea<String>("ErreurTestBio.description", new PropertyModel<String>(erreurTestModel, - "description"))); + formView.add(new TextField<String>("ErreurTestBio.nom", new PropertyModel<String>(erreurTestModel, "nom"))); + formView.add(new TextArea<String>("ErreurTestBio.description", new PropertyModel<String>(erreurTestModel, + "description"))); - // Action : create the erreurTest - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.createErreurTest(erreurTestModel.getObject()); - } + // Action : create the erreurTest + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.createErreurTest(erreurTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the erreurTest - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.updateErreurTestBio(erreurTestModel.getObject()); - } + // Action : update the erreurTest + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.updateErreurTestBio(erreurTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.deleteErreurTest(erreurTestModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.deleteErreurTest(erreurTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); - add(formView); + add(formView); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(erreurTestModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(erreurTestModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeExtractionPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeExtractionPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeExtractionPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -68,7 +68,7 @@ * Page for adding/update/delete a new "MethodeExtraction" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManageMethodeExtractionPage extends TemplatePage { /** Action : create */ @@ -110,7 +110,7 @@ * Constructor */ public ManageMethodeExtractionPage() { - this(null); + this(null); } /** @@ -118,238 +118,238 @@ * @param idMethode The ID of the methode */ public ManageMethodeExtractionPage(Integer idMethode) { - super(ManageMethodeExtractionPage.class); + super(ManageMethodeExtractionPage.class); - boolean createMode; + boolean createMode; - typesDeleted = new HashMap<String, TypeExtrait>(); + typesDeleted = new HashMap<String, TypeExtrait>(); - // model initialization - newTypeExtraitModel = new Model<TypeExtrait>(new TypeExtrait()); - if (idMethode == null) { - // creation mode - methodeExtractionModel = new Model<MethodeExtraction>(new MethodeExtraction()); - createMode = true; - } else { - try { - methodeExtractionModel = new Model<MethodeExtraction>(extraitService.loadMethodeExtraction(idMethode)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - createMode = false; - } + // model initialization + newTypeExtraitModel = new Model<TypeExtrait>(new TypeExtrait()); + if (idMethode == null) { + // creation mode + methodeExtractionModel = new Model<MethodeExtraction>(new MethodeExtraction()); + createMode = true; + } else { + try { + methodeExtractionModel = new Model<MethodeExtraction>(extraitService.loadMethodeExtraction(idMethode)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + createMode = false; + } - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("MethodeExtraction.nom", new PropertyModel<String>(methodeExtractionModel, - "nom"))); - formView.add(new TextArea<String>("MethodeExtraction.description", new PropertyModel<String>( - methodeExtractionModel, "description"))); + formView.add(new TextField<String>("MethodeExtraction.nom", new PropertyModel<String>(methodeExtractionModel, + "nom"))); + formView.add(new TextArea<String>("MethodeExtraction.description", new PropertyModel<String>( + methodeExtractionModel, "description"))); - // Tableau des types en sortie - final MarkupContainer typesEnSortieTable = new WebMarkupContainer("MethodeExtraction.typesEnSortie.Table"); - typesEnSortieTable.setOutputMarkupId(true); + // Tableau des types en sortie + final MarkupContainer typesEnSortieTable = new WebMarkupContainer("MethodeExtraction.typesEnSortie.Table"); + typesEnSortieTable.setOutputMarkupId(true); - // Liste des types extraits ajoutés - typesEnSortieTable.add(new ListView<TypeExtrait>("MethodeExtraction.typesEnSortie.List", - new PropertyModel<List<TypeExtrait>>(methodeExtractionModel, "sortedTypesEnSortie")) { - @Override - protected void populateItem(ListItem<TypeExtrait> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des types extraits ajoutés + typesEnSortieTable.add(new ListView<TypeExtrait>("MethodeExtraction.typesEnSortie.List", + new PropertyModel<List<TypeExtrait>>(methodeExtractionModel, "sortedTypesEnSortie")) { + @Override + protected void populateItem(ListItem<TypeExtrait> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final TypeExtrait typeExtrait = item.getModelObject(); - // Colonnes - item.add(new Label("MethodeExtraction.typesEnSortie.List.initiales", new PropertyModel<String>( - typeExtrait, "initiales"))); - item.add(new Label("MethodeExtraction.typesEnSortie.List.description", new PropertyModel<String>( - typeExtrait, "description"))); + final TypeExtrait typeExtrait = item.getModelObject(); + // Colonnes + item.add(new Label("MethodeExtraction.typesEnSortie.List.initiales", new PropertyModel<String>( + typeExtrait, "initiales"))); + item.add(new Label("MethodeExtraction.typesEnSortie.List.description", new PropertyModel<String>( + typeExtrait, "description"))); - // Action : suppression d'un type extrait - Button deleteButton = new AjaxFallbackButton("MethodeExtraction.typesEnSortie.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - methodeExtractionModel.getObject().getTypesEnSortie().remove(typeExtrait); - // keep the id of the deleted 'extrait' in case of new one with the same 'initiales' - typesDeleted.put(typeExtrait.getInitiales(), typeExtrait); + // Action : suppression d'un type extrait + Button deleteButton = new AjaxFallbackButton("MethodeExtraction.typesEnSortie.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + methodeExtractionModel.getObject().getTypesEnSortie().remove(typeExtrait); + // keep the id of the deleted 'extrait' in case of new one with the same 'initiales' + typesDeleted.put(typeExtrait.getInitiales(), typeExtrait); - if (target != null) { - target.add(typesEnSortieTable); - } - } + if (target != null) { + target.add(typesEnSortieTable); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - final FormComponent<String> initialesInput = new TextField<String>("MethodeExtraction.typesEnSortie.initiales", - new PropertyModel<String>(newTypeExtraitModel, "initiales")); - typesEnSortieTable.add(initialesInput); + final FormComponent<String> initialesInput = new TextField<String>("MethodeExtraction.typesEnSortie.initiales", + new PropertyModel<String>(newTypeExtraitModel, "initiales")); + typesEnSortieTable.add(initialesInput); - final FormComponent<String> descriptionInput = new TextField<String>( - "MethodeExtraction.typesEnSortie.description", new PropertyModel<String>(newTypeExtraitModel, - "description")); - typesEnSortieTable.add(descriptionInput); + final FormComponent<String> descriptionInput = new TextField<String>( + "MethodeExtraction.typesEnSortie.description", new PropertyModel<String>(newTypeExtraitModel, + "description")); + typesEnSortieTable.add(descriptionInput); - // Bouton AJAX pour ajouter un type extrait - Button addButton = new AjaxFallbackButton("MethodeExtraction.typeEnSortie.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // normalisation du type extrait - newTypeExtraitModel.getObject().setInitiales( - Normalizer.normalize(ConfigNameNormalizer.class, newTypeExtraitModel.getObject() - .getInitiales())); - // Ajout du type extrait - newTypeExtraitModel.getObject().setMethodeExtraction(methodeExtractionModel.getObject()); - // recuperate the id if an just deleted type - if (typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()) != null) { - newTypeExtraitModel.getObject().setIdTypeExtrait( - typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()).getIdTypeExtrait()); - } + // Bouton AJAX pour ajouter un type extrait + Button addButton = new AjaxFallbackButton("MethodeExtraction.typeEnSortie.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // normalisation du type extrait + newTypeExtraitModel.getObject().setInitiales( + Normalizer.normalize(ConfigNameNormalizer.class, newTypeExtraitModel.getObject() + .getInitiales())); + // Ajout du type extrait + newTypeExtraitModel.getObject().setMethodeExtraction(methodeExtractionModel.getObject()); + // recuperate the id if an just deleted type + if (typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()) != null) { + newTypeExtraitModel.getObject().setIdTypeExtrait( + typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()).getIdTypeExtrait()); + } - // ajout à la liste - TypeExtrait typeExtraitAdded = newTypeExtraitModel.getObject().clone(); - methodeExtractionModel.getObject().getTypesEnSortie().add(typeExtraitAdded); + // ajout à la liste + TypeExtrait typeExtraitAdded = newTypeExtraitModel.getObject().clone(); + methodeExtractionModel.getObject().getTypesEnSortie().add(typeExtraitAdded); - List<String> errors = validator.validate(newTypeExtraitModel.getObject(), getSession().getLocale()); - if (errors.isEmpty()) { - if (typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()) != null) { - // si ancien extrait supprimé, on l'enlève de la liste des supprimés - typesDeleted.remove(newTypeExtraitModel.getObject().getInitiales()); - } + List<String> errors = validator.validate(newTypeExtraitModel.getObject(), getSession().getLocale()); + if (errors.isEmpty()) { + if (typesDeleted.get(newTypeExtraitModel.getObject().getInitiales()) != null) { + // si ancien extrait supprimé, on l'enlève de la liste des supprimés + typesDeleted.remove(newTypeExtraitModel.getObject().getInitiales()); + } - // réinit du champ ajout - newTypeExtraitModel.getObject().setInitiales(null); - newTypeExtraitModel.getObject().setDescription(null); - } else { - methodeExtractionModel.getObject().getTypesEnSortie().remove(typeExtraitAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // réinit du champ ajout + newTypeExtraitModel.getObject().setInitiales(null); + newTypeExtraitModel.getObject().setDescription(null); + } else { + methodeExtractionModel.getObject().getTypesEnSortie().remove(typeExtraitAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - if (target != null) { - target.add(typesEnSortieTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(typesEnSortieTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - typesEnSortieTable.add(addButton); + }; + typesEnSortieTable.add(addButton); - // Action : create the methodeExtraction - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extraitService.createMethodeExtraction(methodeExtractionModel.getObject()); - } + // Action : create the methodeExtraction + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extraitService.createMethodeExtraction(methodeExtractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - formView.add(typesEnSortieTable); + formView.add(typesEnSortieTable); - // Action : update the methodeExtraction - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extraitService.updateMethodeExtraction(methodeExtractionModel.getObject()); - } + // Action : update the methodeExtraction + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extraitService.updateMethodeExtraction(methodeExtractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extraitService.deleteMethodeExtraction(methodeExtractionModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extraitService.deleteMethodeExtraction(methodeExtractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); - formView.setDefaultButton(addButton); - add(formView); + formView.setDefaultButton(addButton); + add(formView); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(methodeExtractionModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(methodeExtractionModel.getObject(), getSession().getLocale())); - // vérifie s'il existe des types supprimés qui sont tjr référencés - for (TypeExtrait curDelType : typesDeleted.values()) { - if (extraitService.isTypeExtraitReferenced(curDelType)) { - getPage().error( - getString("TypeExtrait.isReferenced", - new Model<Serializable>(new Serializable[] { curDelType.getInitiales() }))); - } - } + // vérifie s'il existe des types supprimés qui sont tjr référencés + for (TypeExtrait curDelType : typesDeleted.values()) { + if (extraitService.isTypeExtraitReferenced(curDelType)) { + getPage().error( + getString("TypeExtrait.isReferenced", new Model<Serializable>(new Serializable[] { curDelType + .getInitiales() }))); + } + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodePurificationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodePurificationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodePurificationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -68,7 +68,7 @@ * Page for adding/update/delete a new "MethodePurification" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManageMethodePurificationPage extends TemplatePage { /** Action : create */ @@ -110,7 +110,7 @@ * Constructor */ public ManageMethodePurificationPage() { - this(null); + this(null); } /** @@ -118,240 +118,240 @@ * @param idMethode The ID of the methode */ public ManageMethodePurificationPage(Integer idMethode) { - super(ManageMethodePurificationPage.class); + super(ManageMethodePurificationPage.class); - boolean createMode; + boolean createMode; - paramsDeleted = new HashMap<String, ParamMethoPuri>(); + paramsDeleted = new HashMap<String, ParamMethoPuri>(); - // model initialization - newParamModel = new Model<ParamMethoPuri>(new ParamMethoPuri()); - if (idMethode == null) { - // creation mode - methodePurificationModel = new Model<MethodePurification>(new MethodePurification()); - createMode = true; - } else { - try { - methodePurificationModel = new Model<MethodePurification>( - purificationService.loadMethodePurification(idMethode)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - createMode = false; - } + // model initialization + newParamModel = new Model<ParamMethoPuri>(new ParamMethoPuri()); + if (idMethode == null) { + // creation mode + methodePurificationModel = new Model<MethodePurification>(new MethodePurification()); + createMode = true; + } else { + try { + methodePurificationModel = new Model<MethodePurification>(purificationService + .loadMethodePurification(idMethode)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + createMode = false; + } - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("MethodePurification.nom", new PropertyModel<String>( - methodePurificationModel, "nom"))); - formView.add(new TextArea<String>("MethodePurification.description", new PropertyModel<String>( - methodePurificationModel, "description"))); + formView.add(new TextField<String>("MethodePurification.nom", new PropertyModel<String>( + methodePurificationModel, "nom"))); + formView.add(new TextArea<String>("MethodePurification.description", new PropertyModel<String>( + methodePurificationModel, "description"))); - // Tableau des types en sortie - final MarkupContainer typesEnSortieTable = new WebMarkupContainer("MethodePurification.parametres.Table"); - typesEnSortieTable.setOutputMarkupId(true); + // Tableau des types en sortie + final MarkupContainer typesEnSortieTable = new WebMarkupContainer("MethodePurification.parametres.Table"); + typesEnSortieTable.setOutputMarkupId(true); - // Liste des types extraits ajoutés - typesEnSortieTable.add(new ListView<ParamMethoPuri>("MethodePurification.parametres.List", - new PropertyModel<List<ParamMethoPuri>>(methodePurificationModel, "sortedParametres")) { - @Override - protected void populateItem(final ListItem<ParamMethoPuri> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des types extraits ajoutés + typesEnSortieTable.add(new ListView<ParamMethoPuri>("MethodePurification.parametres.List", + new PropertyModel<List<ParamMethoPuri>>(methodePurificationModel, "sortedParametres")) { + @Override + protected void populateItem(final ListItem<ParamMethoPuri> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final ParamMethoPuri param = item.getModelObject(); - // Colonnes - item.add(new Label("MethodePurification.parametres.List.nom", new PropertyModel<String>(param, "nom"))); - item.add(new Label("MethodePurification.parametres.List.description", new PropertyModel<String>(param, - "description"))); - item.add(new Label("MethodePurification.parametres.List.index", new PropertyModel<String>(param, - "index"))); + final ParamMethoPuri param = item.getModelObject(); + // Colonnes + item.add(new Label("MethodePurification.parametres.List.nom", new PropertyModel<String>(param, "nom"))); + item.add(new Label("MethodePurification.parametres.List.description", new PropertyModel<String>(param, + "description"))); + item.add(new Label("MethodePurification.parametres.List.index", new PropertyModel<String>(param, + "index"))); - // Action : suppression d'un type extrait - Button deleteButton = new AjaxFallbackButton("MethodePurification.parametres.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - methodePurificationModel.getObject().getParametres().remove(param); - // keep the id of the deleted 'extrait' in case of new one with the same 'initiales' - paramsDeleted.put(param.getNom(), param); - if (target != null) { - target.add(typesEnSortieTable); - } - } + // Action : suppression d'un type extrait + Button deleteButton = new AjaxFallbackButton("MethodePurification.parametres.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + methodePurificationModel.getObject().getParametres().remove(param); + // keep the id of the deleted 'extrait' in case of new one with the same 'initiales' + paramsDeleted.put(param.getNom(), param); + if (target != null) { + target.add(typesEnSortieTable); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - final FormComponent<String> nomParamInput = new TextField<String>("MethodePurification.parametres.nom", - new PropertyModel<String>(newParamModel, "nom")); - typesEnSortieTable.add(nomParamInput); + final FormComponent<String> nomParamInput = new TextField<String>("MethodePurification.parametres.nom", + new PropertyModel<String>(newParamModel, "nom")); + typesEnSortieTable.add(nomParamInput); - final FormComponent<String> descriptionParamInput = new TextField<String>( - "MethodePurification.parametres.description", new PropertyModel<String>(newParamModel, "description")); - typesEnSortieTable.add(descriptionParamInput); + final FormComponent<String> descriptionParamInput = new TextField<String>( + "MethodePurification.parametres.description", new PropertyModel<String>(newParamModel, "description")); + typesEnSortieTable.add(descriptionParamInput); - final FormComponent<String> indexParamInput = new TextField<String>("MethodePurification.parametres.index", - new PropertyModel<String>(newParamModel, "index")); - typesEnSortieTable.add(indexParamInput); + final FormComponent<String> indexParamInput = new TextField<String>("MethodePurification.parametres.index", + new PropertyModel<String>(newParamModel, "index")); + typesEnSortieTable.add(indexParamInput); - // Bouton AJAX pour ajouter un type extrait - Button addButton = new AjaxFallbackButton("MethodePurification.parametres.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // normalisation du type extrait - newParamModel.getObject().setNom( - Normalizer.normalize(ConfigNameNormalizer.class, newParamModel.getObject().getNom())); - // Ajout du type extrait - newParamModel.getObject().setMethodePurification(methodePurificationModel.getObject()); - // recuperate the id if an just deleted type - if (paramsDeleted.get(newParamModel.getObject().getNom()) != null) { - newParamModel.getObject().setIdParamMethoPuri( - paramsDeleted.get(newParamModel.getObject().getNom()).getIdParamMethoPuri()); - } + // Bouton AJAX pour ajouter un type extrait + Button addButton = new AjaxFallbackButton("MethodePurification.parametres.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // normalisation du type extrait + newParamModel.getObject().setNom( + Normalizer.normalize(ConfigNameNormalizer.class, newParamModel.getObject().getNom())); + // Ajout du type extrait + newParamModel.getObject().setMethodePurification(methodePurificationModel.getObject()); + // recuperate the id if an just deleted type + if (paramsDeleted.get(newParamModel.getObject().getNom()) != null) { + newParamModel.getObject().setIdParamMethoPuri( + paramsDeleted.get(newParamModel.getObject().getNom()).getIdParamMethoPuri()); + } - // ajout à la liste - ParamMethoPuri paramAdded = newParamModel.getObject().clone(); - methodePurificationModel.getObject().getParametres().add(paramAdded); + // ajout à la liste + ParamMethoPuri paramAdded = newParamModel.getObject().clone(); + methodePurificationModel.getObject().getParametres().add(paramAdded); - List<String> errors = validator.validate(newParamModel.getObject(), getSession().getLocale()); - if (errors.isEmpty()) { - if (paramsDeleted.get(newParamModel.getObject().getNom()) != null) { - // si ancien extrait supprimé, on l'enlève de la liste des supprimés - paramsDeleted.remove(newParamModel.getObject().getNom()); - } - // réinit du champ ajout - newParamModel.getObject().setNom(null); - newParamModel.getObject().setDescription(null); - } else { - methodePurificationModel.getObject().getParametres().remove(paramAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + List<String> errors = validator.validate(newParamModel.getObject(), getSession().getLocale()); + if (errors.isEmpty()) { + if (paramsDeleted.get(newParamModel.getObject().getNom()) != null) { + // si ancien extrait supprimé, on l'enlève de la liste des supprimés + paramsDeleted.remove(newParamModel.getObject().getNom()); + } + // réinit du champ ajout + newParamModel.getObject().setNom(null); + newParamModel.getObject().setDescription(null); + } else { + methodePurificationModel.getObject().getParametres().remove(paramAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - if (target != null) { - target.add(typesEnSortieTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(typesEnSortieTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - typesEnSortieTable.add(addButton); + }; + typesEnSortieTable.add(addButton); - // Action : create the methodePurification - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.createMethodePurification(methodePurificationModel.getObject()); - } + // Action : create the methodePurification + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.createMethodePurification(methodePurificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - formView.add(typesEnSortieTable); + formView.add(typesEnSortieTable); - // Action : update the methodePurificationModel - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.updateMethodePurification(methodePurificationModel.getObject()); - } + // Action : update the methodePurificationModel + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.updateMethodePurification(methodePurificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.deleteMethodePurification(methodePurificationModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.deleteMethodePurification(methodePurificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); - formView.setDefaultButton(addButton); - add(formView); + formView.setDefaultButton(addButton); + add(formView); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(methodePurificationModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(methodePurificationModel.getObject(), getSession().getLocale())); - // vérifie s'il existe des paramètres supprimés qui sont tjr référencés - for (ParamMethoPuri curDelParam : paramsDeleted.values()) { - if (purificationService.isParamMethoPuriReferenced(curDelParam)) { - getPage().error( - getString("ParamMethoPuri.isReferenced", new Model<Serializable>( - new Serializable[] { curDelParam.getNom() }))); - } - } + // vérifie s'il existe des paramètres supprimés qui sont tjr référencés + for (ParamMethoPuri curDelParam : paramsDeleted.values()) { + if (purificationService.isParamMethoPuriReferenced(curDelParam)) { + getPage().error( + getString("ParamMethoPuri.isReferenced", new Model<Serializable>( + new Serializable[] { curDelParam.getNom() }))); + } + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeTestBioPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeTestBioPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManageMethodeTestBioPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,7 +56,7 @@ * Page for adding/update/delete a new "MethodeTest" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManageMethodeTestBioPage extends TemplatePage { /** Action : create */ @@ -89,7 +89,7 @@ * Constructor */ public ManageMethodeTestBioPage() { - this(null); + this(null); } /** @@ -97,128 +97,129 @@ * @param idMethodeTest The ID of the methode */ public ManageMethodeTestBioPage(Integer idMethodeTest) { - super(ManageMethodeTestBioPage.class); + super(ManageMethodeTestBioPage.class); - boolean createMode; + boolean createMode; - // model initialization - if (idMethodeTest == null) { - // creation mode - methodeTestModel = new Model<MethodeTestBio>(new MethodeTestBio()); - createMode = true; - } else { - try { - methodeTestModel = new Model<MethodeTestBio>(testService.loadMethodeTest(idMethodeTest)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - createMode = false; - } + // model initialization + if (idMethodeTest == null) { + // creation mode + methodeTestModel = new Model<MethodeTestBio>(new MethodeTestBio()); + createMode = true; + } else { + try { + methodeTestModel = new Model<MethodeTestBio>(testService.loadMethodeTest(idMethodeTest)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + createMode = false; + } - // Initialisation des liste (pour le AutoCompleteTextField) - // liste des valeurs déjà existantes pour la propriété correspondante - List<String> domaines = testService.listDomainesMethodes(); - List<String> unites = testService.listUnitesResultatMethodes(); + // Initialisation des liste (pour le AutoCompleteTextField) + // liste des valeurs déjà existantes pour la propriété correspondante + List<String> domaines = testService.listDomainesMethodes(); + List<String> unites = testService.listUnitesResultatMethodes(); - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("MethodeTestBio.nom", new PropertyModel<String>(methodeTestModel, "nom"))); - formView.add(new TextField<String>("MethodeTestBio.cible", new PropertyModel<String>(methodeTestModel, "cible"))); - formView.add(new AutoCompleteTextFieldString("MethodeTestBio.domaine", new PropertyModel<String>( - methodeTestModel, "domaine"), domaines, ComparisonMode.CONTAINS)); - formView.add(new TextArea<String>("MethodeTestBio.description", new PropertyModel<String>(methodeTestModel, - "description"))); - formView.add(new TextField<String>("MethodeTestBio.valeurMesuree", new PropertyModel<String>(methodeTestModel, - "valeurMesuree"))); - formView.add(new AutoCompleteTextFieldString("MethodeTestBio.uniteResultat", new PropertyModel<String>( - methodeTestModel, "uniteResultat"), unites, ComparisonMode.STARTS_WITH)); - formView.add(new TextField<String>("MethodeTestBio.critereActivite", new PropertyModel<String>( - methodeTestModel, "critereActivite"))); + formView.add(new TextField<String>("MethodeTestBio.nom", new PropertyModel<String>(methodeTestModel, "nom"))); + formView + .add(new TextField<String>("MethodeTestBio.cible", new PropertyModel<String>(methodeTestModel, "cible"))); + formView.add(new AutoCompleteTextFieldString("MethodeTestBio.domaine", new PropertyModel<String>( + methodeTestModel, "domaine"), domaines, ComparisonMode.CONTAINS)); + formView.add(new TextArea<String>("MethodeTestBio.description", new PropertyModel<String>(methodeTestModel, + "description"))); + formView.add(new TextField<String>("MethodeTestBio.valeurMesuree", new PropertyModel<String>(methodeTestModel, + "valeurMesuree"))); + formView.add(new AutoCompleteTextFieldString("MethodeTestBio.uniteResultat", new PropertyModel<String>( + methodeTestModel, "uniteResultat"), unites, ComparisonMode.STARTS_WITH)); + formView.add(new TextField<String>("MethodeTestBio.critereActivite", new PropertyModel<String>( + methodeTestModel, "critereActivite"))); - // Action : create the methodeTest - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.createMethodeTestBio(methodeTestModel.getObject()); - } + // Action : create the methodeTest + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.createMethodeTestBio(methodeTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the methodeTest - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.updateMethodeTest(methodeTestModel.getObject()); - } + // Action : update the methodeTest + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.updateMethodeTest(methodeTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testService.deleteMethodeTestBio(methodeTestModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testService.deleteMethodeTestBio(methodeTestModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); - add(formView); + add(formView); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(methodeTestModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(methodeTestModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManagePartiePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManagePartiePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/ManagePartiePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,7 +52,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManagePartiePage extends TemplatePage { /** Action : create */ @@ -85,7 +85,7 @@ * Constructor */ public ManagePartiePage() { - this(null); + this(null); } /** @@ -93,112 +93,112 @@ * @param idPartie The ID of the partie */ public ManagePartiePage(Integer idPartie) { - super(ManagePartiePage.class); + super(ManagePartiePage.class); - boolean createMode; + boolean createMode; - // model initialization - if (idPartie == null) { - // creation mode - partieModel = new Model<Partie>(new Partie()); - createMode = true; - } else { - try { - partieModel = new Model<Partie>(lotService.loadPartie(idPartie)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - createMode = false; - } + // model initialization + if (idPartie == null) { + // creation mode + partieModel = new Model<Partie>(new Partie()); + createMode = true; + } else { + try { + partieModel = new Model<Partie>(lotService.loadPartie(idPartie)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + createMode = false; + } - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("Partie.nom", new PropertyModel<String>(partieModel, "nom"))); + formView.add(new TextField<String>("Partie.nom", new PropertyModel<String>(partieModel, "nom"))); - // Action : create the partie - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.createPartie(partieModel.getObject()); - } + // Action : create the partie + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.createPartie(partieModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the partie - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.updatePartie(partieModel.getObject()); - } + // Action : update the partie + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.updatePartie(partieModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression de la personne - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.deletePartie(partieModel.getObject()); - } + // Action : suppression de la personne + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.deletePartie(partieModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - PageParameters params = new PageParameters(); - params.add(RETURN_PARAM[0], RETURN_PARAM[1]); - setResponsePage(ListConfigurationPage.class, params); - } - }); + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + PageParameters params = new PageParameters(); + params.add(RETURN_PARAM[0], RETURN_PARAM[1]); + setResponsePage(ListConfigurationPage.class, params); + } + }); - add(formView); + add(formView); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(partieModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(partieModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListErreurTestBioPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListErreurTestBioPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListErreurTestBioPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,48 +58,48 @@ * @param id The panel ID */ public ListErreurTestBioPanel(String id) { - super(id); + super(id); - add(new BookmarkablePageLink<Void>("ListErreurTestBioPanel.NewErreurTestBio", ManageErreurTestBioPage.class)); + add(new BookmarkablePageLink<Void>("ListErreurTestBioPanel.NewErreurTestBio", ManageErreurTestBioPage.class)); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer erreursTestRefresh = new WebMarkupContainer( - "ListErreurTestBioPanel.ErreursTestBio.Refresh"); - erreursTestRefresh.setOutputMarkupId(true); - add(erreursTestRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer erreursTestRefresh = new WebMarkupContainer( + "ListErreurTestBioPanel.ErreursTestBio.Refresh"); + erreursTestRefresh.setOutputMarkupId(true); + add(erreursTestRefresh); - // Liste des erreursTest - final List<ErreurTestBio> erreurTest = testService.listErreursTestBio(); - LoadableDetachableSortableListDataProvider<ErreurTestBio> erreursDataProvider = new LoadableDetachableSortableListDataProvider<ErreurTestBio>( - erreurTest, getSession().getLocale()); + // Liste des erreursTest + final List<ErreurTestBio> erreurTest = testService.listErreursTestBio(); + LoadableDetachableSortableListDataProvider<ErreurTestBio> erreursDataProvider = new LoadableDetachableSortableListDataProvider<ErreurTestBio>( + erreurTest, getSession().getLocale()); - erreursTestRefresh - .add(new DataView<ErreurTestBio>("ListErreurTestBioPanel.ErreursTestBio", erreursDataProvider) { - @Override - protected void populateItem(Item<ErreurTestBio> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + erreursTestRefresh + .add(new DataView<ErreurTestBio>("ListErreurTestBioPanel.ErreursTestBio", erreursDataProvider) { + @Override + protected void populateItem(Item<ErreurTestBio> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - ErreurTestBio erreurTest = item.getModelObject(); - // Colonnes - item.add(new Label("ListErreurTestBioPanel.ErreursTestBio.nom", new PropertyModel<String>( - erreurTest, "nom"))); - item.add(new Label("ListErreurTestBioPanel.ErreursTestBio.description", - new PropertyModel<String>(erreurTest, "description"))); + ErreurTestBio erreurTest = item.getModelObject(); + // Colonnes + item.add(new Label("ListErreurTestBioPanel.ErreursTestBio.nom", new PropertyModel<String>( + erreurTest, "nom"))); + item.add(new Label("ListErreurTestBioPanel.ErreursTestBio.description", + new PropertyModel<String>(erreurTest, "description"))); - // Action : mise à jour (redirection vers le formulaire) - Link<ErreurTestBio> updateLink = new Link<ErreurTestBio>( - "ListErreurTestBioPanel.ErreursTestBio.Update", new Model<ErreurTestBio>(erreurTest)) { - @Override - public void onClick() { - setResponsePage(new ManageErreurTestBioPage(getModelObject().getIdErreurTest())); - } - }; - item.add(updateLink); - } - }); + // Action : mise à jour (redirection vers le formulaire) + Link<ErreurTestBio> updateLink = new Link<ErreurTestBio>( + "ListErreurTestBioPanel.ErreursTestBio.Update", new Model<ErreurTestBio>(erreurTest)) { + @Override + public void onClick() { + setResponsePage(new ManageErreurTestBioPage(getModelObject().getIdErreurTest())); + } + }; + item.add(updateLink); + } + }); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeExtractionPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeExtractionPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeExtractionPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -59,55 +59,55 @@ * @param id The panel ID */ public ListMethodeExtractionPanel(String id) { - super(id); + super(id); - add(new BookmarkablePageLink<Void>("ListMethodeExtractionPanel.NewMethodeExtraction", - ManageMethodeExtractionPage.class)); + add(new BookmarkablePageLink<Void>("ListMethodeExtractionPanel.NewMethodeExtraction", + ManageMethodeExtractionPage.class)); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer methodesExtractionRefresh = new WebMarkupContainer( - "ListMethodeExtractionPanel.MethodesExtraction.Refresh"); - methodesExtractionRefresh.setOutputMarkupId(true); - add(methodesExtractionRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer methodesExtractionRefresh = new WebMarkupContainer( + "ListMethodeExtractionPanel.MethodesExtraction.Refresh"); + methodesExtractionRefresh.setOutputMarkupId(true); + add(methodesExtractionRefresh); - // Liste des methodesExtraction - final List<MethodeExtraction> methodesExtraction = extraitService.listMethodesExtraction(); - LoadableDetachableSortableListDataProvider<MethodeExtraction> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodeExtraction>( - methodesExtraction, getSession().getLocale()); + // Liste des methodesExtraction + final List<MethodeExtraction> methodesExtraction = extraitService.listMethodesExtraction(); + LoadableDetachableSortableListDataProvider<MethodeExtraction> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodeExtraction>( + methodesExtraction, getSession().getLocale()); - methodesExtractionRefresh.add(new DataView<MethodeExtraction>("ListMethodeExtractionPanel.MethodesExtraction", - methodesDataProvider) { - @Override - protected void populateItem(Item<MethodeExtraction> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + methodesExtractionRefresh.add(new DataView<MethodeExtraction>("ListMethodeExtractionPanel.MethodesExtraction", + methodesDataProvider) { + @Override + protected void populateItem(Item<MethodeExtraction> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - MethodeExtraction methodeExtraction = item.getModelObject(); - // Refresh the methodeExtraction for Ajax refreshes (typesEnSorties is LAZY and session different from - // the one used for the init) - extraitService.refreshMethodeExtraction(methodeExtraction); - // Colonnes - item.add(new Label("ListMethodeExtractionPanel.MethodesExtraction.nom", new PropertyModel<String>( - methodeExtraction, "nom"))); - item.add(new MultiLineLabel("ListMethodeExtractionPanel.MethodesExtraction.description", - new PropertyModel<String>(methodeExtraction, "description"))); - item.add(new Label("ListMethodeExtractionPanel.MethodesExtraction.typesEnSortie", StringUtils.join( - methodeExtraction.getSortedTypesEnSortie(), ", "))); + MethodeExtraction methodeExtraction = item.getModelObject(); + // Refresh the methodeExtraction for Ajax refreshes (typesEnSorties is LAZY and session different from + // the one used for the init) + extraitService.refreshMethodeExtraction(methodeExtraction); + // Colonnes + item.add(new Label("ListMethodeExtractionPanel.MethodesExtraction.nom", new PropertyModel<String>( + methodeExtraction, "nom"))); + item.add(new MultiLineLabel("ListMethodeExtractionPanel.MethodesExtraction.description", + new PropertyModel<String>(methodeExtraction, "description"))); + item.add(new Label("ListMethodeExtractionPanel.MethodesExtraction.typesEnSortie", StringUtils.join( + methodeExtraction.getSortedTypesEnSortie(), ", "))); - // Action : mise à jour (redirection vers le formulaire) - Link<MethodeExtraction> updateLink = new Link<MethodeExtraction>( - "ListMethodeExtractionPanel.MethodesExtraction.Update", new Model<MethodeExtraction>( - methodeExtraction)) { - @Override - public void onClick() { - setResponsePage(new ManageMethodeExtractionPage(getModelObject().getIdMethodeExtraction())); - } - }; - item.add(updateLink); - } - }); + // Action : mise à jour (redirection vers le formulaire) + Link<MethodeExtraction> updateLink = new Link<MethodeExtraction>( + "ListMethodeExtractionPanel.MethodesExtraction.Update", new Model<MethodeExtraction>( + methodeExtraction)) { + @Override + public void onClick() { + setResponsePage(new ManageMethodeExtractionPage(getModelObject().getIdMethodeExtraction())); + } + }; + item.add(updateLink); + } + }); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodePurificationPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodePurificationPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodePurificationPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,55 +58,55 @@ * @param id The panel ID */ public ListMethodePurificationPanel(String id) { - super(id); + super(id); - add(new BookmarkablePageLink<Void>("ListMethodePurificationPanel.NewMethodePurification", - ManageMethodePurificationPage.class)); + add(new BookmarkablePageLink<Void>("ListMethodePurificationPanel.NewMethodePurification", + ManageMethodePurificationPage.class)); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer methodesPurificationRefresh = new WebMarkupContainer( - "ListMethodePurificationPanel.MethodesPurification.Refresh"); - methodesPurificationRefresh.setOutputMarkupId(true); - add(methodesPurificationRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer methodesPurificationRefresh = new WebMarkupContainer( + "ListMethodePurificationPanel.MethodesPurification.Refresh"); + methodesPurificationRefresh.setOutputMarkupId(true); + add(methodesPurificationRefresh); - // Liste des methodesPurification - final List<MethodePurification> methodesPurification = purificationService.listMethodesPurification(); - LoadableDetachableSortableListDataProvider<MethodePurification> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodePurification>( - methodesPurification, getSession().getLocale()); + // Liste des methodesPurification + final List<MethodePurification> methodesPurification = purificationService.listMethodesPurification(); + LoadableDetachableSortableListDataProvider<MethodePurification> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodePurification>( + methodesPurification, getSession().getLocale()); - methodesPurificationRefresh.add(new DataView<MethodePurification>( - "ListMethodePurificationPanel.MethodesPurification", methodesDataProvider) { - @Override - protected void populateItem(Item<MethodePurification> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + methodesPurificationRefresh.add(new DataView<MethodePurification>( + "ListMethodePurificationPanel.MethodesPurification", methodesDataProvider) { + @Override + protected void populateItem(Item<MethodePurification> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - MethodePurification methodePurification = item.getModelObject(); - // Refresh the methodePurification for Ajax refreshes (parametres is LAZY and session different from - // the one used for the init) - purificationService.refreshMethodePurification(methodePurification); - // Colonnes - item.add(new Label("ListMethodePurificationPanel.MethodesPurification.nom", methodePurification - .getNom())); - item.add(new MultiLineLabel("ListMethodePurificationPanel.MethodesPurification.description", - methodePurification.getDescription())); - item.add(new Label("ListMethodePurificationPanel.MethodesPurification.parametres", StringUtils.join( - methodePurification.getParametres(), ", "))); + MethodePurification methodePurification = item.getModelObject(); + // Refresh the methodePurification for Ajax refreshes (parametres is LAZY and session different from + // the one used for the init) + purificationService.refreshMethodePurification(methodePurification); + // Colonnes + item.add(new Label("ListMethodePurificationPanel.MethodesPurification.nom", methodePurification + .getNom())); + item.add(new MultiLineLabel("ListMethodePurificationPanel.MethodesPurification.description", + methodePurification.getDescription())); + item.add(new Label("ListMethodePurificationPanel.MethodesPurification.parametres", StringUtils.join( + methodePurification.getParametres(), ", "))); - // Action : mise à jour (redirection vers le formulaire) - Link<MethodePurification> updateLink = new Link<MethodePurification>( - "ListMethodePurificationPanel.MethodesPurification.Update", new Model<MethodePurification>( - methodePurification)) { - @Override - public void onClick() { - setResponsePage(new ManageMethodePurificationPage(getModelObject().getIdMethodePurification())); - } - }; - item.add(updateLink); - } - }); + // Action : mise à jour (redirection vers le formulaire) + Link<MethodePurification> updateLink = new Link<MethodePurification>( + "ListMethodePurificationPanel.MethodesPurification.Update", new Model<MethodePurification>( + methodePurification)) { + @Override + public void onClick() { + setResponsePage(new ManageMethodePurificationPage(getModelObject().getIdMethodePurification())); + } + }; + item.add(updateLink); + } + }); } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeTestBioPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeTestBioPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListMethodeTestBioPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,59 +58,59 @@ * @param id The panel ID */ public ListMethodeTestBioPanel(String id) { - super(id); + super(id); - add(new BookmarkablePageLink<Void>("ListMethodeTestBioPanel.NewMethodeTestBio", ManageMethodeTestBioPage.class)); + add(new BookmarkablePageLink<Void>("ListMethodeTestBioPanel.NewMethodeTestBio", ManageMethodeTestBioPage.class)); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer methodesTestRefresh = new WebMarkupContainer( - "ListMethodeTestBioPanel.MethodesTestBio.Refresh"); - methodesTestRefresh.setOutputMarkupId(true); - add(methodesTestRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer methodesTestRefresh = new WebMarkupContainer( + "ListMethodeTestBioPanel.MethodesTestBio.Refresh"); + methodesTestRefresh.setOutputMarkupId(true); + add(methodesTestRefresh); - // Liste des methodesTest - final List<MethodeTestBio> methodesTest = testService.listMethodesTestBio(); - LoadableDetachableSortableListDataProvider<MethodeTestBio> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodeTestBio>( - methodesTest, getSession().getLocale()); + // Liste des methodesTest + final List<MethodeTestBio> methodesTest = testService.listMethodesTestBio(); + LoadableDetachableSortableListDataProvider<MethodeTestBio> methodesDataProvider = new LoadableDetachableSortableListDataProvider<MethodeTestBio>( + methodesTest, getSession().getLocale()); - methodesTestRefresh.add(new DataView<MethodeTestBio>("ListMethodeTestBioPanel.MethodesTestBio", - methodesDataProvider) { - @Override - protected void populateItem(Item<MethodeTestBio> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + methodesTestRefresh.add(new DataView<MethodeTestBio>("ListMethodeTestBioPanel.MethodesTestBio", + methodesDataProvider) { + @Override + protected void populateItem(Item<MethodeTestBio> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - MethodeTestBio methodeExtraction = item.getModelObject(); + MethodeTestBio methodeExtraction = item.getModelObject(); - // Colonnes - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.nom", new PropertyModel<String>( - methodeExtraction, "nom"))); - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.cible", new PropertyModel<String>( - methodeExtraction, "cible"))); - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.domaine", new PropertyModel<String>( - methodeExtraction, "domaine"))); - item.add(new MultiLineLabel("ListMethodeTestBioPanel.MethodesTestBio.description", - new PropertyModel<String>(methodeExtraction, "description"))); - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.valeurMesuree", new PropertyModel<String>( - methodeExtraction, "valeurMesuree"))); - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.uniteResultat", new PropertyModel<String>( - methodeExtraction, "uniteResultat"))); - item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.critereActivite", - new PropertyModel<String>(methodeExtraction, "critereActivite"))); + // Colonnes + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.nom", new PropertyModel<String>( + methodeExtraction, "nom"))); + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.cible", new PropertyModel<String>( + methodeExtraction, "cible"))); + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.domaine", new PropertyModel<String>( + methodeExtraction, "domaine"))); + item.add(new MultiLineLabel("ListMethodeTestBioPanel.MethodesTestBio.description", + new PropertyModel<String>(methodeExtraction, "description"))); + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.valeurMesuree", new PropertyModel<String>( + methodeExtraction, "valeurMesuree"))); + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.uniteResultat", new PropertyModel<String>( + methodeExtraction, "uniteResultat"))); + item.add(new Label("ListMethodeTestBioPanel.MethodesTestBio.critereActivite", + new PropertyModel<String>(methodeExtraction, "critereActivite"))); - // Action : mise à jour (redirection vers le formulaire) - Link<MethodeTestBio> updateLink = new Link<MethodeTestBio>( - "ListMethodeTestBioPanel.MethodesTestBio.Update", new Model<MethodeTestBio>(methodeExtraction)) { - @Override - public void onClick() { - setResponsePage(new ManageMethodeTestBioPage(getModelObject().getIdMethodeTest())); - } - }; - item.add(updateLink); - } - }); + // Action : mise à jour (redirection vers le formulaire) + Link<MethodeTestBio> updateLink = new Link<MethodeTestBio>( + "ListMethodeTestBioPanel.MethodesTestBio.Update", new Model<MethodeTestBio>(methodeExtraction)) { + @Override + public void onClick() { + setResponsePage(new ManageMethodeTestBioPage(getModelObject().getIdMethodeTest())); + } + }; + item.add(updateLink); + } + }); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListPartiePanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListPartiePanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/ListPartiePanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,42 +58,42 @@ * @param id The panel ID */ public ListPartiePanel(String id) { - super(id); + super(id); - add(new BookmarkablePageLink<Void>("ListPartiePanel.NewPartie", ManagePartiePage.class)); + add(new BookmarkablePageLink<Void>("ListPartiePanel.NewPartie", ManagePartiePage.class)); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer partiesRefresh = new WebMarkupContainer("ListPartiePanel.Parties.Refresh"); - partiesRefresh.setOutputMarkupId(true); - add(partiesRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer partiesRefresh = new WebMarkupContainer("ListPartiePanel.Parties.Refresh"); + partiesRefresh.setOutputMarkupId(true); + add(partiesRefresh); - // Liste des parties - final List<Partie> parties = lotService.listParties(); - LoadableDetachableSortableListDataProvider<Partie> partiesDataProvider = new LoadableDetachableSortableListDataProvider<Partie>( - parties, getSession().getLocale()); + // Liste des parties + final List<Partie> parties = lotService.listParties(); + LoadableDetachableSortableListDataProvider<Partie> partiesDataProvider = new LoadableDetachableSortableListDataProvider<Partie>( + parties, getSession().getLocale()); - partiesRefresh.add(new DataView<Partie>("ListPartiePanel.Parties", partiesDataProvider) { - @Override - protected void populateItem(Item<Partie> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + partiesRefresh.add(new DataView<Partie>("ListPartiePanel.Parties", partiesDataProvider) { + @Override + protected void populateItem(Item<Partie> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - Partie partie = item.getModelObject(); - // Colonnes - item.add(new Label("ListPartiePanel.Parties.nom", new PropertyModel<String>(partie, "nom"))); + Partie partie = item.getModelObject(); + // Colonnes + item.add(new Label("ListPartiePanel.Parties.nom", new PropertyModel<String>(partie, "nom"))); - // Action : mise à jour (redirection vers le formulaire) - Link<Partie> updateLink = new Link<Partie>("ListPartiePanel.Parties.Update", new Model<Partie>(partie)) { - @Override - public void onClick() { - setResponsePage(new ManagePartiePage(getModelObject().getIdPartie())); - } - }; - item.add(updateLink); - } - }); + // Action : mise à jour (redirection vers le formulaire) + Link<Partie> updateLink = new Link<Partie>("ListPartiePanel.Parties.Update", new Model<Partie>(partie)) { + @Override + public void onClick() { + setResponsePage(new ManagePartiePage(getModelObject().getIdPartie())); + } + }; + item.add(updateLink); + } + }); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/RebuildLuceneIndexPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/RebuildLuceneIndexPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/config/panels/RebuildLuceneIndexPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,26 +51,26 @@ * @param id The panel ID */ public RebuildLuceneIndexPanel(String id) { - super(id); + super(id); - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - Button addButton = new AjaxFallbackButton("Rebuild", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - rebuildResultLabel.setDefaultModelObject("Rebuilding..."); - searchService.reIndex(); - rebuildResultLabel.setDefaultModelObject("Done."); - } + Button addButton = new AjaxFallbackButton("Rebuild", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + rebuildResultLabel.setDefaultModelObject("Rebuilding..."); + searchService.reIndex(); + rebuildResultLabel.setDefaultModelObject("Done."); + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - - } - }; - formView.add(addButton); - rebuildResultLabel = new Label("rebuildResult", new Model<String>("")); - formView.add(rebuildResultLabel); - add(formView); + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + + } + }; + formView.add(addButton); + rebuildResultLabel = new Label("rebuildResult", new Model<String>("")); + formView.add(rebuildResultLabel); + add(formView); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ManageDocumentPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ManageDocumentPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ManageDocumentPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -112,7 +112,7 @@ * @param multipleEntry Saisie multiple */ public ManageDocumentPage(CallerPage callerPage, DocumentAttachable documentAttachable, boolean multipleEntry) { - this(null, null, documentAttachable, callerPage, multipleEntry); + this(null, null, documentAttachable, callerPage, multipleEntry); } /** @@ -121,7 +121,7 @@ * @param callerPage Page appelante */ public ManageDocumentPage(Integer idDocument, CallerPage callerPage) { - this(idDocument, null, null, callerPage, false); + this(idDocument, null, null, callerPage, false); } /** @@ -130,7 +130,7 @@ * @param callerPage Page appelante */ public ManageDocumentPage(Document document, CallerPage callerPage) { - this(null, document, null, callerPage, true); + this(null, document, null, callerPage, true); } /** @@ -145,208 +145,212 @@ * @param multipleEntry Saisie multiple */ private ManageDocumentPage(Integer idDocument, Document document, final DocumentAttachable documentAttachable, - final CallerPage callerPage, boolean multipleEntry) { - super(ManageDocumentPage.class); - assert idDocument == null || document == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + final CallerPage callerPage, boolean multipleEntry) { + super(ManageDocumentPage.class); + assert idDocument == null || document == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - final CallerPage currentPage = new CallerPage(this); + final CallerPage currentPage = new CallerPage(this); - // Initialisation du modèle - try { - documentModel = new Model<Document>(idDocument == null && document == null ? new Document() : document != null ? document - : documentService.loadDocument(idDocument)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + documentModel = new Model<Document>(idDocument == null && document == null ? new Document() + : document != null ? document : documentService.loadDocument(idDocument)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - boolean createMode = idDocument == null; - if (createMode) { - documentModel.getObject().setCreateur(getSession().getUtilisateur()); - documentModel.getObject().setAjoutePar(getSession().getUtilisateur()); - } + boolean createMode = idDocument == null; + if (createMode) { + documentModel.getObject().setCreateur(getSession().getUtilisateur()); + documentModel.getObject().setAjoutePar(getSession().getUtilisateur()); + } - // Initialisation des listes (pour le dropDownChoice) - List<Personne> personnes = personneService.listPersonnes(); - List<TypeDocument> typeDocuments = documentService.listTypeDocuments(); + // Initialisation des listes (pour le dropDownChoice) + List<Personne> personnes = personneService.listPersonnes(); + List<TypeDocument> typeDocuments = documentService.listTypeDocuments(); - // champ fichier - final FileUploadField fileUploadField = new FileUploadField("Document.fileName"); + // champ fichier + final FileUploadField fileUploadField = new FileUploadField("Document.fileName"); - // initialisation du formulaire wicket - final Form<Void> formView = new Form<Void>("ManageDocumentPage.Form") { - @Override - protected void onSubmit() { - super.onSubmit(); - - - } - }; - formView.setMultiPart(true); - formView.setMaxSize(Bytes.megabytes(1)); + // initialisation du formulaire wicket + final Form<Void> formView = new Form<Void>("ManageDocumentPage.Form") { + @Override + protected void onSubmit() { + super.onSubmit(); - formView.add(new TextField<String>("Document.titre", new PropertyModel<String>(documentModel, "titre"))); + } + }; + formView.setMultiPart(true); + formView.setMaxSize(Bytes.megabytes(1)); - final DropDownChoice<Personne> createurInput = new DropDownChoice<Personne>("Document.createur", - new PropertyModel<Personne>(documentModel, "createur"), personnes); - createurInput.setOutputMarkupId(true); - createurInput.setNullValid(false); - formView.add(createurInput); + formView.add(new TextField<String>("Document.titre", new PropertyModel<String>(documentModel, "titre"))); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(currentPage, false)); - } + final DropDownChoice<Personne> createurInput = new DropDownChoice<Personne>("Document.createur", + new PropertyModel<Personne>(documentModel, "createur"), personnes); + createurInput.setOutputMarkupId(true); + createurInput.setNullValid(false); + formView.add(createurInput); - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(currentPage, false)); - } - }); + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(currentPage, false)); + } - formView.add(new DateTextField("Document.dateCreation", new PropertyModel<Date>(documentModel, "dateCreation")) - .add(new DatePicker())); - formView.add(new TextField<String>("Document.editeur", new PropertyModel<String>(documentModel, "editeur"))); - - formView.add(new TextArea<String>("Document.description", new PropertyModel<String>(documentModel, "description"))); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(currentPage, false)); + } + }); - formView.add(new DropDownChoice<String>("Document.langue", - new PropertyModel<String>(documentModel, "langue"), WebContext.COUNTRY_CODES.get(getSession() - .getLocale()), new MapChoiceRenderer<String, String>(WebContext.COUNTRIES.get(getSession() - .getLocale())))); - formView.add(new TextField<String>("Document.contrainteLegale", new PropertyModel<String>(documentModel, "contrainteLegale"))); + formView.add(new DateTextField("Document.dateCreation", new PropertyModel<Date>(documentModel, "dateCreation")) + .add(new DatePicker())); + formView.add(new TextField<String>("Document.editeur", new PropertyModel<String>(documentModel, "editeur"))); - // AjoutePar en lecture seule - formView.add(new TextField<String>("Document.ajoutePar", new PropertyModel<String>(documentModel, "ajoutePar")) - .setEnabled(false)); + formView.add(new TextArea<String>("Document.description", new PropertyModel<String>(documentModel, + "description"))); - // Type de document - final DropDownChoice<TypeDocument> typeDocumentInput = new DropDownChoice<TypeDocument>("TypeDocument.nom", - new PropertyModel<TypeDocument>(documentModel, "typeDocument"), typeDocuments); - typeDocumentInput.setOutputMarkupId(true); - typeDocumentInput.setNullValid(false); - formView.add(typeDocumentInput); + formView.add(new DropDownChoice<String>("Document.langue", new PropertyModel<String>(documentModel, "langue"), + WebContext.COUNTRY_CODES.get(getSession().getLocale()), new MapChoiceRenderer<String, String>( + WebContext.COUNTRIES.get(getSession().getLocale())))); + formView.add(new TextField<String>("Document.contrainteLegale", new PropertyModel<String>(documentModel, + "contrainteLegale"))); - final Label typeDocumentDomainLabel = new Label("TypeDocument.domaine", new PropertyModel<String>(documentModel, "typeDocument.domaine")); - typeDocumentDomainLabel.setOutputMarkupId(true); - formView.add(typeDocumentDomainLabel); + // AjoutePar en lecture seule + formView.add(new TextField<String>("Document.ajoutePar", new PropertyModel<String>(documentModel, "ajoutePar")) + .setEnabled(false)); - final Label typeDocumentDescriptionLabel = new Label("TypeDocument.description", new PropertyModel<String>(documentModel, "typeDocument.description")); - typeDocumentDescriptionLabel.setOutputMarkupId(true); - formView.add(typeDocumentDescriptionLabel); + // Type de document + final DropDownChoice<TypeDocument> typeDocumentInput = new DropDownChoice<TypeDocument>("TypeDocument.nom", + new PropertyModel<TypeDocument>(documentModel, "typeDocument"), typeDocuments); + typeDocumentInput.setOutputMarkupId(true); + typeDocumentInput.setNullValid(false); + formView.add(typeDocumentInput); - // Fichier - formView.add(fileUploadField); + final Label typeDocumentDomainLabel = new Label("TypeDocument.domaine", new PropertyModel<String>( + documentModel, "typeDocument.domaine")); + typeDocumentDomainLabel.setOutputMarkupId(true); + formView.add(typeDocumentDomainLabel); - // Action : création du document - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - documentAttachable.addDocument(documentModel.getObject()); - } + final Label typeDocumentDescriptionLabel = new Label("TypeDocument.description", new PropertyModel<String>( + documentModel, "typeDocument.description")); + typeDocumentDescriptionLabel.setOutputMarkupId(true); + formView.add(typeDocumentDescriptionLabel); - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + // Fichier + formView.add(fileUploadField); - @Override - public void onValidate() { - final FileUpload uploadedFile = fileUploadField.getFileUpload(); - if (uploadedFile != null) { - documentModel.getObject().setFileContent(uploadedFile.getBytes()); - documentModel.getObject().setFileName(uploadedFile.getClientFileName()); - documentModel.getObject().setFileMimetype(uploadedFile.getContentType()); - - } - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + // Action : création du document + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + documentAttachable.addDocument(documentModel.getObject()); + } - // Action : mise à jour du document - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - // nothing, will be updated by cascade - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onValidate() { + final FileUpload uploadedFile = fileUploadField.getFileUpload(); + if (uploadedFile != null) { + documentModel.getObject().setFileContent(uploadedFile.getBytes()); + documentModel.getObject().setFileName(uploadedFile.getClientFileName()); + documentModel.getObject().setFileMimetype(uploadedFile.getContentType()); - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode - && documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession().getUtilisateur())); - formView.add(updateButton); + } + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : suppression du document - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - documentAttachable.removeDocument(documentModel.getObject()); - } + // Action : mise à jour du document + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + // nothing, will be updated by cascade + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode - && documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession().getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) this.getPage()); - } - }); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode + && documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateButton); - add(formView); + // Action : suppression du document + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + documentAttachable.removeDocument(documentModel.getObject()); + } + + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode + && documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); + + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) this.getPage()); + } + }); + + add(formView); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection vers l'écran de saisie d'un nouveau document, en fournissant déjà quelques données - Document nextDocument = new Document(); - setResponsePage(new ManageDocumentPage(nextDocument, callerPage)); - } else if (callerPage != null) { - // On passe l'id du document associé à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - //callerPage.addPageParameter(Document.class.getSimpleName(), documentModel.getObject().getIdDocument()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection vers l'écran de saisie d'un nouveau document, en fournissant déjà quelques données + Document nextDocument = new Document(); + setResponsePage(new ManageDocumentPage(nextDocument, callerPage)); + } else if (callerPage != null) { + // On passe l'id du document associé à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + //callerPage.addPageParameter(Document.class.getSimpleName(), documentModel.getObject().getIdDocument()); + callerPage.responsePage(this); + } } - + /** * Validate model */ private void validateModel() { - if (documentModel.getObject().getCreateur() == null) { - documentModel.getObject().setCreateur(getSession().getUtilisateur()); - } - addValidationErrors(validator.validate(documentModel.getObject(), getSession().getLocale())); + if (documentModel.getObject().getCreateur() == null) { + documentModel.getObject().setCreateur(getSession().getUtilisateur()); + } + addValidationErrors(validator.validate(documentModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ReadDocumentPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ReadDocumentPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/document/ReadDocumentPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,88 +62,90 @@ * @param idDocument ID document * @param callerPage Page appelante */ - public ReadDocumentPage(final Document document, final DocumentAttachable documentAttachable, final CallerPage callerPage) { - super(ReadDocumentPage.class); - this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage(this); + public ReadDocumentPage(final Document document, final DocumentAttachable documentAttachable, + final CallerPage callerPage) { + super(ReadDocumentPage.class); + this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage(this); - // Initialisation du modèle - documentModel = new Model<Document>(document); - - add(new Label("Document.titre", new PropertyModel<String>(documentModel, "titre")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.createur", new PropertyModel<String>(documentModel, "createur")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.dateCreation", new PropertyModel<String>(documentModel, "dateCreation")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.editeur", new PropertyModel<String>(documentModel, "editeur")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.description", new PropertyModel<String>(documentModel, "description")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.langue", new PropertyModel<String>(documentModel, "langue")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.contrainteLegale", new PropertyModel<String>(documentModel, "contrainteLegale")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.ajoutePar", new PropertyModel<String>(documentModel, "ajoutePar")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("TypeDocument.nom", new PropertyModel<String>(documentModel, "typeDocument.nom")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("TypeDocument.domaine", new PropertyModel<String>(documentModel, "typeDocument.domaine")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("TypeDocument.description", new PropertyModel<String>(documentModel, "typeDocument.description")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.fileName", new PropertyModel<String>(documentModel, "fileName")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Document.fileMimetype", new PropertyModel<String>(documentModel, "fileMimetype")) - .add(new ReplaceEmptyLabelBehavior())); + // Initialisation du modèle + documentModel = new Model<Document>(document); - // Formulaire des actions - final Form<Void> formView = new Form<Void>("Form"); + add(new Label("Document.titre", new PropertyModel<String>(documentModel, "titre")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.createur", new PropertyModel<String>(documentModel, "createur")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.dateCreation", new PropertyModel<String>(documentModel, "dateCreation")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.editeur", new PropertyModel<String>(documentModel, "editeur")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.description", new PropertyModel<String>(documentModel, "description")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.langue", new PropertyModel<String>(documentModel, "langue")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.contrainteLegale", new PropertyModel<String>(documentModel, "contrainteLegale")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.ajoutePar", new PropertyModel<String>(documentModel, "ajoutePar")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TypeDocument.nom", new PropertyModel<String>(documentModel, "typeDocument.nom")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TypeDocument.domaine", new PropertyModel<String>(documentModel, "typeDocument.domaine")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TypeDocument.description", new PropertyModel<String>(documentModel, "typeDocument.description")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.fileName", new PropertyModel<String>(documentModel, "fileName")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Document.fileMimetype", new PropertyModel<String>(documentModel, "fileMimetype")) + .add(new ReplaceEmptyLabelBehavior())); - // Action : mise à jour (redirection vers le formulaire) - Link<Document> updateLink = new Link<Document>(getResource() + ".Document.Update", new Model<Document>(documentModel.getObject())) { - @Override - public void onClick() { - setResponsePage(new ManageDocumentPage(getModelObject().getIdDocument(), currentPage)); - } - }; - //FIXME updateLink.setVisibilityAllowed(documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() - // .getUtilisateur())); - formView.add(updateLink); + // Formulaire des actions + final Form<Void> formView = new Form<Void>("Form"); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - documentAttachable.removeDocument(documentModel.getObject()); - } + // Action : mise à jour (redirection vers le formulaire) + Link<Document> updateLink = new Link<Document>(getResource() + ".Document.Update", new Model<Document>( + documentModel.getObject())) { + @Override + public void onClick() { + setResponsePage(new ManageDocumentPage(getModelObject().getIdDocument(), currentPage)); + } + }; + //FIXME updateLink.setVisibilityAllowed(documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() + // .getUtilisateur())); + formView.add(updateLink); - @Override - public void onSuccess() { - successNextPage(ManageDocumentPage.class, ACTION_DELETE); - redirect(); - } - }); - // FIXME deleteButton.setVisibilityAllowed(documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() - // .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + documentAttachable.removeDocument(documentModel.getObject()); + } - // Action : retour - formView.add(new Link<Void>(getResource() + ".Document.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManageDocumentPage.class, ACTION_DELETE); + redirect(); + } + }); + // FIXME deleteButton.setVisibilityAllowed(documentService.updateOrdeleteDocumentEnabled(documentModel.getObject(), getSession() + // .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); + + // Action : retour + formView.add(new Link<Void>(getResource() + ".Document.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ExtraitsColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ExtraitsColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ExtraitsColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -46,7 +46,8 @@ * * @author Eric Chatellier */ -public class ExtraitsColumn extends AbstractColumn<Extraction, String> implements IExportableColumn<Extraction, String, Serializable> { +public class ExtraitsColumn extends AbstractColumn<Extraction, String> implements + IExportableColumn<Extraction, String, Serializable> { /** Nombre d'extraits affichés dans la colonne de résumés des extraits. */ private static final int MAX_EXTRAITS_DISPLAY = 4; @@ -61,59 +62,60 @@ * @param locale locale */ public ExtraitsColumn(IModel<String> displayModel, Locale locale) { - super(displayModel); - this.locale = locale; + super(displayModel); + this.locale = locale; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<Extraction>> cellItem, String componentId, IModel<Extraction> rowModel) { - // affiche un résumé des types extraits et des masses, allant jusqu'à MAX_EXTRAITS_DISPLAY extraits - Label extraitsLabel = new Label(componentId, getDataModel(rowModel, true)); - extraitsLabel.setEscapeModelStrings(false); - extraitsLabel.add(new ReplaceEmptyLabelBehavior()); - cellItem.add(extraitsLabel); + // affiche un résumé des types extraits et des masses, allant jusqu'à MAX_EXTRAITS_DISPLAY extraits + Label extraitsLabel = new Label(componentId, getDataModel(rowModel, true)); + extraitsLabel.setEscapeModelStrings(false); + extraitsLabel.add(new ReplaceEmptyLabelBehavior()); + cellItem.add(extraitsLabel); } /** {@inheritDoc} */ @Override public IModel<Serializable> getDataModel(IModel<Extraction> rowModel) { - return getDataModel(rowModel, false); + return getDataModel(rowModel, false); } - + /** * Improve data model to support optionnal html formatting. */ protected IModel<Serializable> getDataModel(IModel<Extraction> rowModel, final boolean html) { - return new Model<Serializable>(rowModel) { - /** {@inheritDoc} */ - @Override - public String getObject() { - StringBuilder extraitsResume = new StringBuilder(); - List<Extrait> extraits = new PropertyModel<List<Extrait>>(super.getObject(), "sortedExtraits") - .getObject(); - for (int i = 0; i < MAX_EXTRAITS_DISPLAY && i < extraits.size(); i++) { - Extrait curExtrait = extraits.get(i); - if (html) { - extraitsResume.append("<b>"); - } - extraitsResume.append(curExtrait.getTypeExtrait().getInitiales()); - if (html) { - extraitsResume.append("</b>"); - } - extraitsResume.append(" : "); - extraitsResume.append(curExtrait.getMasseObtenue() == null ? ReplaceEmptyLabelBehavior.NULL_PROPERTY - : new DisplayDecimalPropertyModel(curExtrait, "masseObtenue", - DecimalDisplFormat.SMALL, locale).getObject()); - if (i < MAX_EXTRAITS_DISPLAY - 1 && i < extraits.size() - 1) { - extraitsResume.append(", "); - } - if (i == MAX_EXTRAITS_DISPLAY - 1 && i < extraits.size() - 1) { - extraitsResume.append(", ..."); - } - } - return extraitsResume.toString(); - } - }; + return new Model<Serializable>(rowModel) { + /** {@inheritDoc} */ + @Override + public String getObject() { + StringBuilder extraitsResume = new StringBuilder(); + List<Extrait> extraits = new PropertyModel<List<Extrait>>(super.getObject(), "sortedExtraits") + .getObject(); + for (int i = 0; i < MAX_EXTRAITS_DISPLAY && i < extraits.size(); i++) { + Extrait curExtrait = extraits.get(i); + if (html) { + extraitsResume.append("<b>"); + } + extraitsResume.append(curExtrait.getTypeExtrait().getInitiales()); + if (html) { + extraitsResume.append("</b>"); + } + extraitsResume.append(" : "); + extraitsResume + .append(curExtrait.getMasseObtenue() == null ? ReplaceEmptyLabelBehavior.NULL_PROPERTY + : new DisplayDecimalPropertyModel(curExtrait, "masseObtenue", + DecimalDisplFormat.SMALL, locale).getObject()); + if (i < MAX_EXTRAITS_DISPLAY - 1 && i < extraits.size() - 1) { + extraitsResume.append(", "); + } + if (i == MAX_EXTRAITS_DISPLAY - 1 && i < extraits.size() - 1) { + extraitsResume.append(", ..."); + } + } + return extraitsResume.toString(); + } + }; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ListExtractionsPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ListExtractionsPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ListExtractionsPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -60,7 +60,7 @@ * Page de consultation des extractions * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ListExtractionsPage extends TemplatePage { /** Service : manipExtraction */ @@ -71,30 +71,30 @@ * Constructeur */ public ListExtractionsPage() { - super(ListExtractionsPage.class); + super(ListExtractionsPage.class); - final CallerPage currentPage = new CallerPage(ListExtractionsPage.class); + final CallerPage currentPage = new CallerPage(ListExtractionsPage.class); - add(new Link<Void>(getResource() + ".NewExtraction") { - @Override - public void onClick() { - setResponsePage(new ManageExtractionPage(currentPage, true)); - } - }); + add(new Link<Void>(getResource() + ".NewExtraction") { + @Override + public void onClick() { + setResponsePage(new ManageExtractionPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer extractionsRefresh = new WebMarkupContainer(getResource() + ".Extractions.Refresh"); - extractionsRefresh.setOutputMarkupId(true); - add(extractionsRefresh); - - // Liste des Extractions - final List<Extraction> extractions = extractionService.listExtractions(getSession().getUtilisateur()); - - DataTable<Extraction, String> extractionsDataTable = initExtractionsDataTable(this, - "ListExtractionsPage.Extractions", currentPage, extractions, extractionService); - extractionsRefresh.add(extractionsDataTable); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer extractionsRefresh = new WebMarkupContainer(getResource() + ".Extractions.Refresh"); + extractionsRefresh.setOutputMarkupId(true); + add(extractionsRefresh); + // Liste des Extractions + final List<Extraction> extractions = extractionService.listExtractions(getSession().getUtilisateur()); + + DataTable<Extraction, String> extractionsDataTable = initExtractionsDataTable(this, + "ListExtractionsPage.Extractions", currentPage, extractions, extractionService); + extractionsRefresh.add(extractionsDataTable); + } /** @@ -110,79 +110,84 @@ * @return data table component */ public static DataTable<Extraction, String> initExtractionsDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<Extraction> extractions, final ExtractionService extractionService) { + final String componentId, final CallerPage callerPage, List<Extraction> extractions, + final ExtractionService extractionService) { - LoadableDetachableSortableListDataProvider<Extraction> extractionsDataProvider = new LoadableDetachableSortableListDataProvider<Extraction>( - extractions, templatePage.getSession().getLocale()); + LoadableDetachableSortableListDataProvider<Extraction> extractionsDataProvider = new LoadableDetachableSortableListDataProvider<Extraction>( + extractions, templatePage.getSession().getLocale()); - List<IColumn<Extraction, String>> columns = new ArrayList<IColumn<Extraction, String>>(); + List<IColumn<Extraction, String>> columns = new ArrayList<IColumn<Extraction, String>>(); - columns.add(new LinkableImagePropertyColumn<Extraction, String>("images/read.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - templatePage.setResponsePage(new ReadExtractionPage(model.getObject().getIdExtraction(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Extraction, String>("images/read.png", templatePage + .getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + templatePage.setResponsePage(new ReadExtractionPage(model.getObject().getIdExtraction(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Extraction.lot")), "lot", "lot", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - templatePage.setResponsePage(new ReadLotPage(model.getObject().getLot().getIdLot(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage + .getString("Extraction.lot")), "lot", "lot", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + templatePage.setResponsePage(new ReadLotPage(model.getObject().getLot().getIdLot(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Extraction.ref")), "ref", "ref", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - templatePage.setResponsePage(new ReadExtractionPage(model.getObject().getIdExtraction(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage + .getString("Extraction.ref")), "ref", "ref", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + templatePage.setResponsePage(new ReadExtractionPage(model.getObject().getIdExtraction(), callerPage)); + } + }); - columns.add(new ShortDatePropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Extraction.date")), "date", - "date", templatePage.getLocale())); + columns.add(new ShortDatePropertyColumn<Extraction, String>(new Model<String>(templatePage + .getString("Extraction.date")), "date", "date", templatePage.getLocale())); - columns.add(new PropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Extraction.methode2")), "methode", - "methode")); + columns.add(new PropertyColumn<Extraction, String>(new Model<String>(templatePage + .getString("Extraction.methode2")), "methode", "methode")); - columns.add(new DecimalPropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Extraction.masseDepart2")), - "masseDepart", "masseDepart", DecimalDisplFormat.SMALL, templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<Extraction, String>(new Model<String>(templatePage + .getString("Extraction.masseDepart2")), "masseDepart", "masseDepart", DecimalDisplFormat.SMALL, + templatePage.getLocale())); - columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Campagne")), "lot.campagne", - "lot.campagne", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getLot().getCampagne().getIdCampagne(), - callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Extraction, String>(new Model<String>(templatePage.getString("Campagne")), + "lot.campagne", "lot.campagne", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getLot().getCampagne() + .getIdCampagne(), callerPage)); + } + }); - columns.add(new ExtraitsColumn(new Model<String>(templatePage.getString("Extraction.extraits")), templatePage.getLocale())); + columns.add(new ExtraitsColumn(new Model<String>(templatePage.getString("Extraction.extraits")), templatePage + .getLocale())); - columns.add(new LinkableImagePropertyColumn<Extraction, String>("images/edit.png", templatePage.getString("Update"), - templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - if (extractionService.updateOrdeleteExtractionEnabled(model.getObject(), templatePage.getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + columns.add(new LinkableImagePropertyColumn<Extraction, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + if (extractionService.updateOrdeleteExtractionEnabled(model.getObject(), templatePage.getSession() + .getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { - templatePage.setResponsePage(new ManageExtractionPage(model.getObject().getIdExtraction(), callerPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<Extraction>> item, String componentId, IModel<Extraction> model) { + templatePage.setResponsePage(new ManageExtractionPage(model.getObject().getIdExtraction(), callerPage)); + } + }); - final DataTable<Extraction, String> extractionsDataTable = new AjaxFallbackDefaultDataTable<Extraction, String>( - componentId, columns, extractionsDataProvider, WebContext.ROWS_PER_PAGE); - extractionsDataTable.addBottomToolbar(new TableExportToolbar(extractionsDataTable, "extractions", templatePage.getSession().getLocale())); - return extractionsDataTable; + final DataTable<Extraction, String> extractionsDataTable = new AjaxFallbackDefaultDataTable<Extraction, String>( + componentId, columns, extractionsDataProvider, WebContext.ROWS_PER_PAGE); + extractionsDataTable.addBottomToolbar(new TableExportToolbar(extractionsDataTable, "extractions", templatePage + .getSession().getLocale())); + return extractionsDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ManageExtractionPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ManageExtractionPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ManageExtractionPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -94,7 +94,7 @@ * Page for adding/update/delete a new "Extraction" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManageExtractionPage extends TemplatePage { /** Action : create */ @@ -189,7 +189,7 @@ * @param multipleEntry Saisie multiple */ public ManageExtractionPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -198,7 +198,7 @@ * @param callerPage Page appelante */ public ManageExtractionPage(Integer idManip, CallerPage callerPage) { - this(idManip, null, callerPage, false); + this(idManip, null, callerPage, false); } /** @@ -207,7 +207,7 @@ * @param callerPage Page appelante */ public ManageExtractionPage(Extraction manip, CallerPage callerPage) { - this(null, manip, callerPage, true); + this(null, manip, callerPage, true); } /** @@ -220,128 +220,128 @@ * @param multipleEntry Saisie multiple */ private ManageExtractionPage(Integer idManip, Extraction manip, final CallerPage callerPage, boolean multipleEntry) { - super(ManageExtractionPage.class); - assert idManip == null || manip == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManageExtractionPage.class); + assert idManip == null || manip == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - extraitsDeleted = new HashMap<String, Integer>(); - newExtraitModel = new Model<Extrait>(new Extrait()); + extraitsDeleted = new HashMap<String, Integer>(); + newExtraitModel = new Model<Extrait>(new Extrait()); - // Initialisation du modèle - try { - extractionModel = new Model<Extraction>(idManip == null && manip == null ? new Extraction() - : manip != null ? manip : extractionService.loadExtraction(idManip)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + extractionModel = new Model<Extraction>(idManip == null && manip == null ? new Extraction() + : manip != null ? manip : extractionService.loadExtraction(idManip)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - createMode = idManip == null; - if (createMode) { - extractionModel.getObject().setCreateur(getSession().getUtilisateur()); - } + createMode = idManip == null; + if (createMode) { + extractionModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes (pour le dropDownChoice) - personnes = personneService.listPersonnes(); - methodes = extractionService.listMethodesExtraction(); - lots = lotService.listLots(getSession().getUtilisateur()); + // Initialisation des listes (pour le dropDownChoice) + personnes = personneService.listPersonnes(); + methodes = extractionService.listMethodesExtraction(); + lots = lotService.listLots(getSession().getUtilisateur()); - if (manip != null) { - // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que - // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas - // l'égalité entre les objets) - extractionModel.getObject().setManipulateur( - CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, extractionModel - .getObject().getManipulateur().getIdPersonne())); - extractionModel.getObject().setMethode( - CollectionTools.findWithValue(methodes, "idMethodeExtraction", AccessType.GETTER, extractionModel - .getObject().getMethode().getIdMethodeExtraction())); - } + if (manip != null) { + // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que + // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas + // l'égalité entre les objets) + extractionModel.getObject().setManipulateur( + CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, extractionModel + .getObject().getManipulateur().getIdPersonne())); + extractionModel.getObject().setMethode( + CollectionTools.findWithValue(methodes, "idMethodeExtraction", AccessType.GETTER, extractionModel + .getObject().getMethode().getIdMethodeExtraction())); + } - typesExtrait = new ArrayList<TypeExtrait>(); + typesExtrait = new ArrayList<TypeExtrait>(); - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - initPrincipalFields(formView); + initPrincipalFields(formView); - initMethodeFields(formView); + initMethodeFields(formView); - initExtraitsFields(formView); + initExtraitsFields(formView); - // Action : create the extraction - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extractionService.createExtraction(extractionModel.getObject()); - } + // Action : create the extraction + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extractionService.createExtraction(extractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); + @Override + public void onValidate() { + validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the extraction - Button updateButton = new SubmittableButton(ACTION_UPDATE, ManageExtractionPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extractionService.updateExtraction(extractionModel.getObject()); - } + // Action : update the extraction + Button updateButton = new SubmittableButton(ACTION_UPDATE, ManageExtractionPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extractionService.updateExtraction(extractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extractionService.deleteExtraction(extractionModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extractionService.deleteExtraction(extractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - formView.setDefaultButton(addExtraitButton); - add(formView); + formView.setDefaultButton(addExtraitButton); + add(formView); } /** @@ -349,75 +349,75 @@ * @param formView le formulaire */ private void initPrincipalFields(final Form<Void> formView) { - formView.add(new TextField<String>("Extraction.ref", new PropertyModel<String>(extractionModel, "ref"))); + formView.add(new TextField<String>("Extraction.ref", new PropertyModel<String>(extractionModel, "ref"))); - DropDownChoice<Personne> pers = new DropDownChoice<Personne>("Extraction.manipulateur", - new PropertyModel<Personne>(extractionModel, "manipulateur"), personnes, new PersonneRenderer()); - pers.setNullValid(false); + DropDownChoice<Personne> pers = new DropDownChoice<Personne>("Extraction.manipulateur", + new PropertyModel<Personne>(extractionModel, "manipulateur"), personnes, new PersonneRenderer()); + pers.setNullValid(false); - pers.setModelObject(extractionModel.getObject().getManipulateur()); - formView.add(pers); - pers.getChoices().indexOf(pers.getModelObject()); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } + pers.setModelObject(extractionModel.getObject().getManipulateur()); + formView.add(pers); + pers.getChoices().indexOf(pers.getModelObject()); + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } + }); - formView.add(new DateTextField("Extraction.date", new PropertyModel<Date>(extractionModel, "date")) - .add(new DatePicker())); + formView.add(new DateTextField("Extraction.date", new PropertyModel<Date>(extractionModel, "date")) + .add(new DatePicker())); - final AbstractSingleSelectChoice<Lot> lotsChoice = new DropDownChoice<Lot>("Extraction.lot", - new PropertyModel<Lot>(extractionModel, "lot"), lots); - lotsChoice.setNullValid(false); - lotsChoice.setEnabled(createMode); - lotsChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - updateRefExtrait(target); - } - }); - formView.add(lotsChoice); + final AbstractSingleSelectChoice<Lot> lotsChoice = new DropDownChoice<Lot>("Extraction.lot", + new PropertyModel<Lot>(extractionModel, "lot"), lots); + lotsChoice.setNullValid(false); + lotsChoice.setEnabled(createMode); + lotsChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + updateRefExtrait(target); + } + }); + formView.add(lotsChoice); - // Action : création d'un nouveau lot - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - AbstractLink newLot = new AjaxSubmitLink("NewLot") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManageLotPage(new CallerPage((TemplatePage) getPage()), false)); - } + // Action : création d'un nouveau lot + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + AbstractLink newLot = new AjaxSubmitLink("NewLot") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManageLotPage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageLotPage(new CallerPage((TemplatePage) getPage()), false)); - } - }; - newLot.setOutputMarkupPlaceholderTag(true); - newLot.setVisibilityAllowed(createMode); - formView.add(newLot); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageLotPage(new CallerPage((TemplatePage) getPage()), false)); + } + }; + newLot.setOutputMarkupPlaceholderTag(true); + newLot.setVisibilityAllowed(createMode); + formView.add(newLot); - TextField<BigDecimal> masseDepartInput = new TextField<BigDecimal>("Extraction.masseDepart", - new PropertyModel<BigDecimal>(extractionModel, "masseDepart")); - masseDepartInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - }; - }); - formView.add(masseDepartInput); + TextField<BigDecimal> masseDepartInput = new TextField<BigDecimal>("Extraction.masseDepart", + new PropertyModel<BigDecimal>(extractionModel, "masseDepart")); + masseDepartInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + }; + }); + formView.add(masseDepartInput); - formView.add(new TextArea<String>("Extraction.complement", new PropertyModel<String>(extractionModel, - "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("Extraction.createur", - new PropertyModel<String>(extractionModel, "createur")).setEnabled(false)); + formView.add(new TextArea<String>("Extraction.complement", new PropertyModel<String>(extractionModel, + "complement"))); + // Créateur en lecture seule + formView.add(new TextField<String>("Extraction.createur", + new PropertyModel<String>(extractionModel, "createur")).setEnabled(false)); } /** @@ -425,45 +425,45 @@ * @param formView le formulaire */ private void initMethodeFields(final Form<Void> formView) { - // Champs méthode + // Champs méthode - final WebMarkupContainer descriptionMethoContainer = new WebMarkupContainer("TestBio.descriptionMethodeCont") { - @Override - public boolean isVisible() { - // description cachée si pas de méthode sélectionnée - return extractionModel.getObject().getMethode() != null; - } - }; - descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax - descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); // pour accéder à l'élement html qd son état est - // non visible - formView.add(descriptionMethoContainer); + final WebMarkupContainer descriptionMethoContainer = new WebMarkupContainer("TestBio.descriptionMethodeCont") { + @Override + public boolean isVisible() { + // description cachée si pas de méthode sélectionnée + return extractionModel.getObject().getMethode() != null; + } + }; + descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax + descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); // pour accéder à l'élement html qd son état est + // non visible + formView.add(descriptionMethoContainer); - descriptionMethoContainer.add(new MultiLineLabel("Extraction.methode.description", new PropertyModel<String>( - extractionModel, "methode.description"))); + descriptionMethoContainer.add(new MultiLineLabel("Extraction.methode.description", new PropertyModel<String>( + extractionModel, "methode.description"))); - final DropDownChoice<MethodeExtraction> methodeChoice = new DropDownChoice<MethodeExtraction>( - "Extraction.methode.nom", new PropertyModel<MethodeExtraction>(extractionModel, "methode"), methodes); - methodeChoice.setNullValid(false); - methodeChoice.setOutputMarkupId(true); // pour l'update Ajax - // mise à jour de la description de la méthode et des extraits lors de la sélection de la méthode - methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - extractionModel.getObject().getExtraits().clear(); - // maj de la liste des typesExtraits suivant la sélection - typesExtrait.clear(); - if (extractionModel.getObject().getMethode() != null) { - // rafraichi la méthode pour pouvoir accéder aux types en sortie accédés en LAZY - extractionService.refreshMethodeExtraction(extractionModel.getObject().getMethode()); - typesExtrait.addAll(extractionModel.getObject().getMethode().getSortedTypesEnSortie()); - } - // mise à jour de typesExtrait - updateTypesExtrait(true, target); + final DropDownChoice<MethodeExtraction> methodeChoice = new DropDownChoice<MethodeExtraction>( + "Extraction.methode.nom", new PropertyModel<MethodeExtraction>(extractionModel, "methode"), methodes); + methodeChoice.setNullValid(false); + methodeChoice.setOutputMarkupId(true); // pour l'update Ajax + // mise à jour de la description de la méthode et des extraits lors de la sélection de la méthode + methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + extractionModel.getObject().getExtraits().clear(); + // maj de la liste des typesExtraits suivant la sélection + typesExtrait.clear(); + if (extractionModel.getObject().getMethode() != null) { + // rafraichi la méthode pour pouvoir accéder aux types en sortie accédés en LAZY + extractionService.refreshMethodeExtraction(extractionModel.getObject().getMethode()); + typesExtrait.addAll(extractionModel.getObject().getMethode().getSortedTypesEnSortie()); + } + // mise à jour de typesExtrait + updateTypesExtrait(true, target); - target.add(methodeChoice, descriptionMethoContainer); - } - }); - formView.add(methodeChoice); + target.add(methodeChoice, descriptionMethoContainer); + } + }); + formView.add(methodeChoice); } /** @@ -472,228 +472,228 @@ */ private void initExtraitsFields(final Form<Void> formView) { - extraitsTable = new WebMarkupContainer("Extraction.extraits.Table"); - // Contenu tableaux extrait - // Liste des types extraits ajoutés (pour raffraichissements) - extraitsTable.add(new ListView<Extrait>("Extraction.extraits.List", new PropertyModel<List<Extrait>>( - extractionModel, "sortedExtraits")) { - @Override - protected void populateItem(ListItem<Extrait> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + extraitsTable = new WebMarkupContainer("Extraction.extraits.Table"); + // Contenu tableaux extrait + // Liste des types extraits ajoutés (pour raffraichissements) + extraitsTable.add(new ListView<Extrait>("Extraction.extraits.List", new PropertyModel<List<Extrait>>( + extractionModel, "sortedExtraits")) { + @Override + protected void populateItem(ListItem<Extrait> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - IModel<Extrait> extraitModel = item.getModel(); - final Extrait extrait = item.getModelObject(); - // Colonnes - item.add(new Label("Extraction.extraits.List.typeExtrait", new PropertyModel<String>(extrait, - "typeExtrait"))); - // info-bulle comprenant la description du type d'extrait - item.add(new SimpleTooltipPanel("Extraction.extraits.List.typeExtrait.info", new PropertyModel<String>( - extrait, "typeExtrait.description"))); - item.add(new Label("Extraction.extraits.List.ref", new PropertyModel<String>(extrait, "ref"))); - item.add(new Label("Extraction.extraits.List.masseObtenue", new PropertyModel<String>(extrait, - "masseObtenue"))); + IModel<Extrait> extraitModel = item.getModel(); + final Extrait extrait = item.getModelObject(); + // Colonnes + item.add(new Label("Extraction.extraits.List.typeExtrait", new PropertyModel<String>(extrait, + "typeExtrait"))); + // info-bulle comprenant la description du type d'extrait + item.add(new SimpleTooltipPanel("Extraction.extraits.List.typeExtrait.info", new PropertyModel<String>( + extrait, "typeExtrait.description"))); + item.add(new Label("Extraction.extraits.List.ref", new PropertyModel<String>(extrait, "ref"))); + item.add(new Label("Extraction.extraits.List.masseObtenue", new PropertyModel<String>(extrait, + "masseObtenue"))); - item.add(new Label("Extraction.extraits.List.rendement", new DisplayPercentPropertyModel(extraitModel, - "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Extraction.extraits.List.rendement", new DisplayPercentPropertyModel(extraitModel, + "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); - // Action : suppression d'un extrait - Button deleteButton = new AjaxFallbackButton("Extraction.extraits.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // vérification si des données liées existe - if (produitService.isProduitReferenced(extrait)) { - getPage().error(getString("Extrait.isReferenced")); - } else { - // Suppression - extractionModel.getObject().getExtraits().remove(extrait); - // keep the id of the deleted 'extrait' for the case of a new one with the same 'ref' - extraitsDeleted.put(extrait.getRef(), extrait.getId()); + // Action : suppression d'un extrait + Button deleteButton = new AjaxFallbackButton("Extraction.extraits.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // vérification si des données liées existe + if (produitService.isProduitReferenced(extrait)) { + getPage().error(getString("Extrait.isReferenced")); + } else { + // Suppression + extractionModel.getObject().getExtraits().remove(extrait); + // keep the id of the deleted 'extrait' for the case of a new one with the same 'ref' + extraitsDeleted.put(extrait.getRef(), extrait.getId()); - // mise à jour de l'extrait - updateTypesExtrait(false, target); - } - if (target != null) { - target.add(extraitsTable); - refreshFeedbackPage(target); - } - } + // mise à jour de l'extrait + updateTypesExtrait(false, target); + } + if (target != null) { + target.add(extraitsTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); - extraitsTable.setOutputMarkupId(true); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); + extraitsTable.setOutputMarkupId(true); - typeExtraitInput = new DropDownChoice<TypeExtrait>("Extraction.extraits.typeExtrait", - new PropertyModel<TypeExtrait>(newExtraitModel, "typeExtrait"), typesExtrait).setNullValid(false); - // info-bulle comprenant la description du type d'extrait - typeExtraitTooltip = new SimpleTooltipPanel("Extraction.extraits.typeExtrait.info", new PropertyModel<String>( - newExtraitModel, "typeExtrait.description")); - // permet la mise en visibité ou non en Ajax - typeExtraitTooltip.setOutputMarkupId(true); - typeExtraitTooltip.setOutputMarkupPlaceholderTag(true); - extraitsTable.add(typeExtraitTooltip); + typeExtraitInput = new DropDownChoice<TypeExtrait>("Extraction.extraits.typeExtrait", + new PropertyModel<TypeExtrait>(newExtraitModel, "typeExtrait"), typesExtrait).setNullValid(false); + // info-bulle comprenant la description du type d'extrait + typeExtraitTooltip = new SimpleTooltipPanel("Extraction.extraits.typeExtrait.info", new PropertyModel<String>( + newExtraitModel, "typeExtrait.description")); + // permet la mise en visibité ou non en Ajax + typeExtraitTooltip.setOutputMarkupId(true); + typeExtraitTooltip.setOutputMarkupPlaceholderTag(true); + extraitsTable.add(typeExtraitTooltip); - typeExtraitInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - updateRefExtrait(target); - target.add(typeExtraitTooltip); - } - }); - extraitsTable.add(typeExtraitInput); + typeExtraitInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + updateRefExtrait(target); + target.add(typeExtraitTooltip); + } + }); + extraitsTable.add(typeExtraitInput); - refInput = new TextField<String>("Extraction.extraits.ref", new PropertyModel<String>(newExtraitModel, "ref")); - refInput.setOutputMarkupId(true); - extraitsTable.add(refInput); + refInput = new TextField<String>("Extraction.extraits.ref", new PropertyModel<String>(newExtraitModel, "ref")); + refInput.setOutputMarkupId(true); + extraitsTable.add(refInput); - masseObtenueInput = new TextField<BigDecimal>("Extraction.extraits.masseObtenue", - new PropertyModel<BigDecimal>(newExtraitModel, "masseObtenue")); - masseObtenueInput.setOutputMarkupId(true); - extraitsTable.add(masseObtenueInput); + masseObtenueInput = new TextField<BigDecimal>("Extraction.extraits.masseObtenue", + new PropertyModel<BigDecimal>(newExtraitModel, "masseObtenue")); + masseObtenueInput.setOutputMarkupId(true); + extraitsTable.add(masseObtenueInput); - // Bouton AJAX pour ajouter un extrait - addExtraitButton = new AjaxFallbackButton("Extraction.extraits.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // normalisation de l'extrait - newExtraitModel.getObject().setRef( - Normalizer.normalize(UniqueFieldNormalizer.class, newExtraitModel.getObject().getRef())); - // Ajout du type extrait - newExtraitModel.getObject().setExtraction(extractionModel.getObject()); - // recuperate the id if an just deleted type, null otherwise - newExtraitModel.getObject().setId(extraitsDeleted.get(newExtraitModel.getObject().getRef())); + // Bouton AJAX pour ajouter un extrait + addExtraitButton = new AjaxFallbackButton("Extraction.extraits.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // normalisation de l'extrait + newExtraitModel.getObject().setRef( + Normalizer.normalize(UniqueFieldNormalizer.class, newExtraitModel.getObject().getRef())); + // Ajout du type extrait + newExtraitModel.getObject().setExtraction(extractionModel.getObject()); + // recuperate the id if an just deleted type, null otherwise + newExtraitModel.getObject().setId(extraitsDeleted.get(newExtraitModel.getObject().getRef())); - // ajout à la liste - Extrait extraitAdded = newExtraitModel.getObject().clone(); - extractionModel.getObject().getExtraits().add(extraitAdded); + // ajout à la liste + Extrait extraitAdded = newExtraitModel.getObject().clone(); + extractionModel.getObject().getExtraits().add(extraitAdded); - List<String> errors = validator.validate(newExtraitModel.getObject(), getSession().getLocale()); - // test si unicité dans la base - // erreur si non unique dans la base ET extrait de même réf non supprimé de la liste (dans ce - // dernier cas, ajout avec son ancien id) ET non pris en compte par la validation de - // CollectionUniqueFieldValidator - if (!extractionService.isExtraitUnique(extraitAdded) - && extraitAdded.getRef() != null - && extraitsDeleted.get(extraitAdded.getRef()) == null - && CollectionTools.countWithValue(extraitAdded.getExtraction().getExtraits(), "ref", - AccessType.GETTER, extraitAdded.getRef()) == 1) { - errors.add(getString("Extrait.notUnique")); - } + List<String> errors = validator.validate(newExtraitModel.getObject(), getSession().getLocale()); + // test si unicité dans la base + // erreur si non unique dans la base ET extrait de même réf non supprimé de la liste (dans ce + // dernier cas, ajout avec son ancien id) ET non pris en compte par la validation de + // CollectionUniqueFieldValidator + if (!extractionService.isExtraitUnique(extraitAdded) + && extraitAdded.getRef() != null + && extraitsDeleted.get(extraitAdded.getRef()) == null + && CollectionTools.countWithValue(extraitAdded.getExtraction().getExtraits(), "ref", + AccessType.GETTER, extraitAdded.getRef()) == 1) { + errors.add(getString("Extrait.notUnique")); + } - if (errors.isEmpty()) { - // réinit du champ ajout - newExtraitModel.getObject().setRef(null); - newExtraitModel.getObject().setMasseObtenue(null); + if (errors.isEmpty()) { + // réinit du champ ajout + newExtraitModel.getObject().setRef(null); + newExtraitModel.getObject().setMasseObtenue(null); - // mise à jour de typesExtrait - updateTypesExtrait(true, target); - } else { - extractionModel.getObject().getExtraits().remove(extraitAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // mise à jour de typesExtrait + updateTypesExtrait(true, target); + } else { + extractionModel.getObject().getExtraits().remove(extraitAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - if (target != null) { - target.add(extraitsTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(extraitsTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - addExtraitButton.setOutputMarkupId(true); - extraitsTable.add(addExtraitButton); + }; + addExtraitButton.setOutputMarkupId(true); + extraitsTable.add(addExtraitButton); - formView.add(extraitsTable); - updateTypesExtrait(true, null); + formView.add(extraitsTable); + updateTypesExtrait(true, null); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Personne ou Lot) - refreshModel(); - super.onBeforeRender(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Personne ou Lot) + refreshModel(); + super.onBeforeRender(); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection de nouveau vers l'écran de saisie d'une nouvelle extraction - Extraction nextManip = new Extraction(); - nextManip.setManipulateur(extractionModel.getObject().getManipulateur()); - nextManip.setMethode(extractionModel.getObject().getMethode()); - nextManip.setMasseDepart(extractionModel.getObject().getMasseDepart()); - setResponsePage(new ManageExtractionPage(nextManip, callerPage)); - } else if (callerPage != null) { - // On passe l'id de l'extraction associée à cette page, en paramètre de la prochaine page, pour lui - // permettre de - // l'exploiter si besoin - callerPage - .addPageParameter(Extraction.class.getSimpleName(), extractionModel.getObject().getIdExtraction()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection de nouveau vers l'écran de saisie d'une nouvelle extraction + Extraction nextManip = new Extraction(); + nextManip.setManipulateur(extractionModel.getObject().getManipulateur()); + nextManip.setMethode(extractionModel.getObject().getMethode()); + nextManip.setMasseDepart(extractionModel.getObject().getMasseDepart()); + setResponsePage(new ManageExtractionPage(nextManip, callerPage)); + } else if (callerPage != null) { + // On passe l'id de l'extraction associée à cette page, en paramètre de la prochaine page, pour lui + // permettre de + // l'exploiter si besoin + callerPage + .addPageParameter(Extraction.class.getSimpleName(), extractionModel.getObject().getIdExtraction()); + callerPage.responsePage(this); + } } /** * Refresh model, appelé au rechargement de la page */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Personne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(personnes, personneService.listPersonnes()); - try { - Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); - extractionModel.getObject().setManipulateur(createdPersonne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Personne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(personnes, personneService.listPersonnes()); + try { + Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); + extractionModel.getObject().setManipulateur(createdPersonne); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } - key = Lot.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(lots, lotService.listLots(getSession().getUtilisateur())); - try { - Lot createdLot = lotService.loadLot(getPageParameters().get(key).toInt()); - extractionModel.getObject().setLot(createdLot); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + key = Lot.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(lots, lotService.listLots(getSession().getUtilisateur())); + try { + Lot createdLot = lotService.loadLot(getPageParameters().get(key).toInt()); + extractionModel.getObject().setLot(createdLot); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } - // mise à jour du champ réf d'un nouvel extrait au cas où retour sur le formulaire avec un nouveau lot - // sélectionné - updateRefExtrait(null); + // mise à jour du champ réf d'un nouvel extrait au cas où retour sur le formulaire avec un nouveau lot + // sélectionné + updateRefExtrait(null); } /** @@ -701,15 +701,15 @@ * @param target An AjaxRequestTarget, null if not a ajax request */ private void updateRefExtrait(AjaxRequestTarget target) { - if (extractionModel.getObject().getLot() != null && newExtraitModel.getObject().getTypeExtrait() != null) { - // met à jour la réf de l'extrait suivant celle du lot et le type d'extrait - newExtraitModel.getObject().setRef( - String.format(PATTERN_REF_EXTRAIT, extractionModel.getObject().getLot().getRef(), newExtraitModel - .getObject().getTypeExtrait().getInitiales())); - if (target != null) { - target.add(refInput); - } - } + if (extractionModel.getObject().getLot() != null && newExtraitModel.getObject().getTypeExtrait() != null) { + // met à jour la réf de l'extrait suivant celle du lot et le type d'extrait + newExtraitModel.getObject().setRef( + String.format(PATTERN_REF_EXTRAIT, extractionModel.getObject().getLot().getRef(), newExtraitModel + .getObject().getTypeExtrait().getInitiales())); + if (target != null) { + target.add(refInput); + } + } } /** @@ -718,71 +718,71 @@ * @param selectFirstTypeExtrait If the first element of the TypeExtraits combobox need to be selected */ private void updateTypesExtrait(boolean selectFirstTypeExtrait, AjaxRequestTarget target) { - if (extractionModel.getObject().getMethode() != null) { - CollectionTools.setter(typesExtrait, extractionModel.getObject().getMethode().getSortedTypesEnSortie()); - for (Extrait curExtrait : extractionModel.getObject().getExtraits()) { - typesExtrait.remove(curExtrait.getTypeExtrait()); - } - } - configureExtraitInputs(); + if (extractionModel.getObject().getMethode() != null) { + CollectionTools.setter(typesExtrait, extractionModel.getObject().getMethode().getSortedTypesEnSortie()); + for (Extrait curExtrait : extractionModel.getObject().getExtraits()) { + typesExtrait.remove(curExtrait.getTypeExtrait()); + } + } + configureExtraitInputs(); - if (selectFirstTypeExtrait) { - // Si liste des types extraits non vide, sélection du premier élement - newExtraitModel.getObject().setTypeExtrait( - typeExtraitInput.getChoices().isEmpty() ? null : typeExtraitInput.getChoices().get(0)); - } + if (selectFirstTypeExtrait) { + // Si liste des types extraits non vide, sélection du premier élement + newExtraitModel.getObject().setTypeExtrait( + typeExtraitInput.getChoices().isEmpty() ? null : typeExtraitInput.getChoices().get(0)); + } - updateRefExtrait(target); + updateRefExtrait(target); - if (target != null) { - target.add(typeExtraitInput, typeExtraitTooltip, refInput, masseObtenueInput, addExtraitButton); - } + if (target != null) { + target.add(typeExtraitInput, typeExtraitTooltip, refInput, masseObtenueInput, addExtraitButton); + } } /** * Configure les composants pour la saisie d'extraits */ private void configureExtraitInputs() { - // désactivation de la saisie d'un extrait si pas de méthode ou si déjà un extrait par type d'extrait - if (extractionModel.getObject().getMethode() == null - || extractionModel.getObject().getExtraits() != null - && extractionModel.getObject().getExtraits().size() == extractionModel.getObject().getMethode() - .getTypesEnSortie().size()) { - disableExtraitAdding(); - } else { - enableExtraitAdding(); - } + // désactivation de la saisie d'un extrait si pas de méthode ou si déjà un extrait par type d'extrait + if (extractionModel.getObject().getMethode() == null + || extractionModel.getObject().getExtraits() != null + && extractionModel.getObject().getExtraits().size() == extractionModel.getObject().getMethode() + .getTypesEnSortie().size()) { + disableExtraitAdding(); + } else { + enableExtraitAdding(); + } } /** * Active la saisie pour ajouter un nouvel extrait */ private void enableExtraitAdding() { - typeExtraitInput.setEnabled(true); - typeExtraitTooltip.setVisibilityAllowed(true); - refInput.setEnabled(true); - masseObtenueInput.setEnabled(true); - addExtraitButton.setEnabled(true); + typeExtraitInput.setEnabled(true); + typeExtraitTooltip.setVisibilityAllowed(true); + refInput.setEnabled(true); + masseObtenueInput.setEnabled(true); + addExtraitButton.setEnabled(true); } /** * Désactive la saisie pour ajouter un nouvel extrait */ private void disableExtraitAdding() { - typeExtraitInput.setEnabled(false); - typeExtraitTooltip.setVisibilityAllowed(false); - refInput.setEnabled(false); - masseObtenueInput.setEnabled(false); - addExtraitButton.setEnabled(false); + typeExtraitInput.setEnabled(false); + typeExtraitTooltip.setVisibilityAllowed(false); + refInput.setEnabled(false); + masseObtenueInput.setEnabled(false); + addExtraitButton.setEnabled(false); } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(extractionModel.getObject(), getSession().getLocale())); - if (!extractionService.isExtractionUnique(extractionModel.getObject())) { - error(getString("Extraction.notUnique")); - } + addValidationErrors(validator.validate(extractionModel.getObject(), getSession().getLocale())); + if (!extractionService.isExtractionUnique(extractionModel.getObject())) { + error(getString("Extraction.notUnique")); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ReadExtractionPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ReadExtractionPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/extraction/ReadExtractionPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -92,147 +92,147 @@ * @param callerPage Page appelante */ public ReadExtractionPage(Integer idExtraction, final CallerPage callerPage) { - super(ReadExtractionPage.class); - this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + super(ReadExtractionPage.class); + this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - // Initialisation du modèle - extractionModel = new GenericLoadableDetachableModel<Extraction>(Extraction.class, idExtraction); + // Initialisation du modèle + extractionModel = new GenericLoadableDetachableModel<Extraction>(Extraction.class, idExtraction); - add(new Label("Extraction.ref", new PropertyModel<String>(extractionModel, "ref")) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Extraction.ref", new PropertyModel<String>(extractionModel, "ref")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Extraction.manipulateur", new PropertyModel<Personne>( - extractionModel, "manipulateur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Extraction.manipulateur", new PropertyModel<Personne>( + extractionModel, "manipulateur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - add(new Label("Extraction.date", new PropertyModel<Date>(extractionModel, "date")) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Extraction.date", new PropertyModel<Date>(extractionModel, "date")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Lot>("Extraction.lot", new PropertyModel<Lot>(extractionModel, "lot"), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadLotPage(getModelObject().getIdLot(), currentPage)); - } - }); - add(new Label("Extraction.masseDepart", new DisplayDecimalPropertyModel(extractionModel, "masseDepart", - DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Extraction.complement", new PropertyModel<String>(extractionModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); + add(new PropertyLabelLinkPanel<Lot>("Extraction.lot", new PropertyModel<Lot>(extractionModel, "lot"), + getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadLotPage(getModelObject().getIdLot(), currentPage)); + } + }); + add(new Label("Extraction.masseDepart", new DisplayDecimalPropertyModel(extractionModel, "masseDepart", + DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Extraction.complement", new PropertyModel<String>(extractionModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Extraction.createur", new PropertyModel<Personne>(extractionModel, - "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Extraction.createur", new PropertyModel<Personne>(extractionModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - // Méthode d'extraction - add(new MultiLineLabel("Extraction.methode.description", new PropertyModel<String>(extractionModel, - "methode.description")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Extraction.methode.nom", new PropertyModel<MethodeExtraction>(extractionModel, "methode")) - .add(new ReplaceEmptyLabelBehavior())); + // Méthode d'extraction + add(new MultiLineLabel("Extraction.methode.description", new PropertyModel<String>(extractionModel, + "methode.description")).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Extraction.methode.nom", new PropertyModel<MethodeExtraction>(extractionModel, "methode")) + .add(new ReplaceEmptyLabelBehavior())); - // Déclaration tableau des extraits - extraitsTable = new WebMarkupContainer("Extraction.extraits.Table") { - @Override - public boolean isVisible() { - return extractionModel.getObject().getExtraits().size() > 0; - } - }; - extraitsTable.setOutputMarkupId(true); + // Déclaration tableau des extraits + extraitsTable = new WebMarkupContainer("Extraction.extraits.Table") { + @Override + public boolean isVisible() { + return extractionModel.getObject().getExtraits().size() > 0; + } + }; + extraitsTable.setOutputMarkupId(true); - // Contenu tableaux extrait - // Liste des types extraits ajoutés - extraitsTable.add(new ListView<Extrait>("Extraction.extraits.List", new PropertyModel<List<Extrait>>( - extractionModel, "sortedExtraits")) { - @Override - protected void populateItem(ListItem<Extrait> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux extrait + // Liste des types extraits ajoutés + extraitsTable.add(new ListView<Extrait>("Extraction.extraits.List", new PropertyModel<List<Extrait>>( + extractionModel, "sortedExtraits")) { + @Override + protected void populateItem(ListItem<Extrait> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - IModel<Extrait> extraitModel = item.getModel(); - final Extrait extrait = item.getModelObject(); - // Colonnes - item.add(new Label("Extraction.extraits.List.typeExtrait", new PropertyModel<String>(extrait, - "typeExtrait"))); - // info-bulle comprenant la description du type d'extrait - item.add(new SimpleTooltipPanel("Extraction.extraits.List.typeExtrait.info", new PropertyModel<String>( - extrait, "typeExtrait.description"))); - item.add(new Label("Extraction.extraits.List.ref", new PropertyModel<String>(extrait, "ref"))); - item.add(new Label("Extraction.extraits.List.masseObtenue", new DisplayDecimalPropertyModel( - extraitModel, "masseObtenue", DecimalDisplFormat.SMALL, getLocale()))); + IModel<Extrait> extraitModel = item.getModel(); + final Extrait extrait = item.getModelObject(); + // Colonnes + item.add(new Label("Extraction.extraits.List.typeExtrait", new PropertyModel<String>(extrait, + "typeExtrait"))); + // info-bulle comprenant la description du type d'extrait + item.add(new SimpleTooltipPanel("Extraction.extraits.List.typeExtrait.info", new PropertyModel<String>( + extrait, "typeExtrait.description"))); + item.add(new Label("Extraction.extraits.List.ref", new PropertyModel<String>(extrait, "ref"))); + item.add(new Label("Extraction.extraits.List.masseObtenue", new DisplayDecimalPropertyModel( + extraitModel, "masseObtenue", DecimalDisplFormat.SMALL, getLocale()))); - item.add(new Label("Extraction.extraits.List.rendement", new DisplayPercentPropertyModel(extraitModel, - "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); - } - }); - add(extraitsTable); + item.add(new Label("Extraction.extraits.List.rendement", new DisplayPercentPropertyModel(extraitModel, + "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); + } + }); + add(extraitsTable); - // Selon la non existence d'elements dans la liste on affiche le span - add(new WebMarkupContainer("Extraction.extraits.noTable") { - @Override - public boolean isVisible() { - return !extraitsTable.isVisible(); - } - }); + // Selon la non existence d'elements dans la liste on affiche le span + add(new WebMarkupContainer("Extraction.extraits.noTable") { + @Override + public boolean isVisible() { + return !extraitsTable.isVisible(); + } + }); - // Formulaire des actions - final Form<Void> formView = new Form<Void>("Form"); + // Formulaire des actions + final Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<Extraction> updateLink = new Link<Extraction>(getResource() + ".Extraction.Update", new Model<Extraction>( - extractionModel.getObject())) { - @Override - public void onClick() { - setResponsePage(new ManageExtractionPage(getModelObject().getIdExtraction(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(extractionService.updateOrdeleteExtractionEnabled(extractionModel.getObject(), - getSession().getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Extraction> updateLink = new Link<Extraction>(getResource() + ".Extraction.Update", new Model<Extraction>( + extractionModel.getObject())) { + @Override + public void onClick() { + setResponsePage(new ManageExtractionPage(getModelObject().getIdExtraction(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(extractionService.updateOrdeleteExtractionEnabled(extractionModel.getObject(), + getSession().getUtilisateur())); + formView.add(updateLink); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageExtractionPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - extractionService.deleteExtraction(extractionModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageExtractionPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + extractionService.deleteExtraction(extractionModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ManageExtractionPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(extractionService.updateOrdeleteExtractionEnabled( - extractionModel.getObject(), getSession().getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ManageExtractionPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(extractionService.updateOrdeleteExtractionEnabled( + extractionModel.getObject(), getSession().getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - // Action : retour - formView.add(new Link<Void>(getResource() + ".Extraction.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); - add(formView); + // Action : retour + formView.add(new Link<Void>(getResource() + ".Extraction.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ListLotsPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ListLotsPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ListLotsPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -75,26 +75,27 @@ * Constructeur */ public ListLotsPage() { - super(ListLotsPage.class); - final CallerPage currentPage = new CallerPage(ListLotsPage.class); + super(ListLotsPage.class); + final CallerPage currentPage = new CallerPage(ListLotsPage.class); - add(new Link<Void>(getResource() + ".NewLot") { - @Override - public void onClick() { - setResponsePage(new ManageLotPage(currentPage, true)); - } - }); + add(new Link<Void>(getResource() + ".NewLot") { + @Override + public void onClick() { + setResponsePage(new ManageLotPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer lotsRefresh = new WebMarkupContainer(getResource() + ".Lots.Refresh"); - lotsRefresh.setOutputMarkupId(true); - add(lotsRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer lotsRefresh = new WebMarkupContainer(getResource() + ".Lots.Refresh"); + lotsRefresh.setOutputMarkupId(true); + add(lotsRefresh); - // Liste des lots - final List<Lot> lots = lotService.listLots(getSession().getUtilisateur()); - DataTable<Lot, String> lotsDataTable = initLotsDataTable(this, "ListLotsPage.Lots", currentPage, lots, lotService); - lotsRefresh.add(lotsDataTable); + // Liste des lots + final List<Lot> lots = lotService.listLots(getSession().getUtilisateur()); + DataTable<Lot, String> lotsDataTable = initLotsDataTable(this, "ListLotsPage.Lots", currentPage, lots, + lotService); + lotsRefresh.add(lotsDataTable); } /** @@ -109,103 +110,114 @@ * @param lotService lot service * @return data table component */ - public static DataTable<Lot, String> initLotsDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<Lot> lots, final LotService lotService) { - LoadableDetachableSortableListDataProvider<Lot> lotsDataProvider = new LoadableDetachableSortableListDataProvider<Lot>( - lots, templatePage.getSession().getLocale()); + public static DataTable<Lot, String> initLotsDataTable(final TemplatePage templatePage, final String componentId, + final CallerPage callerPage, List<Lot> lots, final LotService lotService) { + LoadableDetachableSortableListDataProvider<Lot> lotsDataProvider = new LoadableDetachableSortableListDataProvider<Lot>( + lots, templatePage.getSession().getLocale()); - List<IColumn<Lot, String>> columns = new ArrayList<IColumn<Lot, String>>(); + List<IColumn<Lot, String>> columns = new ArrayList<IColumn<Lot, String>>(); - columns.add(new LinkableImagePropertyColumn<Lot, String>("images/read.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ReadLotPage(model.getObject().getIdLot(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Lot, String>("images/read.png", templatePage.getString("Read"), + templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ReadLotPage(model.getObject().getIdLot(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.ref")), "ref", "ref", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ReadLotPage(model.getObject().getIdLot(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.ref")), "ref", + "ref", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ReadLotPage(model.getObject().getIdLot(), callerPage)); + } + }); - columns.add(new PropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.dateRecolte2")), "dateRecolte", - "dateRecolte")); + columns.add(new PropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.dateRecolte2")), + "dateRecolte", "dateRecolte")); - columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.station")), "station", "station", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ReadStationPage(model.getObject().getStation().getIdStation(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.station")), + "station", "station", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ReadStationPage(model.getObject().getStation().getIdStation(), + callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.specimenRef2")), "specimenRef", - "specimenRef", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getSpecimenRef().getIdSpecimen(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.specimenRef2")), + "specimenRef", "specimenRef", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getSpecimenRef().getIdSpecimen(), + callerPage)); + } + }); - columns.add(new EnumPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Specimen.typeOrganisme")), - "specimenRef.typeOrganisme", "specimenRef.typeOrganisme", templatePage)); + columns.add(new EnumPropertyColumn<Lot, String>(new Model<String>(templatePage + .getString("Specimen.typeOrganisme")), "specimenRef.typeOrganisme", "specimenRef.typeOrganisme", + templatePage)); - columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Specimen.embranchement")), - "specimenRef.embranchement", "specimenRef.embranchement")); + columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage + .getString("Specimen.embranchement")), "specimenRef.embranchement", "specimenRef.embranchement")); - columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Specimen.famille")), - "specimenRef.famille", "specimenRef.famille")); + columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage + .getString("Specimen.famille")), "specimenRef.famille", "specimenRef.famille")); - columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Specimen.genre")), - "specimenRef.genre", "specimenRef.genre")); + columns.add(new TaxonomyPropertyColumn<Lot, String>( + new Model<String>(templatePage.getString("Specimen.genre")), "specimenRef.genre", "specimenRef.genre")); - columns.add(new TaxonomyPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Specimen.espece")), - "specimenRef.espece", "specimenRef.espece")); + columns.add(new TaxonomyPropertyColumn<Lot, String>( + new Model<String>(templatePage.getString("Specimen.espece")), "specimenRef.espece", + "specimenRef.espece")); - columns.add(new PropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.partie")), "partie", "partie")); + columns.add(new PropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.partie")), "partie", + "partie")); - columns.add(new DecimalPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.masseFraiche2")), "masseFraiche", - "masseFraiche", DecimalDisplFormat.SMALL, templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<Lot, String>(new Model<String>(templatePage + .getString("Lot.masseFraiche2")), "masseFraiche", "masseFraiche", DecimalDisplFormat.SMALL, + templatePage.getLocale())); - columns.add(new DecimalPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.masseSeche2")), "masseSeche", - "masseSeche", DecimalDisplFormat.SMALL, templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<Lot, String>( + new Model<String>(templatePage.getString("Lot.masseSeche2")), "masseSeche", "masseSeche", + DecimalDisplFormat.SMALL, templatePage.getLocale())); - columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.campagne")), "campagne", "campagne", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getCampagne().getIdCampagne(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Lot, String>(new Model<String>(templatePage.getString("Lot.campagne")), + "campagne", "campagne", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getCampagne().getIdCampagne(), + callerPage)); + } + }); - columns.add(new MapValuePropertyColumn<Lot, String, String>(new Model<String>(templatePage.getString("Campagne.codePays")), - "campagne.codePays", "campagne.codePays", WebContext.COUNTRIES.get(templatePage.getSession().getLocale()))); + columns.add(new MapValuePropertyColumn<Lot, String, String>(new Model<String>(templatePage + .getString("Campagne.codePays")), "campagne.codePays", "campagne.codePays", WebContext.COUNTRIES + .get(templatePage.getSession().getLocale()))); - columns.add(new LinkableImagePropertyColumn<Lot, String>("images/edit.png", templatePage.getString("Update"), templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - if (lotService.updateOrdeleteLotEnabled(model.getObject(), templatePage.getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + columns.add(new LinkableImagePropertyColumn<Lot, String>("images/edit.png", templatePage.getString("Update"), + templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + if (lotService.updateOrdeleteLotEnabled(model.getObject(), templatePage.getSession().getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { - templatePage.setResponsePage(new ManageLotPage(model.getObject().getIdLot(), callerPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<Lot>> item, String componentId, IModel<Lot> model) { + templatePage.setResponsePage(new ManageLotPage(model.getObject().getIdLot(), callerPage)); + } + }); - final DataTable<Lot, String> lotsDataTable = new AjaxFallbackDefaultDataTable<Lot, String>(componentId, columns, - lotsDataProvider, WebContext.ROWS_PER_PAGE); - lotsDataTable.addBottomToolbar(new TableExportToolbar(lotsDataTable, "lots", templatePage.getSession().getLocale())); - return lotsDataTable; + final DataTable<Lot, String> lotsDataTable = new AjaxFallbackDefaultDataTable<Lot, String>(componentId, + columns, lotsDataProvider, WebContext.ROWS_PER_PAGE); + lotsDataTable.addBottomToolbar(new TableExportToolbar(lotsDataTable, "lots", templatePage.getSession() + .getLocale())); + return lotsDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ManageLotPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ManageLotPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ManageLotPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -77,7 +77,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.USER, AuthRole.ADMIN }) +@AuthRoles( { AuthRole.USER, AuthRole.ADMIN }) public final class ManageLotPage extends TemplatePage { /** Action : create */ @@ -129,7 +129,7 @@ * @param multipleEntry Saisie multiple */ public ManageLotPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -138,7 +138,7 @@ * @param callerPage Page appelante */ public ManageLotPage(Integer idLot, CallerPage callerPage) { - this(idLot, null, callerPage, false); + this(idLot, null, callerPage, false); } /** @@ -147,7 +147,7 @@ * @param callerPage Page appelante */ public ManageLotPage(Lot lot, CallerPage callerPage) { - this(null, lot, callerPage, true); + this(null, lot, callerPage, true); } /** @@ -159,237 +159,238 @@ * @param multipleEntry Saisie multiple */ private ManageLotPage(Integer idLot, Lot lot, final CallerPage callerPage, boolean multipleEntry) { - super(ManageLotPage.class); - assert idLot == null || lot == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManageLotPage.class); + assert idLot == null || lot == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - final CallerPage currentPage = new CallerPage(this); + final CallerPage currentPage = new CallerPage(this); - // Initialisation du modèle - try { - lotModel = new Model<Lot>(idLot == null && lot == null ? new Lot() : lot != null ? lot - : lotService.loadLot(idLot)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + lotModel = new Model<Lot>(idLot == null && lot == null ? new Lot() : lot != null ? lot : lotService + .loadLot(idLot)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - boolean createMode = idLot == null; - if (createMode) { - lotModel.getObject().setCreateur(getSession().getUtilisateur()); - } + boolean createMode = idLot == null; + if (createMode) { + lotModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes - campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); - specimens = specimenService.listSpecimens(getSession().getUtilisateur()); + // Initialisation des listes + campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); + specimens = specimenService.listSpecimens(getSession().getUtilisateur()); - List<Partie> parties = lotService.listParties(); + List<Partie> parties = lotService.listParties(); - if (lot != null) { - // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que - // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas - // l'égalité entre les objets) - lotModel.getObject().setCampagne( - CollectionTools.findWithValue(campagnes, "idCampagne", AccessType.GETTER, lotModel.getObject() - .getCampagne().getIdCampagne())); - // normalement pas nul car un bean campagne (le modèle donné en l'occurence) bien formé comporte une - // campagne de renseigné - if (lotModel.getObject().getCampagne() != null) { - List<Station> stations = lotModel.getObject().getCampagne().getStations(); - lotModel.getObject().setStation( - CollectionTools.findWithValue(stations, "idStation", AccessType.GETTER, lotModel.getObject() - .getStation().getIdStation())); - } - if (lotModel.getObject().getPartie() != null) { - lotModel.getObject().setPartie( - CollectionTools.findWithValue(parties, "idPartie", AccessType.GETTER, lotModel.getObject() - .getPartie().getIdPartie())); - } - } else if (idLot != null) { + if (lot != null) { + // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que + // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas + // l'égalité entre les objets) + lotModel.getObject().setCampagne( + CollectionTools.findWithValue(campagnes, "idCampagne", AccessType.GETTER, lotModel.getObject() + .getCampagne().getIdCampagne())); + // normalement pas nul car un bean campagne (le modèle donné en l'occurence) bien formé comporte une + // campagne de renseigné + if (lotModel.getObject().getCampagne() != null) { + List<Station> stations = lotModel.getObject().getCampagne().getStations(); + lotModel.getObject().setStation( + CollectionTools.findWithValue(stations, "idStation", AccessType.GETTER, lotModel.getObject() + .getStation().getIdStation())); + } + if (lotModel.getObject().getPartie() != null) { + lotModel.getObject().setPartie( + CollectionTools.findWithValue(parties, "idPartie", AccessType.GETTER, lotModel.getObject() + .getPartie().getIdPartie())); + } + } else if (idLot != null) { - } + } - final Form<Void> formView = new Form<Void>("Form"); - DropDownChoice<Campagne> campagnesInput = new DropDownChoice<Campagne>("Lot.campagne", - new PropertyModel<Campagne>(lotModel, "campagne"), campagnes); - campagnesInput.setNullValid(false); - formView.add(campagnesInput); + final Form<Void> formView = new Form<Void>("Form"); + DropDownChoice<Campagne> campagnesInput = new DropDownChoice<Campagne>("Lot.campagne", + new PropertyModel<Campagne>(lotModel, "campagne"), campagnes); + campagnesInput.setNullValid(false); + formView.add(campagnesInput); - // Action : création d'une nouvelle campagne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewCampagne") { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageCampagnePage(currentPage, false)); - } + // Action : création d'une nouvelle campagne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewCampagne") { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageCampagnePage(currentPage, false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageCampagnePage(currentPage, false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageCampagnePage(currentPage, false)); + } + }); - final DropDownChoice<Station> stationsInput = new DropDownChoice<Station>("Lot.station", - new PropertyModel<Station>(lotModel, "station"), - lotModel.getObject().getCampagne() == null ? new ArrayList<Station>() : lotModel.getObject() - .getCampagne().getStations()); - stationsInput.setOutputMarkupId(true); - stationsInput.setNullValid(false); - stationsInput.setEnabled(lotModel.getObject().getCampagne() != null); - formView.add(stationsInput); - formView.add(new SimpleTooltipPanel("Lot.station.info", new Model<String>(getString("Lot.station.info")))); + final DropDownChoice<Station> stationsInput = new DropDownChoice<Station>("Lot.station", + new PropertyModel<Station>(lotModel, "station"), + lotModel.getObject().getCampagne() == null ? new ArrayList<Station>() : lotModel.getObject() + .getCampagne().getStations()); + stationsInput.setOutputMarkupId(true); + stationsInput.setNullValid(false); + stationsInput.setEnabled(lotModel.getObject().getCampagne() != null); + formView.add(stationsInput); + formView.add(new SimpleTooltipPanel("Lot.station.info", new Model<String>(getString("Lot.station.info")))); - campagnesInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - List<Station> stations = new ArrayList<Station>(); - if (lotModel.getObject().getCampagne() != null) { - campagneService.refreshCampagne(lotModel.getObject().getCampagne()); - stations = lotModel.getObject().getCampagne().getSortedStations(); - } - stationsInput.setChoices(stations); - stationsInput.setEnabled(lotModel.getObject().getCampagne() != null); - lotModel.getObject().setStation(null); - // refresh the station choices component - target.add(stationsInput); - } - }); + campagnesInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + List<Station> stations = new ArrayList<Station>(); + if (lotModel.getObject().getCampagne() != null) { + campagneService.refreshCampagne(lotModel.getObject().getCampagne()); + stations = lotModel.getObject().getCampagne().getSortedStations(); + } + stationsInput.setChoices(stations); + stationsInput.setEnabled(lotModel.getObject().getCampagne() != null); + lotModel.getObject().setStation(null); + // refresh the station choices component + target.add(stationsInput); + } + }); - formView.add(new DateTextField("Lot.dateRecolte", new PropertyModel<Date>(lotModel, "dateRecolte")) - .add(new DatePicker())); - formView.add(new TextField<String>("Lot.ref", new PropertyModel<String>(lotModel, "ref"))); - formView.add(new DropDownChoice<Specimen>("Lot.specimenRef", new PropertyModel<Specimen>(lotModel, - "specimenRef"), specimens).setNullValid(false)); + formView.add(new DateTextField("Lot.dateRecolte", new PropertyModel<Date>(lotModel, "dateRecolte")) + .add(new DatePicker())); + formView.add(new TextField<String>("Lot.ref", new PropertyModel<String>(lotModel, "ref"))); + formView.add(new DropDownChoice<Specimen>("Lot.specimenRef", new PropertyModel<Specimen>(lotModel, + "specimenRef"), specimens).setNullValid(false)); - // Action : création d'un nouveau spécimen - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewSpecimen") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManageSpecimenPage(currentPage, false)); - } + // Action : création d'un nouveau spécimen + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewSpecimen") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManageSpecimenPage(currentPage, false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageSpecimenPage(currentPage, false)); - } - }); - formView.add(new DropDownChoice<Partie>("Lot.partie", new PropertyModel<Partie>(lotModel, "partie"), parties) - .setNullValid(true)); - formView.add(new TextField<BigDecimal>("Lot.masseFraiche", new PropertyModel<BigDecimal>(lotModel, - "masseFraiche"))); - formView.add(new TextField<BigDecimal>("Lot.masseSeche", new PropertyModel<BigDecimal>(lotModel, "masseSeche"))); - formView.add(new CheckBox("Lot.echantillonColl", new PropertyModel<Boolean>(lotModel, "echantillonColl"))); - formView.add(new CheckBox("Lot.echantillonIdent", new PropertyModel<Boolean>(lotModel, "echantillonIdent"))); - formView.add(new CheckBox("Lot.echantillonPhylo", new PropertyModel<Boolean>(lotModel, "echantillonPhylo"))); - formView.add(new TextArea<String>("Lot.complement", new PropertyModel<String>(lotModel, "complement"))); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageSpecimenPage(currentPage, false)); + } + }); + formView.add(new DropDownChoice<Partie>("Lot.partie", new PropertyModel<Partie>(lotModel, "partie"), parties) + .setNullValid(true)); + formView.add(new TextField<BigDecimal>("Lot.masseFraiche", new PropertyModel<BigDecimal>(lotModel, + "masseFraiche"))); + formView + .add(new TextField<BigDecimal>("Lot.masseSeche", new PropertyModel<BigDecimal>(lotModel, "masseSeche"))); + formView.add(new CheckBox("Lot.echantillonColl", new PropertyModel<Boolean>(lotModel, "echantillonColl"))); + formView.add(new CheckBox("Lot.echantillonIdent", new PropertyModel<Boolean>(lotModel, "echantillonIdent"))); + formView.add(new CheckBox("Lot.echantillonPhylo", new PropertyModel<Boolean>(lotModel, "echantillonPhylo"))); + formView.add(new TextArea<String>("Lot.complement", new PropertyModel<String>(lotModel, "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("Lot.createur", new PropertyModel<String>(lotModel, "createur")) - .setEnabled(false)); + // Créateur en lecture seule + formView.add(new TextField<String>("Lot.createur", new PropertyModel<String>(lotModel, "createur")) + .setEnabled(false)); - // Action : création du lot - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.createLot(lotModel.getObject()); - } + // Action : création du lot + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.createLot(lotModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : mise à jour du lot - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.updateLot(lotModel.getObject()); - } + // Action : mise à jour du lot + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.updateLot(lotModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode - && lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession().getUtilisateur())); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode + && lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession().getUtilisateur())); + formView.add(updateButton); - // Action : suppression du lot - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.deleteLot(lotModel.getObject()); - } + // Action : suppression du lot + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.deleteLot(lotModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode - && lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession().getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode + && lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession().getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) this.getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) this.getPage()); + } + }); - add(formView); + add(formView); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Station, Spécimen ou Campagne) - refreshModel(); - super.onBeforeRender(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Station, Spécimen ou Campagne) + refreshModel(); + super.onBeforeRender(); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection vers l'écran de saisie d'un nouveau lot, en fournissant déjà quelques données - Lot nextLot = new Lot(); - nextLot.setCampagne(lotModel.getObject().getCampagne()); - nextLot.setStation(lotModel.getObject().getStation()); - nextLot.setDateRecolte(lotModel.getObject().getDateRecolte()); - nextLot.setPartie(lotModel.getObject().getPartie()); - setResponsePage(new ManageLotPage(nextLot, callerPage)); - } else if (callerPage != null) { - // On passe l'id du lot associé à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Lot.class.getSimpleName(), lotModel.getObject().getIdLot()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection vers l'écran de saisie d'un nouveau lot, en fournissant déjà quelques données + Lot nextLot = new Lot(); + nextLot.setCampagne(lotModel.getObject().getCampagne()); + nextLot.setStation(lotModel.getObject().getStation()); + nextLot.setDateRecolte(lotModel.getObject().getDateRecolte()); + nextLot.setPartie(lotModel.getObject().getPartie()); + setResponsePage(new ManageLotPage(nextLot, callerPage)); + } else if (callerPage != null) { + // On passe l'id du lot associé à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Lot.class.getSimpleName(), lotModel.getObject().getIdLot()); + callerPage.responsePage(this); + } } /** @@ -397,47 +398,47 @@ */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Campagne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(campagnes, campagneService.listCampagnes(getSession().getUtilisateur())); - try { - Campagne createdCampagne = campagneService.loadCampagne(getPageParameters().get(key).toInt()); - lotModel.getObject().setCampagne(createdCampagne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Campagne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(campagnes, campagneService.listCampagnes(getSession().getUtilisateur())); + try { + Campagne createdCampagne = campagneService.loadCampagne(getPageParameters().get(key).toInt()); + lotModel.getObject().setCampagne(createdCampagne); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } - key = Specimen.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(specimens, specimenService.listSpecimens(getSession().getUtilisateur())); - try { - Specimen createdSpecimen = specimenService.loadSpecimen(getPageParameters().get(key).toInt()); - lotModel.getObject().setSpecimenRef(createdSpecimen); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + key = Specimen.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(specimens, specimenService.listSpecimens(getSession().getUtilisateur())); + try { + Specimen createdSpecimen = specimenService.loadSpecimen(getPageParameters().get(key).toInt()); + lotModel.getObject().setSpecimenRef(createdSpecimen); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } } /** * Validate model */ private void validateModel() { - if (lotModel.getObject().getCreateur() == null) { - lotModel.getObject().setCreateur(getSession().getUtilisateur()); - } - addValidationErrors(validator.validate(lotModel.getObject(), getSession().getLocale())); + if (lotModel.getObject().getCreateur() == null) { + lotModel.getObject().setCreateur(getSession().getUtilisateur()); + } + addValidationErrors(validator.validate(lotModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ReadLotPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ReadLotPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/lot/ReadLotPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -82,110 +82,110 @@ * @param callerPage Page appelante */ public ReadLotPage(Integer idLot, final CallerPage callerPage) { - super(ReadLotPage.class); - this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage(this); + super(ReadLotPage.class); + this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage(this); - // Initialisation du modèle - lotModel = new GenericLoadableDetachableModel<Lot>(Lot.class, idLot); + // Initialisation du modèle + lotModel = new GenericLoadableDetachableModel<Lot>(Lot.class, idLot); - add(new PropertyLabelLinkPanel<Campagne>("Lot.campagne", new PropertyModel<Campagne>(lotModel, "campagne"), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Campagne>("Lot.campagne", new PropertyModel<Campagne>(lotModel, "campagne"), + getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), currentPage)); + } + }); - add(new PropertyLabelLinkPanel<Station>("Lot.station", new PropertyModel<Station>(lotModel, "station"), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Station>("Lot.station", new PropertyModel<Station>(lotModel, "station"), + getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); + } + }); - add(new Label("Lot.dateRecolte", new PropertyModel<String>(lotModel, "dateRecolte")) // formatShortDateValue(lotModel.getDateRecolte())) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.ref", new PropertyModel<String>(lotModel, "ref")).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.dateRecolte", new PropertyModel<String>(lotModel, "dateRecolte")) // formatShortDateValue(lotModel.getDateRecolte())) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.ref", new PropertyModel<String>(lotModel, "ref")).add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Specimen>("Lot.specimenRef", - new PropertyModel<Specimen>(lotModel, "specimenRef"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadSpecimenPage(getModelObject().getIdSpecimen(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Specimen>("Lot.specimenRef", + new PropertyModel<Specimen>(lotModel, "specimenRef"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadSpecimenPage(getModelObject().getIdSpecimen(), currentPage)); + } + }); - add(new Label("Lot.partie", new PropertyModel<String>(lotModel, "partie")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.masseFraiche", new DisplayDecimalPropertyModel(lotModel, "masseFraiche", - DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.masseSeche", new DisplayDecimalPropertyModel(lotModel, "masseSeche", - DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.echantillonColl", new DisplayBooleanPropertyModel(lotModel, "echantillonColl", this)) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.echantillonIdent", new DisplayBooleanPropertyModel(lotModel, "echantillonIdent", this)) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Lot.echantillonPhylo", new DisplayBooleanPropertyModel(lotModel, "echantillonPhylo", this)) - .add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Lot.complement", new PropertyModel<String>(lotModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.partie", new PropertyModel<String>(lotModel, "partie")).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.masseFraiche", new DisplayDecimalPropertyModel(lotModel, "masseFraiche", + DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.masseSeche", new DisplayDecimalPropertyModel(lotModel, "masseSeche", + DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.echantillonColl", new DisplayBooleanPropertyModel(lotModel, "echantillonColl", this)) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.echantillonIdent", new DisplayBooleanPropertyModel(lotModel, "echantillonIdent", this)) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Lot.echantillonPhylo", new DisplayBooleanPropertyModel(lotModel, "echantillonPhylo", this)) + .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Lot.complement", new PropertyModel<String>(lotModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Lot.createur", new PropertyModel<Personne>(lotModel, "createur"), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Lot.createur", new PropertyModel<Personne>(lotModel, "createur"), + getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - // Formulaire des actions - final Form<Void> formView = new Form<Void>("Form"); + // Formulaire des actions + final Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<Lot> updateLink = new Link<Lot>(getResource() + ".Lot.Update", new Model<Lot>(lotModel.getObject())) { - @Override - public void onClick() { - setResponsePage(new ManageLotPage(getModelObject().getIdLot(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Lot> updateLink = new Link<Lot>(getResource() + ".Lot.Update", new Model<Lot>(lotModel.getObject())) { + @Override + public void onClick() { + setResponsePage(new ManageLotPage(getModelObject().getIdLot(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - lotService.deleteLot(lotModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + lotService.deleteLot(lotModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ManageLotPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ManageLotPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(lotService.updateOrdeleteLotEnabled(lotModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - // Action : retour - formView.add(new Link<Void>(getResource() + ".Lot.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); - add(formView); + // Action : retour + formView.add(new Link<Void>(getResource() + ".Lot.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ListMoleculesPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ListMoleculesPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ListMoleculesPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -77,30 +77,30 @@ * Constructor. */ public ListMoleculesPage() { - super(ListMoleculesPage.class); + super(ListMoleculesPage.class); - final CallerPage currentPage = new CallerPage(ListMoleculesPage.class); + final CallerPage currentPage = new CallerPage(ListMoleculesPage.class); - add(new Link<Void>(getResource() + ".NewMolecule") { - @Override - public void onClick() { - setResponsePage(new ManageMoleculePage(currentPage)); - } - }); + add(new Link<Void>(getResource() + ".NewMolecule") { + @Override + public void onClick() { + setResponsePage(new ManageMoleculePage(currentPage)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer moleculesRefresh = new WebMarkupContainer(getResource() + ".Molecules.Refresh"); - moleculesRefresh.setOutputMarkupId(true); - add(moleculesRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer moleculesRefresh = new WebMarkupContainer(getResource() + ".Molecules.Refresh"); + moleculesRefresh.setOutputMarkupId(true); + add(moleculesRefresh); - // Liste des molecules - Utilisateur utilisateur = getSession().getUtilisateur(); - final List<MoleculeProvenanceBean> moleculeProvenances = moleculeService.listMoleculeProvenances(utilisateur); - - DataTable<MoleculeProvenanceBean, String> moleculesDataTable = initMoleculesDataTable(this, - "ListMoleculesPage.Molecules", currentPage, moleculeProvenances); - moleculesRefresh.add(moleculesDataTable); + // Liste des molecules + Utilisateur utilisateur = getSession().getUtilisateur(); + final List<MoleculeProvenanceBean> moleculeProvenances = moleculeService.listMoleculeProvenances(utilisateur); + + DataTable<MoleculeProvenanceBean, String> moleculesDataTable = initMoleculesDataTable(this, + "ListMoleculesPage.Molecules", currentPage, moleculeProvenances); + moleculesRefresh.add(moleculesDataTable); } /** @@ -115,117 +115,110 @@ * @return data table component */ public static DataTable<MoleculeProvenanceBean, String> initMoleculesDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<MoleculeProvenanceBean> moleculeProvenances) { + final String componentId, final CallerPage callerPage, List<MoleculeProvenanceBean> moleculeProvenances) { - SimpleSortableListDataProvider<MoleculeProvenanceBean> moleculesDataProvider = - new SimpleSortableListDataProvider<MoleculeProvenanceBean>( - moleculeProvenances, templatePage.getSession().getLocale()); + SimpleSortableListDataProvider<MoleculeProvenanceBean> moleculesDataProvider = new SimpleSortableListDataProvider<MoleculeProvenanceBean>( + moleculeProvenances, templatePage.getSession().getLocale()); - List<IColumn<MoleculeProvenanceBean, String>> columns = new ArrayList<IColumn<MoleculeProvenanceBean, String>>(); + List<IColumn<MoleculeProvenanceBean, String>> columns = new ArrayList<IColumn<MoleculeProvenanceBean, String>>(); - columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>( - "images/read.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, IModel<MoleculeProvenanceBean> model) { - templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>("images/read.png", templatePage + .getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, + IModel<MoleculeProvenanceBean> model) { + templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.idMolecule")), - "idMolecule", "idMolecule") { - @Override - public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, IModel<MoleculeProvenanceBean> model) { - templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.idMolecule")), "idMolecule", "idMolecule") { + @Override + public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, + IModel<MoleculeProvenanceBean> model) { + templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); + } + }); - columns.add(new AbstractColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.formuleDevMol"))) { - public void populateItem(Item<ICellPopulator<MoleculeProvenanceBean>> cellItem, String componentId, IModel<MoleculeProvenanceBean> rowModel) { - cellItem.add(new Label(componentId, "-") - .add(new MoleculeViewBehavior(new PropertyModel<String>(rowModel, "molecule.formuleDevMol")))); - } - }); + columns.add(new AbstractColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.formuleDevMol"))) { + public void populateItem(Item<ICellPopulator<MoleculeProvenanceBean>> cellItem, String componentId, + IModel<MoleculeProvenanceBean> rowModel) { + cellItem.add(new Label(componentId, "-").add(new MoleculeViewBehavior(new PropertyModel<String>( + rowModel, "molecule.formuleDevMol")))); + } + }); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.nomCommun")), - "molecule.nomCommun", "molecule.nomCommun")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.nomCommun")), "molecule.nomCommun", "molecule.nomCommun")); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.familleChimique")), - "molecule.familleChimique", "molecule.familleChimique")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.familleChimique")), "molecule.familleChimique", "molecule.familleChimique")); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.formuleBrute")), - "molecule.formuleBrute", "molecule.formuleBrute")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.formuleBrute")), "molecule.formuleBrute", "molecule.formuleBrute")); - columns.add(new DecimalPropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.masseMolaire")), - "molecule.masseMolaire", "molecule.masseMolaire", DecimalDisplFormat.SMALL, templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.masseMolaire")), "molecule.masseMolaire", "molecule.masseMolaire", + DecimalDisplFormat.SMALL, templatePage.getLocale())); - columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>( - "images/attachment.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, IModel<MoleculeProvenanceBean> model) { - templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); - } + columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>("images/attachment.png", + templatePage.getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, + IModel<MoleculeProvenanceBean> model) { + templatePage.setResponsePage(new ReadMoleculePage(model.getObject().getIdMolecule(), callerPage)); + } - @Override - protected boolean isVisibleAllowed(IModel<MoleculeProvenanceBean> model) { - return CollectionUtils.isNotEmpty(model.getObject().getMolecule().getDocuments()); - } - }); + @Override + protected boolean isVisibleAllowed(IModel<MoleculeProvenanceBean> model) { + return CollectionUtils.isNotEmpty(model.getObject().getMolecule().getDocuments()); + } + }); - columns.add(new BooleanPropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.nouvMolecul")), - "molecule.nouvMolecul", "molecule.nouvMolecul", templatePage)); + columns.add(new BooleanPropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.nouvMolecul")), "molecule.nouvMolecul", "molecule.nouvMolecul", templatePage)); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.provenance.embranchement")), - "lot.specimenRef.embranchement", "lot.specimenRef.embranchement")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.provenance.embranchement")), "lot.specimenRef.embranchement", + "lot.specimenRef.embranchement")); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.provenance.genre")), - "lot.specimenRef.genre", "lot.specimenRef.genre")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.provenance.genre")), "lot.specimenRef.genre", "lot.specimenRef.genre")); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.provenance.espece")), - "lot.specimenRef.espece", "lot.specimenRef.espece")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.provenance.espece")), "lot.specimenRef.espece", "lot.specimenRef.espece")); - columns.add(new LinkPropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.provenance.lot.ref")), - "lot.ref", "lot.ref") { - @Override - public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, - String componentId, IModel<MoleculeProvenanceBean> model) { - Lot lot = model.getObject().getLot(); - if (lot != null) { - int idLot = lot.getIdLot(); - templatePage.setResponsePage(new ReadLotPage(idLot, callerPage)); - } - } - }); + columns.add(new LinkPropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.provenance.lot.ref")), "lot.ref", "lot.ref") { + @Override + public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, + IModel<MoleculeProvenanceBean> model) { + Lot lot = model.getObject().getLot(); + if (lot != null) { + int idLot = lot.getIdLot(); + templatePage.setResponsePage(new ReadLotPage(idLot, callerPage)); + } + } + }); - columns.add(new PropertyColumn<MoleculeProvenanceBean, String>( - new Model<String>(templatePage.getString("Molecule.provenance.programme")), - "lot.campagne.programme", "lot.campagne.programme")); + columns.add(new PropertyColumn<MoleculeProvenanceBean, String>(new Model<String>(templatePage + .getString("Molecule.provenance.programme")), "lot.campagne.programme", "lot.campagne.programme")); - columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>( - "images/edit.png", templatePage.getString("Update"), templatePage.getString("Update")) { - @Override - public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, - String componentId, IModel<MoleculeProvenanceBean> model) { - int idMolecule = model.getObject().getIdMolecule(); - templatePage.setResponsePage(new ManageMoleculePage(idMolecule, callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<MoleculeProvenanceBean, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + @Override + public void onClick(Item<ICellPopulator<MoleculeProvenanceBean>> item, String componentId, + IModel<MoleculeProvenanceBean> model) { + int idMolecule = model.getObject().getIdMolecule(); + templatePage.setResponsePage(new ManageMoleculePage(idMolecule, callerPage)); + } + }); - final DataTable<MoleculeProvenanceBean, String> moleculesDataTable = - new AjaxFallbackDefaultDataTable<MoleculeProvenanceBean, String>( - componentId, columns, moleculesDataProvider, WebContext.ROWS_PER_PAGE); - moleculesDataTable.addBottomToolbar(new TableExportToolbar(moleculesDataTable, "molecules", templatePage.getSession().getLocale())); - return moleculesDataTable; + final DataTable<MoleculeProvenanceBean, String> moleculesDataTable = new AjaxFallbackDefaultDataTable<MoleculeProvenanceBean, String>( + componentId, columns, moleculesDataProvider, WebContext.ROWS_PER_PAGE); + moleculesDataTable.addBottomToolbar(new TableExportToolbar(moleculesDataTable, "molecules", templatePage + .getSession().getLocale())); + return moleculesDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ManageMoleculePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ManageMoleculePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ManageMoleculePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -114,7 +114,7 @@ * * @author Eric Chatellier */ -@AuthRoles({ AuthRole.USER, AuthRole.ADMIN }) +@AuthRoles( { AuthRole.USER, AuthRole.ADMIN }) public final class ManageMoleculePage extends TemplatePage { /** Action : create */ @@ -169,7 +169,7 @@ * @param callerPage Page appelante */ public ManageMoleculePage(CallerPage callerPage) { - this(null, callerPage); + this(null, callerPage); } /** @@ -179,183 +179,195 @@ * @param callerPage Page appelante */ public ManageMoleculePage(Integer idMolecule, final CallerPage callerPage) { - super(ManageMoleculePage.class); - this.callerPage = callerPage; + super(ManageMoleculePage.class); + this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage(this); + final CallerPage currentPage = new CallerPage(this); - newProvenanceModel = new Model<MoleculeProvenance>(new MoleculeProvenance()); + newProvenanceModel = new Model<MoleculeProvenance>(new MoleculeProvenance()); - // Initialisation du modèle - try { - moleculeModel = new Model<Molecule>(idMolecule == null ? new Molecule() : moleculeService.loadMolecule(idMolecule)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + moleculeModel = new Model<Molecule>(idMolecule == null ? new Molecule() : moleculeService + .loadMolecule(idMolecule)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - boolean createMode = idMolecule == null; - if (createMode) { - moleculeModel.getObject().setCreateur(getSession().getUtilisateur()); - } + boolean createMode = idMolecule == null; + if (createMode) { + moleculeModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes - List<String> organismes = moleculeService.listMoleculeOrganisme(); - campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); + // Initialisation des listes + List<String> organismes = moleculeService.listMoleculeOrganisme(); + campagnes = campagneService.listCampagnes(getSession().getUtilisateur()); - final Form<Void> formView = new Form<Void>("Form"); - initProvenanceFields(formView, currentPage); - initAttachedDocumentsTable(formView, moleculeModel.getObject(), currentPage); + final Form<Void> formView = new Form<Void>("Form"); + initProvenanceFields(formView, currentPage); + initAttachedDocumentsTable(formView, moleculeModel.getObject(), currentPage); - // page can be accessed by anyone for editing provenance - // but molecule fields can be edited only by administrators or - // molecule creator - Utilisateur utilisateur = getSession().getUtilisateur(); - boolean editEnabled = createMode || moleculeService.updateOrdeleteMoleculeEnabled(moleculeModel.getObject(), utilisateur); + // page can be accessed by anyone for editing provenance + // but molecule fields can be edited only by administrators or + // molecule creator + Utilisateur utilisateur = getSession().getUtilisateur(); + boolean editEnabled = createMode + || moleculeService.updateOrdeleteMoleculeEnabled(moleculeModel.getObject(), utilisateur); - formView.add(new TextField<String>("Molecule.nomCommun", new PropertyModel<String>(moleculeModel, "nomCommun")).setEnabled(editEnabled)); - formView.add(new TextField<String>("Molecule.familleChimique", new PropertyModel<String>(moleculeModel, "familleChimique")).setEnabled(editEnabled)); + formView.add(new TextField<String>("Molecule.nomCommun", new PropertyModel<String>(moleculeModel, "nomCommun")) + .setEnabled(editEnabled)); + formView.add(new TextField<String>("Molecule.familleChimique", new PropertyModel<String>(moleculeModel, + "familleChimique")).setEnabled(editEnabled)); - if (editEnabled) { - formView.add(new HiddenField<String>("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, "formuleDevMol")) - .add(new MoleculeEditorBehavior(new PropertyModel<String>(moleculeModel, "formuleDevMol")))); - } else { - formView.add(new HiddenField<String>("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, "formuleDevMol")) - .setEnabled(false) // important otherwise, loose data - .add(new MoleculeViewBehavior(new PropertyModel<String>(moleculeModel, "formuleDevMol"), 500, 300))); - } + if (editEnabled) { + formView.add(new HiddenField<String>("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, + "formuleDevMol")).add(new MoleculeEditorBehavior(new PropertyModel<String>(moleculeModel, + "formuleDevMol")))); + } else { + formView + .add(new HiddenField<String>("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, + "formuleDevMol")).setEnabled(false) // important otherwise, loose data + .add( + new MoleculeViewBehavior(new PropertyModel<String>(moleculeModel, "formuleDevMol"), + 500, 300))); + } - formView.add(new TextField<String>("Molecule.nomIupca", new PropertyModel<String>(moleculeModel, "nomIupca")).setEnabled(editEnabled)); - formView.add(new TextField<String>("Molecule.formuleBrute", new PropertyModel<String>(moleculeModel, "formuleBrute")).setEnabled(editEnabled)); - - TextField<String> masseMolaireField = new TextField<String>("Molecule.masseMolaire", new PropertyModel<String>(moleculeModel, "masseMolaire")); - masseMolaireField.setRequired(true); - masseMolaireField.setEnabled(editEnabled); - formView.add(masseMolaireField); - + formView.add(new TextField<String>("Molecule.nomIupca", new PropertyModel<String>(moleculeModel, "nomIupca")) + .setEnabled(editEnabled)); + formView.add(new TextField<String>("Molecule.formuleBrute", new PropertyModel<String>(moleculeModel, + "formuleBrute")).setEnabled(editEnabled)); - // div qui englobe les champs visible ssi nouvMolecul est coché - final MarkupContainer nouvMoleculRefresh = new WebMarkupContainer("Molecule.nouvMolecul.Refresh"); - nouvMoleculRefresh.setOutputMarkupId(true); - nouvMoleculRefresh.setVisible(moleculeModel.getObject().isNouvMolecul()); - formView.add(nouvMoleculRefresh); + TextField<String> masseMolaireField = new TextField<String>("Molecule.masseMolaire", new PropertyModel<String>( + moleculeModel, "masseMolaire")); + masseMolaireField.setRequired(true); + masseMolaireField.setEnabled(editEnabled); + formView.add(masseMolaireField); - // predéclaration des champs activé par la chec - formView.add(new CheckBox("Molecule.nouvMolecul", new PropertyModel<Boolean>(moleculeModel, "nouvMolecul")) { - @Override - protected void onSelectionChanged(Boolean newSelection) { - nouvMoleculRefresh.setVisible(newSelection); - } - @Override - protected boolean wantOnSelectionChangedNotifications() { - return true; - } - }.setEnabled(editEnabled)); + // div qui englobe les champs visible ssi nouvMolecul est coché + final MarkupContainer nouvMoleculRefresh = new WebMarkupContainer("Molecule.nouvMolecul.Refresh"); + nouvMoleculRefresh.setOutputMarkupId(true); + nouvMoleculRefresh.setVisible(moleculeModel.getObject().isNouvMolecul()); + formView.add(nouvMoleculRefresh); - AutoCompleteTextFieldString identifieeParInput = new AutoCompleteTextFieldString("Molecule.identifieePar", - new PropertyModel<String>(moleculeModel, "identifieePar"), organismes, ComparisonMode.CONTAINS); - identifieeParInput.setEnabled(editEnabled); - nouvMoleculRefresh.add(identifieeParInput); + // predéclaration des champs activé par la chec + formView.add(new CheckBox("Molecule.nouvMolecul", new PropertyModel<Boolean>(moleculeModel, "nouvMolecul")) { + @Override + protected void onSelectionChanged(Boolean newSelection) { + nouvMoleculRefresh.setVisible(newSelection); + } - DropDownChoice<Campagne> campagnesInput = new DropDownChoice<Campagne>("Molecule.campagne", - new PropertyModel<Campagne>(moleculeModel, "campagne"), campagnes); - campagnesInput.setEnabled(editEnabled); - nouvMoleculRefresh.add(campagnesInput); + @Override + protected boolean wantOnSelectionChangedNotifications() { + return true; + } + }.setEnabled(editEnabled)); - // Action : création d'une nouvelle campagne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - nouvMoleculRefresh.add(new AjaxSubmitLink("NewCampagne") { - @Override - protected void onSubmit(AjaxRequestTarget request, Form<?> form) { - setResponsePage(new ManageCampagnePage(currentPage, false)); - } + AutoCompleteTextFieldString identifieeParInput = new AutoCompleteTextFieldString("Molecule.identifieePar", + new PropertyModel<String>(moleculeModel, "identifieePar"), organismes, ComparisonMode.CONTAINS); + identifieeParInput.setEnabled(editEnabled); + nouvMoleculRefresh.add(identifieeParInput); - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageCampagnePage(currentPage, false)); - } - }.setVisibilityAllowed(editEnabled)); + DropDownChoice<Campagne> campagnesInput = new DropDownChoice<Campagne>("Molecule.campagne", + new PropertyModel<Campagne>(moleculeModel, "campagne"), campagnes); + campagnesInput.setEnabled(editEnabled); + nouvMoleculRefresh.add(campagnesInput); - nouvMoleculRefresh.add(new TextArea<String>("Molecule.publiOrigine", new PropertyModel<String>(moleculeModel, "publiOrigine")) - .setEnabled(editEnabled)); + // Action : création d'une nouvelle campagne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + nouvMoleculRefresh.add(new AjaxSubmitLink("NewCampagne") { + @Override + protected void onSubmit(AjaxRequestTarget request, Form<?> form) { + setResponsePage(new ManageCampagnePage(currentPage, false)); + } - formView.add(new TextArea<String>("Molecule.complement", new PropertyModel<String>(moleculeModel, "complement")) - .setEnabled(editEnabled)); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageCampagnePage(currentPage, false)); + } + }.setVisibilityAllowed(editEnabled)); - // Créateur en lecture seule - formView.add(new TextField<String>("Molecule.createur", new PropertyModel<String>(moleculeModel, "createur")) - .setEnabled(false)); + nouvMoleculRefresh.add(new TextArea<String>("Molecule.publiOrigine", new PropertyModel<String>(moleculeModel, + "publiOrigine")).setEnabled(editEnabled)); - // Action : création du lot - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - moleculeService.createMolecule(moleculeModel.getObject()); - } + formView + .add(new TextArea<String>("Molecule.complement", new PropertyModel<String>(moleculeModel, "complement")) + .setEnabled(editEnabled)); - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + // Créateur en lecture seule + formView.add(new TextField<String>("Molecule.createur", new PropertyModel<String>(moleculeModel, "createur")) + .setEnabled(false)); - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + // Action : création du lot + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + moleculeService.createMolecule(moleculeModel.getObject()); + } - // Action : mise à jour du lot - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - moleculeService.updateMolecule(moleculeModel.getObject()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + // Action : mise à jour du lot + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + moleculeService.updateMolecule(moleculeModel.getObject()); + } - // Action : suppression du lot - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - moleculeService.deleteMolecule(moleculeModel.getObject()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) this.getPage()); - } - }); + // Action : suppression du lot + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + moleculeService.deleteMolecule(moleculeModel.getObject()); + } - add(formView); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); + + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) this.getPage()); + } + }); + + add(formView); } /** @@ -364,233 +376,236 @@ * @param formView */ private void initProvenanceFields(final Form<Void> formView, final CallerPage currentPage) { - // Déclaration tableau des provenances - final MarkupContainer provenanceTable = new WebMarkupContainer("Molecule.provenance.Table"); - provenanceTable.setOutputMarkupId(true); + // Déclaration tableau des provenances + final MarkupContainer provenanceTable = new WebMarkupContainer("Molecule.provenance.Table"); + provenanceTable.setOutputMarkupId(true); - final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( - "Molecule.provenance.resultsNotAccessibles"); - resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); - provenanceTable.add(resultNotAccessibleCont); + final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( + "Molecule.provenance.resultsNotAccessibles"); + resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); + provenanceTable.add(resultNotAccessibleCont); - // chargement des données - Utilisateur utilisateur = getSession().getUtilisateur(); - final List<Produit> utilisateurProduits = produitService.listProduits(utilisateur); + // chargement des données + Utilisateur utilisateur = getSession().getUtilisateur(); + final List<Produit> utilisateurProduits = produitService.listProduits(utilisateur); - // Model de liste des provenances - final LoadableDetachableModel<List<MoleculeProvenance>> listProvenanceModel = new LoadableDetachableModel<List<MoleculeProvenance>>() { - @Override - protected List<MoleculeProvenance> load() { - boolean isOneResultNotAccessible = false; + // Model de liste des provenances + final LoadableDetachableModel<List<MoleculeProvenance>> listProvenanceModel = new LoadableDetachableModel<List<MoleculeProvenance>>() { + @Override + protected List<MoleculeProvenance> load() { + boolean isOneResultNotAccessible = false; - List<MoleculeProvenance> listResults = new ArrayList<MoleculeProvenance>(); + List<MoleculeProvenance> listResults = new ArrayList<MoleculeProvenance>(); - for (MoleculeProvenance res : moleculeModel.getObject().getProvenances()) { - // les résultats de type blanc ou témoin sont tjr accessibles - if (moleculeService.isMoleculeProvenanceAccessibleByUser(res, - ((AuthSession) getPage().getSession()).getUtilisateur())) { - listResults.add(res); - } else { - isOneResultNotAccessible = true; - } - } - // si une des provenances est non accessible, on rend visible le message d'avertissement - resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); - return listResults; - } - }; + for (MoleculeProvenance res : moleculeModel.getObject().getProvenances()) { + // les résultats de type blanc ou témoin sont tjr accessibles + if (moleculeService.isMoleculeProvenanceAccessibleByUser(res, + ((AuthSession) getPage().getSession()).getUtilisateur())) { + listResults.add(res); + } else { + isOneResultNotAccessible = true; + } + } + // si une des provenances est non accessible, on rend visible le message d'avertissement + resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); + return listResults; + } + }; - // Contenu tableaux provenance - provenanceTable.add(new ListView<MoleculeProvenance>("Molecule.provenance.List", listProvenanceModel) { - @Override - protected void populateItem(ListItem<MoleculeProvenance> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux provenance + provenanceTable.add(new ListView<MoleculeProvenance>("Molecule.provenance.List", listProvenanceModel) { + @Override + protected void populateItem(ListItem<MoleculeProvenance> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - IModel<MoleculeProvenance> provenanceModel = item.getModel(); - final MoleculeProvenance provenance = provenanceModel.getObject(); + IModel<MoleculeProvenance> provenanceModel = item.getModel(); + final MoleculeProvenance provenance = provenanceModel.getObject(); - // affichage + lien vers la fiche - item.add(new PropertyLabelLinkProduitPanel("Molecule.provenance.List.produit.ref", - new PropertyModel<Produit>(provenanceModel, "produit"), (TemplatePage) getPage()) { - @Override - public void onClickIfExtrait(Extrait extrait) { - setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); - } + // affichage + lien vers la fiche + item.add(new PropertyLabelLinkProduitPanel("Molecule.provenance.List.produit.ref", + new PropertyModel<Produit>(provenanceModel, "produit"), (TemplatePage) getPage()) { + @Override + public void onClickIfExtrait(Extrait extrait) { + setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); + } - @Override - public void onClickIfFraction(Fraction fraction) { - setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), - currentPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), + currentPage)); + } + }); - item.add(new Label("Molecule.provenance.List.presence", new DisplayDecimalPropertyModel( - provenanceModel, "pourcentage", DecimalDisplFormat.SMALL, getLocale()))); - - if (provenance.getProduit() instanceof Fraction) { - item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, - "produit.purification.lotSource.ref"))); - item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, - "produit.purification.lotSource.specimenRef.genre"))); - item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, - "produit.purification.lotSource.specimenRef.espece"))); - item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, - "produit.purification.lotSource.campagne.nom"))); - } else { - item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, - "produit.extraction.lot.ref"))); - item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, - "produit.extraction.lot.specimenRef.genre"))); - item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, - "produit.extraction.lot.specimenRef.espece"))); - item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, - "produit.extraction.lot.campagne.nom"))); - } - - // Action : suppression d'un résultat de test - Button deleteButton = new AjaxFallbackButton("Molecule.provenance.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - moleculeModel.getObject().getProvenances().remove(provenance); + item.add(new Label("Molecule.provenance.List.presence", new DisplayDecimalPropertyModel( + provenanceModel, "pourcentage", DecimalDisplFormat.SMALL, getLocale()))); - if (target != null) { - target.add(provenanceTable); - refreshFeedbackPage(target); - } - } + if (provenance.getProduit() instanceof Fraction) { + item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, + "produit.purification.lotSource.ref"))); + item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, + "produit.purification.lotSource.specimenRef.genre"))); + item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, + "produit.purification.lotSource.specimenRef.espece"))); + item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, + "produit.purification.lotSource.campagne.nom"))); + } else { + item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, + "produit.extraction.lot.ref"))); + item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, + "produit.extraction.lot.specimenRef.genre"))); + item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, + "produit.extraction.lot.specimenRef.espece"))); + item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, + "produit.extraction.lot.campagne.nom"))); + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + // Action : suppression d'un résultat de test + Button deleteButton = new AjaxFallbackButton("Molecule.provenance.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + moleculeModel.getObject().getProvenances().remove(provenance); - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + if (target != null) { + target.add(provenanceTable); + refreshFeedbackPage(target); + } + } - // champs d'input - final DropDownChoice<Produit> produitChoice = new DropDownChoice<Produit>( - "Molecule.provenance.produit.ref", new PropertyModel<Produit>(newProvenanceModel, "produit"), - utilisateurProduits, new ProduitRenderer()) { + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - produitChoice.setNullValid(false); - provenanceTable.add(produitChoice); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - final TextField<BigDecimal> presenceInput = new TextField<BigDecimal>("Molecule.provenance.presence", - new PropertyModel<BigDecimal>(newProvenanceModel, "pourcentage")) { + // champs d'input + final DropDownChoice<Produit> produitChoice = new DropDownChoice<Produit>("Molecule.provenance.produit.ref", + new PropertyModel<Produit>(newProvenanceModel, "produit"), utilisateurProduits, new ProduitRenderer()) { - }; - presenceInput.setOutputMarkupId(true); - presenceInput.setOutputMarkupPlaceholderTag(true); - provenanceTable.add(presenceInput); + }; + produitChoice.setNullValid(false); + provenanceTable.add(produitChoice); - final Label lotRefLabel = new Label("Molecule.provenance.lot.ref", new AbstractPropertyModel<String>(newProvenanceModel) { - @Override - protected String propertyExpression() { - if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { - return "produit.purification.lotSource.ref"; - } else { - return "produit.extraction.lot.ref"; - } - } - }); - lotRefLabel.setOutputMarkupId(true); - provenanceTable.add(lotRefLabel); + final TextField<BigDecimal> presenceInput = new TextField<BigDecimal>("Molecule.provenance.presence", + new PropertyModel<BigDecimal>(newProvenanceModel, "pourcentage")) { - final Label genreLabel = new Label("Molecule.provenance.genre", new AbstractPropertyModel<String>(newProvenanceModel) { - @Override - protected String propertyExpression() { - if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { - return "produit.purification.lotSource.specimenRef.genre"; - } else { - return "produit.extraction.lot.specimenRef.genre"; - } - } - }); - genreLabel.setOutputMarkupId(true); - provenanceTable.add(genreLabel); - - final Label especeLabel = new Label("Molecule.provenance.espece", new AbstractPropertyModel<String>(newProvenanceModel) { - @Override - protected String propertyExpression() { - if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { - return "produit.purification.lotSource.specimenRef.espece"; - } else { - return "produit.extraction.lot.specimenRef.espece"; - } - } - }); - especeLabel.setOutputMarkupId(true); - provenanceTable.add(especeLabel); - - final Label campagneLabel = new Label("Molecule.provenance.campagne", new AbstractPropertyModel<String>(newProvenanceModel) { - @Override - protected String propertyExpression() { - if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { - return "produit.purification.lotSource.campagne.nom"; - } else { - return "produit.extraction.lot.campagne.nom"; - } - } - }); - campagneLabel.setOutputMarkupId(true); - provenanceTable.add(campagneLabel); - - produitChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - target.add(lotRefLabel, genreLabel, especeLabel, campagneLabel); - } - }); + }; + presenceInput.setOutputMarkupId(true); + presenceInput.setOutputMarkupPlaceholderTag(true); + provenanceTable.add(presenceInput); - // Bouton AJAX pour ajouter un résultat de test - addProvenanceButton = new AjaxFallbackButton("Molecule.provenance.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // ajout du type molecule - newProvenanceModel.getObject().setMolecule(moleculeModel.getObject()); + final Label lotRefLabel = new Label("Molecule.provenance.lot.ref", new AbstractPropertyModel<String>( + newProvenanceModel) { + @Override + protected String propertyExpression() { + if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { + return "produit.purification.lotSource.ref"; + } else { + return "produit.extraction.lot.ref"; + } + } + }); + lotRefLabel.setOutputMarkupId(true); + provenanceTable.add(lotRefLabel); - // ajout à la liste - MoleculeProvenance provenanceAdded = newProvenanceModel.getObject().clone(); - moleculeModel.getObject().getProvenances().add(provenanceAdded); + final Label genreLabel = new Label("Molecule.provenance.genre", new AbstractPropertyModel<String>( + newProvenanceModel) { + @Override + protected String propertyExpression() { + if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { + return "produit.purification.lotSource.specimenRef.genre"; + } else { + return "produit.extraction.lot.specimenRef.genre"; + } + } + }); + genreLabel.setOutputMarkupId(true); + provenanceTable.add(genreLabel); - List<String> errors = validator.validate(newProvenanceModel.getObject(), getSession().getLocale()); + final Label especeLabel = new Label("Molecule.provenance.espece", new AbstractPropertyModel<String>( + newProvenanceModel) { + @Override + protected String propertyExpression() { + if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { + return "produit.purification.lotSource.specimenRef.espece"; + } else { + return "produit.extraction.lot.specimenRef.espece"; + } + } + }); + especeLabel.setOutputMarkupId(true); + provenanceTable.add(especeLabel); - if (errors.isEmpty()) { - // réinit des champs de la ligne "ajout" - newProvenanceModel.getObject().setProduit(null); - newProvenanceModel.getObject().setPourcentage(null); - newProvenanceModel.getObject().setMolecule(null); - } else { - moleculeModel.getObject().getProvenances().remove(provenanceAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + final Label campagneLabel = new Label("Molecule.provenance.campagne", new AbstractPropertyModel<String>( + newProvenanceModel) { + @Override + protected String propertyExpression() { + if (newProvenanceModel.getObject().getProduit() instanceof Fraction) { + return "produit.purification.lotSource.campagne.nom"; + } else { + return "produit.extraction.lot.campagne.nom"; + } + } + }); + campagneLabel.setOutputMarkupId(true); + provenanceTable.add(campagneLabel); - if (target != null) { - target.add(provenanceTable); - refreshFeedbackPage(target); - } - } + produitChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + target.add(lotRefLabel, genreLabel, especeLabel, campagneLabel); + } + }); - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + // Bouton AJAX pour ajouter un résultat de test + addProvenanceButton = new AjaxFallbackButton("Molecule.provenance.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // ajout du type molecule + newProvenanceModel.getObject().setMolecule(moleculeModel.getObject()); - }; - provenanceTable.add(addProvenanceButton); - - formView.add(provenanceTable); + // ajout à la liste + MoleculeProvenance provenanceAdded = newProvenanceModel.getObject().clone(); + moleculeModel.getObject().getProvenances().add(provenanceAdded); + + List<String> errors = validator.validate(newProvenanceModel.getObject(), getSession().getLocale()); + + if (errors.isEmpty()) { + // réinit des champs de la ligne "ajout" + newProvenanceModel.getObject().setProduit(null); + newProvenanceModel.getObject().setPourcentage(null); + newProvenanceModel.getObject().setMolecule(null); + } else { + moleculeModel.getObject().getProvenances().remove(provenanceAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + + if (target != null) { + target.add(provenanceTable); + refreshFeedbackPage(target); + } + } + + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } + + }; + provenanceTable.add(addProvenanceButton); + + formView.add(provenanceTable); } /** @@ -600,106 +615,108 @@ * @param documentAttachable entity to get documents * @param currentPage current page */ - private void initAttachedDocumentsTable(final Form<Void> formView, final DocumentAttachable documentAttachable, final CallerPage currentPage) { + private void initAttachedDocumentsTable(final Form<Void> formView, final DocumentAttachable documentAttachable, + final CallerPage currentPage) { - List<Document> documents = documentAttachable.getDocuments(); + List<Document> documents = documentAttachable.getDocuments(); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer attachedDocumentRefresh = new WebMarkupContainer("ListDocumentsPage.AttachedDocuments.Refresh"); - attachedDocumentRefresh.setOutputMarkupId(true); - formView.add(attachedDocumentRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer attachedDocumentRefresh = new WebMarkupContainer( + "ListDocumentsPage.AttachedDocuments.Refresh"); + attachedDocumentRefresh.setOutputMarkupId(true); + formView.add(attachedDocumentRefresh); - SimpleSortableListDataProvider<Document> attachedDocumentsDataProvider = - new SimpleSortableListDataProvider<Document>(documents, getSession().getLocale()); + SimpleSortableListDataProvider<Document> attachedDocumentsDataProvider = new SimpleSortableListDataProvider<Document>( + documents, getSession().getLocale()); - List<IColumn<Document, String>> columns = new ArrayList<IColumn<Document, String>>(); + List<IColumn<Document, String>> columns = new ArrayList<IColumn<Document, String>>(); - columns.add(new LinkPropertyColumn<Document, String>( - new Model<String>(getString("Document.titre")), "titre", "titre") { - @Override - public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { - setResponsePage(new ReadDocumentPage(model.getObject(), documentAttachable, currentPage)); - } - }); + columns.add(new LinkPropertyColumn<Document, String>(new Model<String>(getString("Document.titre")), "titre", + "titre") { + @Override + public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { + setResponsePage(new ReadDocumentPage(model.getObject(), documentAttachable, currentPage)); + } + }); - columns.add(new PropertyColumn<Document, String>( - new Model<String>(getString("Document.typeDocument")), "typeDocument.nom", "typeDocument.nom")); + columns.add(new PropertyColumn<Document, String>(new Model<String>(getString("Document.typeDocument")), + "typeDocument.nom", "typeDocument.nom")); - columns.add(new PropertyColumn<Document, String>( - new Model<String>(getString("Document.createur")), "createur", "createur")); + columns.add(new PropertyColumn<Document, String>(new Model<String>(getString("Document.createur")), "createur", + "createur")); - columns.add(new LinkableImagePropertyColumn<Document, String>(new Model<String>(getString("Document.link")), - "images/download.png", getString("Document.link"), getString("Document.link")) { - @Override - public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { + columns.add(new LinkableImagePropertyColumn<Document, String>(new Model<String>(getString("Document.link")), + "images/download.png", getString("Document.link"), getString("Document.link")) { + @Override + public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { - Document document = model.getObject(); - WebResponse response = (WebResponse) getResponse(); - response.setContentType(document.getFileMimetype()); - response.setAttachmentHeader(document.getFileName()); + Document document = model.getObject(); + WebResponse response = (WebResponse) getResponse(); + response.setContentType(document.getFileMimetype()); + response.setAttachmentHeader(document.getFileName()); - OutputStream out = getResponse().getOutputStream(); - InputStream in = new ByteArrayInputStream(document.getFileContent()); - try { - IOUtils.copy(in, out); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); + OutputStream out = getResponse().getOutputStream(); + InputStream in = new ByteArrayInputStream(document.getFileContent()); + try { + IOUtils.copy(in, out); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); - final DataTable<Document, String> attachedDocumentTable = new AjaxFallbackDefaultDataTable<Document, String>("ListDocumentsPage.AttachedDocuments", columns, - attachedDocumentsDataProvider, WebContext.ROWS_PER_PAGE); + final DataTable<Document, String> attachedDocumentTable = new AjaxFallbackDefaultDataTable<Document, String>( + "ListDocumentsPage.AttachedDocuments", columns, attachedDocumentsDataProvider, WebContext.ROWS_PER_PAGE); - columns.add(new AjaxButtonPropertyColumn<Document, String>(new Model<String>(getString("Actions")), - new Model<String>(getString("Delete")), formView) { - @Override - public void onSubmit(AjaxRequestTarget target, Form<?> form, IModel<Document> model) { - Document document = model.getObject(); - documentAttachable.removeDocument(document); - - if (target != null) { - target.add(attachedDocumentTable); - refreshFeedbackPage(target); - } - } - }); + columns.add(new AjaxButtonPropertyColumn<Document, String>(new Model<String>(getString("Actions")), + new Model<String>(getString("Delete")), formView) { + @Override + public void onSubmit(AjaxRequestTarget target, Form<?> form, IModel<Document> model) { + Document document = model.getObject(); + documentAttachable.removeDocument(document); - attachedDocumentRefresh.add(attachedDocumentTable); - - // Action : création d'un nouveau document - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewDocument") { - @Override - protected void onSubmit(AjaxRequestTarget request, Form<?> form) { - setResponsePage(new ManageDocumentPage(currentPage, moleculeModel.getObject(), false)); - } + if (target != null) { + target.add(attachedDocumentTable); + refreshFeedbackPage(target); + } + } + }); - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageDocumentPage(currentPage, moleculeModel.getObject(), false)); - } - }.setVisibilityAllowed(true)); + attachedDocumentRefresh.add(attachedDocumentTable); + + // Action : création d'un nouveau document + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewDocument") { + @Override + protected void onSubmit(AjaxRequestTarget request, Form<?> form) { + setResponsePage(new ManageDocumentPage(currentPage, moleculeModel.getObject(), false)); + } + + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageDocumentPage(currentPage, moleculeModel.getObject(), false)); + } + }.setVisibilityAllowed(true)); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (callerPage != null) { - callerPage.responsePage(this); - } + if (callerPage != null) { + callerPage.responsePage(this); + } } /** * Validate model */ private void validateModel() { - if (moleculeModel.getObject().getCreateur() == null) { - moleculeModel.getObject().setCreateur(getSession().getUtilisateur()); - } - addValidationErrors(validator.validate(moleculeModel.getObject(), getSession().getLocale())); + if (moleculeModel.getObject().getCreateur() == null) { + moleculeModel.getObject().setCreateur(getSession().getUtilisateur()); + } + addValidationErrors(validator.validate(moleculeModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ReadMoleculePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ReadMoleculePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/molecule/ReadMoleculePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -117,181 +117,194 @@ * @param callerPage caller page */ public ReadMoleculePage(Integer idMolecule, final CallerPage callerPage) { - super(ReadMoleculePage.class); - this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage(this); - - // Initialisation du modèle - moleculeModel = new GenericLoadableDetachableModel<Molecule>(Molecule.class, idMolecule); - - initProvenanceFields(currentPage); - initAttachedDocumentsTable(moleculeModel.getObject(), currentPage); + super(ReadMoleculePage.class); + this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage(this); - add(new Label("Molecule.idMolecule", new PropertyModel<String>(moleculeModel, "idMolecule"))); - add(new Label("Molecule.nomCommun", new PropertyModel<String>(moleculeModel, "nomCommun")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Molecule.familleChimique", new PropertyModel<String>(moleculeModel, "familleChimique")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, "formuleDevMol")).add(new ReplaceEmptyLabelBehavior()) - .add(new MoleculeViewBehavior(new PropertyModel<String>(moleculeModel, "formuleDevMol"), 500, 300))); - add(new Label("Molecule.nomIupca", new PropertyModel<String>(moleculeModel, "nomIupca")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Molecule.formuleBrute", new PropertyModel<String>(moleculeModel, "formuleBrute")).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Molecule.masseMolaire", new DisplayDecimalPropertyModel(moleculeModel, "masseMolaire", DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Molecule.nouvMolecul", new DisplayBooleanPropertyModel(moleculeModel, "nouvMolecul", this)).add(new ReplaceEmptyLabelBehavior())); - - final MarkupContainer nouvMoleculRefresh = new WebMarkupContainer("Molecule.nouvMolecul.Refresh"); - nouvMoleculRefresh.setOutputMarkupId(true); - nouvMoleculRefresh.setVisible(moleculeModel.getObject().isNouvMolecul()); - nouvMoleculRefresh.add(new Label("Molecule.campagne", new PropertyModel<Campagne>(moleculeModel, "campagne")).add(new ReplaceEmptyLabelBehavior())); - nouvMoleculRefresh.add(new Label("Molecule.identifieePar", new PropertyModel<Personne>(moleculeModel, "identifieePar")).add(new ReplaceEmptyLabelBehavior())); - nouvMoleculRefresh.add(new Label("Molecule.publiOrigine", new PropertyModel<String>(moleculeModel, "publiOrigine")).add(new ReplaceEmptyLabelBehavior())); - add(nouvMoleculRefresh); + // Initialisation du modèle + moleculeModel = new GenericLoadableDetachableModel<Molecule>(Molecule.class, idMolecule); - add(new Label("Molecule.complement", new PropertyModel<String>(moleculeModel, "complement")).add(new ReplaceEmptyLabelBehavior())); - - add(new PropertyLabelLinkPanel<Personne>("Molecule.createur", new PropertyModel<Personne>(moleculeModel, "createur"), - getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); - - // Formulaire des actions - final Form<Void> formView = new Form<Void>("Form"); + initProvenanceFields(currentPage); + initAttachedDocumentsTable(moleculeModel.getObject(), currentPage); - // Action : mise à jour (redirection vers le formulaire) - Link<Molecule> updateLink = new Link<Molecule>(getResource() + ".Molecule.Update", new Model<Molecule>(moleculeModel.getObject())) { - @Override - public void onClick() { - setResponsePage(new ManageMoleculePage(getModelObject().getIdMolecule(), currentPage)); - } - }; - formView.add(updateLink); + add(new Label("Molecule.idMolecule", new PropertyModel<String>(moleculeModel, "idMolecule"))); + add(new Label("Molecule.nomCommun", new PropertyModel<String>(moleculeModel, "nomCommun")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Molecule.familleChimique", new PropertyModel<String>(moleculeModel, "familleChimique")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Molecule.formuleDevMol", new PropertyModel<String>(moleculeModel, "formuleDevMol")).add( + new ReplaceEmptyLabelBehavior()).add( + new MoleculeViewBehavior(new PropertyModel<String>(moleculeModel, "formuleDevMol"), 500, 300))); + add(new Label("Molecule.nomIupca", new PropertyModel<String>(moleculeModel, "nomIupca")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Molecule.formuleBrute", new PropertyModel<String>(moleculeModel, "formuleBrute")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Molecule.masseMolaire", new DisplayDecimalPropertyModel(moleculeModel, "masseMolaire", + DecimalDisplFormat.SMALL, getLocale())).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Molecule.nouvMolecul", new DisplayBooleanPropertyModel(moleculeModel, "nouvMolecul", this)) + .add(new ReplaceEmptyLabelBehavior())); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - moleculeService.deleteMolecule(moleculeModel.getObject()); - } + final MarkupContainer nouvMoleculRefresh = new WebMarkupContainer("Molecule.nouvMolecul.Refresh"); + nouvMoleculRefresh.setOutputMarkupId(true); + nouvMoleculRefresh.setVisible(moleculeModel.getObject().isNouvMolecul()); + nouvMoleculRefresh.add(new Label("Molecule.campagne", new PropertyModel<Campagne>(moleculeModel, "campagne")) + .add(new ReplaceEmptyLabelBehavior())); + nouvMoleculRefresh.add(new Label("Molecule.identifieePar", new PropertyModel<Personne>(moleculeModel, + "identifieePar")).add(new ReplaceEmptyLabelBehavior())); + nouvMoleculRefresh.add(new Label("Molecule.publiOrigine", new PropertyModel<String>(moleculeModel, + "publiOrigine")).add(new ReplaceEmptyLabelBehavior())); + add(nouvMoleculRefresh); - @Override - public void onSuccess() { - successNextPage(ManageMoleculePage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(moleculeService.updateOrdeleteMoleculeEnabled(moleculeModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + add(new Label("Molecule.complement", new PropertyModel<String>(moleculeModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); - // Action : retour - formView.add(new Link<Void>(getResource() + ".Molecule.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); - add(formView); + add(new PropertyLabelLinkPanel<Personne>("Molecule.createur", new PropertyModel<Personne>(moleculeModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); + + // Formulaire des actions + final Form<Void> formView = new Form<Void>("Form"); + + // Action : mise à jour (redirection vers le formulaire) + Link<Molecule> updateLink = new Link<Molecule>(getResource() + ".Molecule.Update", new Model<Molecule>( + moleculeModel.getObject())) { + @Override + public void onClick() { + setResponsePage(new ManageMoleculePage(getModelObject().getIdMolecule(), currentPage)); + } + }; + formView.add(updateLink); + + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageLotPage.class, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + moleculeService.deleteMolecule(moleculeModel.getObject()); + } + + @Override + public void onSuccess() { + successNextPage(ManageMoleculePage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(moleculeService.updateOrdeleteMoleculeEnabled(moleculeModel.getObject(), + getSession().getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); + + // Action : retour + formView.add(new Link<Void>(getResource() + ".Molecule.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } - + /** * Init provenance table. * * @param formView */ private void initProvenanceFields(final CallerPage currentPage) { - // Déclaration tableau des provenances - final MarkupContainer provenanceTable = new WebMarkupContainer("Molecule.provenance.Table"); - provenanceTable.setOutputMarkupId(true); + // Déclaration tableau des provenances + final MarkupContainer provenanceTable = new WebMarkupContainer("Molecule.provenance.Table"); + provenanceTable.setOutputMarkupId(true); - final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( - "Molecule.provenance.resultsNotAccessibles"); - resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); - provenanceTable.add(resultNotAccessibleCont); + final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( + "Molecule.provenance.resultsNotAccessibles"); + resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); + provenanceTable.add(resultNotAccessibleCont); - // Model de liste des provenances - final LoadableDetachableModel<List<MoleculeProvenance>> listProvenanceModel = new LoadableDetachableModel<List<MoleculeProvenance>>() { - @Override - protected List<MoleculeProvenance> load() { - boolean isOneResultNotAccessible = false; + // Model de liste des provenances + final LoadableDetachableModel<List<MoleculeProvenance>> listProvenanceModel = new LoadableDetachableModel<List<MoleculeProvenance>>() { + @Override + protected List<MoleculeProvenance> load() { + boolean isOneResultNotAccessible = false; - List<MoleculeProvenance> listResults = new ArrayList<MoleculeProvenance>(); + List<MoleculeProvenance> listResults = new ArrayList<MoleculeProvenance>(); - for (MoleculeProvenance res : moleculeModel.getObject().getProvenances()) { - // les résultats de type blanc ou témoin sont tjr accessibles - if (moleculeService.isMoleculeProvenanceAccessibleByUser(res, - ((AuthSession) getPage().getSession()).getUtilisateur())) { - listResults.add(res); - } else { - isOneResultNotAccessible = true; - } - } - // si une des provenances est non accessible, on rend visible le message d'avertissement - resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); - return listResults; - } - }; + for (MoleculeProvenance res : moleculeModel.getObject().getProvenances()) { + // les résultats de type blanc ou témoin sont tjr accessibles + if (moleculeService.isMoleculeProvenanceAccessibleByUser(res, + ((AuthSession) getPage().getSession()).getUtilisateur())) { + listResults.add(res); + } else { + isOneResultNotAccessible = true; + } + } + // si une des provenances est non accessible, on rend visible le message d'avertissement + resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); + return listResults; + } + }; - // Contenu tableaux provenance - ListView<MoleculeProvenance> provenanceListView = new ListView<MoleculeProvenance>( - "Molecule.provenance.List", listProvenanceModel) { - @Override - protected void populateItem(ListItem<MoleculeProvenance> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux provenance + ListView<MoleculeProvenance> provenanceListView = new ListView<MoleculeProvenance>("Molecule.provenance.List", + listProvenanceModel) { + @Override + protected void populateItem(ListItem<MoleculeProvenance> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - IModel<MoleculeProvenance> provenanceModel = item.getModel(); - // affichage + lien vers la fiche - item.add(new PropertyLabelLinkProduitPanel("Molecule.provenance.List.produit.ref", - new PropertyModel<Produit>(provenanceModel, "produit"), (TemplatePage) getPage()) { - @Override - public void onClickIfExtrait(Extrait extrait) { - setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); - } + IModel<MoleculeProvenance> provenanceModel = item.getModel(); + // affichage + lien vers la fiche + item.add(new PropertyLabelLinkProduitPanel("Molecule.provenance.List.produit.ref", + new PropertyModel<Produit>(provenanceModel, "produit"), (TemplatePage) getPage()) { + @Override + public void onClickIfExtrait(Extrait extrait) { + setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); + } - @Override - public void onClickIfFraction(Fraction fraction) { - setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), - currentPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), + currentPage)); + } + }); - item.add(new Label("Molecule.provenance.List.presence", new DisplayDecimalPropertyModel( - provenanceModel, "pourcentage", DecimalDisplFormat.SMALL, getLocale()))) - .add(new ReplaceEmptyLabelBehavior()); - item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, - "pourcentage")).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, - "pourcentage")).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, - "pourcentage")).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, - "pourcentage")).add(new ReplaceEmptyLabelBehavior())); - } - }; - provenanceTable.add(provenanceListView); - add(provenanceTable); + item.add( + new Label("Molecule.provenance.List.presence", new DisplayDecimalPropertyModel(provenanceModel, + "pourcentage", DecimalDisplFormat.SMALL, getLocale()))).add( + new ReplaceEmptyLabelBehavior()); + item.add(new Label("Molecule.provenance.List.lot.ref", new PropertyModel<String>(provenanceModel, + "pourcentage")).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Molecule.provenance.List.genre", new PropertyModel<String>(provenanceModel, + "pourcentage")).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Molecule.provenance.List.espece", new PropertyModel<String>(provenanceModel, + "pourcentage")).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Molecule.provenance.List.campagne", new PropertyModel<String>(provenanceModel, + "pourcentage")).add(new ReplaceEmptyLabelBehavior())); + } + }; + provenanceTable.add(provenanceListView); + add(provenanceTable); - // Selon la non existence d'elements dans la liste on affiche le span - MarkupContainer noTableProvenances = new WebMarkupContainer("Molecule.provenance.noTable") { - @Override - public boolean isVisible() { - return moleculeModel.getObject().getProvenances().isEmpty(); - } - }; - add(noTableProvenances); + // Selon la non existence d'elements dans la liste on affiche le span + MarkupContainer noTableProvenances = new WebMarkupContainer("Molecule.provenance.noTable") { + @Override + public boolean isVisible() { + return moleculeModel.getObject().getProvenances().isEmpty(); + } + }; + add(noTableProvenances); } - + /** * Init attached document table for current entity. * @@ -301,50 +314,49 @@ */ private void initAttachedDocumentsTable(final DocumentAttachable documentAttachable, final CallerPage currentPage) { - List<Document> documents = documentAttachable.getDocuments(); + List<Document> documents = documentAttachable.getDocuments(); - SimpleSortableListDataProvider<Document> attachedDocumentsDataProvider = - new SimpleSortableListDataProvider<Document>( - documents, getSession().getLocale()); + SimpleSortableListDataProvider<Document> attachedDocumentsDataProvider = new SimpleSortableListDataProvider<Document>( + documents, getSession().getLocale()); - List<IColumn<Document, String>> columns = new ArrayList<IColumn<Document, String>>(); + List<IColumn<Document, String>> columns = new ArrayList<IColumn<Document, String>>(); - columns.add(new LinkPropertyColumn<Document, String>( - new Model<String>(getString("Document.titre")), "titre", "titre") { - @Override - public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { - setResponsePage(new ReadDocumentPage(model.getObject(), documentAttachable, currentPage)); - } - }); + columns.add(new LinkPropertyColumn<Document, String>(new Model<String>(getString("Document.titre")), "titre", + "titre") { + @Override + public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { + setResponsePage(new ReadDocumentPage(model.getObject(), documentAttachable, currentPage)); + } + }); - columns.add(new PropertyColumn<Document, String>( - new Model<String>(getString("Document.typeDocument")), "typeDocument.nom", "typeDocument.nom")); + columns.add(new PropertyColumn<Document, String>(new Model<String>(getString("Document.typeDocument")), + "typeDocument.nom", "typeDocument.nom")); - columns.add(new PropertyColumn<Document, String>( - new Model<String>(getString("Document.createur")), "createur", "createur")); + columns.add(new PropertyColumn<Document, String>(new Model<String>(getString("Document.createur")), "createur", + "createur")); - columns.add(new LinkableImagePropertyColumn<Document, String>(new Model<String>(getString("Document.link")), - "images/download.png", getString("Document.link"), getString("Document.link")) { - @Override - public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { + columns.add(new LinkableImagePropertyColumn<Document, String>(new Model<String>(getString("Document.link")), + "images/download.png", getString("Document.link"), getString("Document.link")) { + @Override + public void onClick(Item<ICellPopulator<Document>> item, String componentId, IModel<Document> model) { - Document document = model.getObject(); - WebResponse response = (WebResponse) getResponse(); - response.setContentType(document.getFileMimetype()); - response.setAttachmentHeader(document.getFileName()); + Document document = model.getObject(); + WebResponse response = (WebResponse) getResponse(); + response.setContentType(document.getFileMimetype()); + response.setAttachmentHeader(document.getFileName()); - OutputStream out = getResponse().getOutputStream(); - InputStream in = new ByteArrayInputStream(document.getFileContent()); - try { - IOUtils.copy(in, out); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); + OutputStream out = getResponse().getOutputStream(); + InputStream in = new ByteArrayInputStream(document.getFileContent()); + try { + IOUtils.copy(in, out); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); - final DataTable<Document, String> attachedDocumentTable = new AjaxFallbackDefaultDataTable<Document, String>("ListDocumentsPage.AttachedDocuments", columns, - attachedDocumentsDataProvider, WebContext.ROWS_PER_PAGE); - add(attachedDocumentTable); + final DataTable<Document, String> attachedDocumentTable = new AjaxFallbackDefaultDataTable<Document, String>( + "ListDocumentsPage.AttachedDocuments", columns, attachedDocumentsDataProvider, WebContext.ROWS_PER_PAGE); + add(attachedDocumentTable); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ListPersonnesPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ListPersonnesPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ListPersonnesPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -74,114 +74,116 @@ * Constructeur */ public ListPersonnesPage() { - super(ListPersonnesPage.class); + super(ListPersonnesPage.class); - final CallerPage currentPage = new CallerPage(ListPersonnesPage.class); + final CallerPage currentPage = new CallerPage(ListPersonnesPage.class); - // Lien pour créer une nouvelle personne - add(new Link<Personne>(getResource() + ".NewPersonne") { - @Override - public void onClick() { - setResponsePage(new ManagePersonnePage(currentPage, true)); - } + // Lien pour créer une nouvelle personne + add(new Link<Personne>(getResource() + ".NewPersonne") { + @Override + public void onClick() { + setResponsePage(new ManagePersonnePage(currentPage, true)); + } - }); + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra rafraichir quand la liste évoluera - final MarkupContainer personnesRefresh = new WebMarkupContainer(getResource() + ".Personnes.Refresh"); - personnesRefresh.setOutputMarkupId(true); - add(personnesRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra rafraichir quand la liste évoluera + final MarkupContainer personnesRefresh = new WebMarkupContainer(getResource() + ".Personnes.Refresh"); + personnesRefresh.setOutputMarkupId(true); + add(personnesRefresh); - // Liste des personnes - final List<Personne> personnes; - if (getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR) { - personnes = personneService.listPersonnesWithInvalidUsers(); - } else { - personnes = personneService.listPersonnes(); - } + // Liste des personnes + final List<Personne> personnes; + if (getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR) { + personnes = personneService.listPersonnesWithInvalidUsers(); + } else { + personnes = personneService.listPersonnes(); + } - final LoadableDetachableSortableListDataProvider<Personne> personnesDataProvider = new LoadableDetachableSortableListDataProvider<Personne>( - personnes, getSession().getLocale()); + final LoadableDetachableSortableListDataProvider<Personne> personnesDataProvider = new LoadableDetachableSortableListDataProvider<Personne>( + personnes, getSession().getLocale()); - List<IColumn<Personne, String>> columns = new ArrayList<IColumn<Personne, String>>(); + List<IColumn<Personne, String>> columns = new ArrayList<IColumn<Personne, String>>(); - columns.add(new LinkableImagePropertyColumn<Personne, String>("images/read.png", getString("Read"), getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { - if (model.getObject() instanceof Utilisateur) { - setResponsePage(new ReadUtilisateurPage(model.getObject().getIdPersonne(), currentPage)); - } else { // sinon c'est une "Personne" - assert (model.getObject() instanceof Personne); - setResponsePage(new ReadPersonnePage(model.getObject().getIdPersonne(), currentPage)); - } - } - }); + columns.add(new LinkableImagePropertyColumn<Personne, String>("images/read.png", getString("Read"), + getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { + if (model.getObject() instanceof Utilisateur) { + setResponsePage(new ReadUtilisateurPage(model.getObject().getIdPersonne(), currentPage)); + } else { // sinon c'est une "Personne" + assert (model.getObject() instanceof Personne); + setResponsePage(new ReadPersonnePage(model.getObject().getIdPersonne(), currentPage)); + } + } + }); - columns.add(new PropertyColumn<Personne, String>(new Model<String>(getString("Personne.nom")), "nom", "nom")); + columns.add(new PropertyColumn<Personne, String>(new Model<String>(getString("Personne.nom")), "nom", "nom")); - columns.add(new PropertyColumn<Personne, String>(new Model<String>(getString("Personne.prenom")), "prenom", "prenom")); + columns.add(new PropertyColumn<Personne, String>(new Model<String>(getString("Personne.prenom")), "prenom", + "prenom")); - columns.add(new LinkPropertyColumn<Personne, String>(new Model<String>(getString("Personne.courriel")), "courriel", - "courriel", getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> rowModel) { - if (rowModel.getObject() instanceof Utilisateur) { - setResponsePage(new ReadUtilisateurPage(rowModel.getObject().getIdPersonne(), currentPage)); - } else { // sinon c'est une "Personne" - assert (rowModel.getObject() instanceof Personne); - setResponsePage(new ReadPersonnePage(rowModel.getObject().getIdPersonne(), currentPage)); - } - } - }); + columns.add(new LinkPropertyColumn<Personne, String>(new Model<String>(getString("Personne.courriel")), + "courriel", "courriel", getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> rowModel) { + if (rowModel.getObject() instanceof Utilisateur) { + setResponsePage(new ReadUtilisateurPage(rowModel.getObject().getIdPersonne(), currentPage)); + } else { // sinon c'est une "Personne" + assert (rowModel.getObject() instanceof Personne); + setResponsePage(new ReadPersonnePage(rowModel.getObject().getIdPersonne(), currentPage)); + } + } + }); - columns.add(new AbstractColumn<Personne, String>(new Model<String>(getString("Utilisateur.typeDroit"))) { - @Override - public void populateItem(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> rowModel) { - String typeDroit; - if (rowModel.getObject() instanceof Utilisateur) { - Utilisateur util = (Utilisateur) rowModel.getObject(); - typeDroit = enumValueMessage(util.getTypeDroit()) - + (util.isValide() ? "" : " " + getString(getResource() + ".IsNotValid")); - } else { - typeDroit = getString(Personne.class.getSimpleName()); - } - item.add(new Label(componentId, typeDroit)); - } - }); + columns.add(new AbstractColumn<Personne, String>(new Model<String>(getString("Utilisateur.typeDroit"))) { + @Override + public void populateItem(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> rowModel) { + String typeDroit; + if (rowModel.getObject() instanceof Utilisateur) { + Utilisateur util = (Utilisateur) rowModel.getObject(); + typeDroit = enumValueMessage(util.getTypeDroit()) + + (util.isValide() ? "" : " " + getString(getResource() + ".IsNotValid")); + } else { + typeDroit = getString(Personne.class.getSimpleName()); + } + item.add(new Label(componentId, typeDroit)); + } + }); - columns.add(new LinkableImagePropertyColumn<Personne, String>("images/edit.png", getString("Update"), - getString("Update")) { + columns.add(new LinkableImagePropertyColumn<Personne, String>("images/edit.png", getString("Update"), + getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { - if (personneService.updateOrDeletePersonneEnabled(model.getObject(), getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { + if (personneService.updateOrDeletePersonneEnabled(model.getObject(), getSession().getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { - if (model.getObject() instanceof Utilisateur) { - // Si l'utilisateur est l'utilisateur "courant", alors on le redirige vers la page de mise à - // jour de son profil sinon vers la page de gestion d'un utilisateur - setResponsePage(model.getObject().getIdPersonne().equals( - getSession().getUtilisateur().getIdPersonne()) ? new UpdateUtilisateurPage(currentPage) - : new ManageUtilisateurPage(model.getObject().getIdPersonne(), currentPage)); - } else { // sinon c'est une "Personne" - assert (model.getObject() instanceof Personne); - setResponsePage(new ManagePersonnePage(model.getObject().getIdPersonne(), currentPage)); - } - } - }); + @Override + public void onClick(Item<ICellPopulator<Personne>> item, String componentId, IModel<Personne> model) { + if (model.getObject() instanceof Utilisateur) { + // Si l'utilisateur est l'utilisateur "courant", alors on le redirige vers la page de mise à + // jour de son profil sinon vers la page de gestion d'un utilisateur + setResponsePage(model.getObject().getIdPersonne().equals( + getSession().getUtilisateur().getIdPersonne()) ? new UpdateUtilisateurPage(currentPage) + : new ManageUtilisateurPage(model.getObject().getIdPersonne(), currentPage)); + } else { // sinon c'est une "Personne" + assert (model.getObject() instanceof Personne); + setResponsePage(new ManagePersonnePage(model.getObject().getIdPersonne(), currentPage)); + } + } + }); - final DataTable<Personne, String> personnesDataTable = new AjaxFallbackDefaultDataTable<Personne, String>( - "ListPersonnesPage.Personnes", columns, personnesDataProvider, WebContext.ROWS_PER_PAGE); + final DataTable<Personne, String> personnesDataTable = new AjaxFallbackDefaultDataTable<Personne, String>( + "ListPersonnesPage.Personnes", columns, personnesDataProvider, WebContext.ROWS_PER_PAGE); - personnesRefresh.add(personnesDataTable); + personnesRefresh.add(personnesDataTable); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ManagePersonnePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ManagePersonnePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ManagePersonnePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,7 +52,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManagePersonnePage extends TemplatePage { /** Action : create */ @@ -89,7 +89,7 @@ * @param multipleEntry Saisie multiple */ public ManagePersonnePage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -98,7 +98,7 @@ * @param callerPage Page appelante */ public ManagePersonnePage(Integer idPersonne, CallerPage callerPage) { - this(idPersonne, null, callerPage, false); + this(idPersonne, null, callerPage, false); } /** @@ -107,7 +107,7 @@ * @param callerPage Page appelante */ public ManagePersonnePage(Personne personne, CallerPage callerPage) { - this(null, personne, callerPage, true); + this(null, personne, callerPage, true); } /** @@ -120,141 +120,141 @@ * @param multipleEntry Saisie multiple */ private ManagePersonnePage(Integer idPersonne, Personne personne, final CallerPage callerPage, boolean multipleEntry) { - super(ManagePersonnePage.class); - assert idPersonne == null || personne == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManagePersonnePage.class); + assert idPersonne == null || personne == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - // Initialisation du modèle - try { - personneModel = new Model<Personne>(idPersonne == null && personne == null ? new Personne() - : personne != null ? personne : personneService.loadPersonne(idPersonne)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + personneModel = new Model<Personne>(idPersonne == null && personne == null ? new Personne() + : personne != null ? personne : personneService.loadPersonne(idPersonne)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - boolean createMode = idPersonne == null; - final Form<Personne> formView = new Form<Personne>("Form", personneModel); + boolean createMode = idPersonne == null; + final Form<Personne> formView = new Form<Personne>("Form", personneModel); - final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", personneModel); - formView.add(personnePanel); + final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", personneModel); + formView.add(personnePanel); - // Action : création de la personne - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.createPersonne(personneModel.getObject()); - } + // Action : création de la personne + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.createPersonne(personneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - personnePanel.validate(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + personnePanel.validate(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : mise à jour de la personne - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.updatePersonne(personneModel.getObject()); - } + // Action : mise à jour de la personne + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.updatePersonne(personneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + redirect(); + } - @Override - public void onValidate() { - personnePanel.validate(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + personnePanel.validate(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : transformation de la personne en utilisateur - Button createUtilisateurButton = new SubmittableButton(ACTION_CREATE_UTILISATEUR, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws EmailException, DataConstraintException { - personneService.updateAndCreateUtilisateur(personneModel.getObject()); - } + // Action : transformation de la personne en utilisateur + Button createUtilisateurButton = new SubmittableButton(ACTION_CREATE_UTILISATEUR, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws EmailException, DataConstraintException { + personneService.updateAndCreateUtilisateur(personneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE_UTILISATEUR); - // redirect all the time to ReadUtilisateur - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE_UTILISATEUR); + // redirect all the time to ReadUtilisateur + } - @Override - public void onValidate() { - personnePanel.validate(); - } - }); - createUtilisateurButton.setVisibilityAllowed(!createMode - && getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR); - formView.add(createUtilisateurButton); + @Override + public void onValidate() { + personnePanel.validate(); + } + }); + createUtilisateurButton.setVisibilityAllowed(!createMode + && getSession().getUtilisateur().getTypeDroit() == TypeDroit.ADMINISTRATEUR); + formView.add(createUtilisateurButton); - // Action : suppression de la personne - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.deletePersonne(personneModel.getObject()); - } + // Action : suppression de la personne + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.deletePersonne(personneModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - if (callerPage != null) { - callerPage.responsePage((TemplatePage) this.getPage()); - } - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + if (callerPage != null) { + callerPage.responsePage((TemplatePage) this.getPage()); + } + } + }); - add(formView); + add(formView); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection vers l'écran de saisie d'un nouveau lot, en fournissant déjà quelques données - Personne nextPersonne = new Personne(); - nextPersonne.setOrganisme(personneModel.getObject().getOrganisme()); - nextPersonne.setAdressePostale(personneModel.getObject().getAdressePostale()); - nextPersonne.setCodePostal(personneModel.getObject().getCodePostal()); - nextPersonne.setVille(personneModel.getObject().getVille()); - nextPersonne.setCodePays(personneModel.getObject().getCodePays()); - setResponsePage(new ManagePersonnePage(nextPersonne, callerPage)); - } else if (callerPage != null) { - // On passe l'id de la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre - // de - // l'exploiter si besoin - callerPage.addPageParameter(Personne.class.getSimpleName(), personneModel.getObject().getIdPersonne()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection vers l'écran de saisie d'un nouveau lot, en fournissant déjà quelques données + Personne nextPersonne = new Personne(); + nextPersonne.setOrganisme(personneModel.getObject().getOrganisme()); + nextPersonne.setAdressePostale(personneModel.getObject().getAdressePostale()); + nextPersonne.setCodePostal(personneModel.getObject().getCodePostal()); + nextPersonne.setVille(personneModel.getObject().getVille()); + nextPersonne.setCodePays(personneModel.getObject().getCodePays()); + setResponsePage(new ManagePersonnePage(nextPersonne, callerPage)); + } else if (callerPage != null) { + // On passe l'id de la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre + // de + // l'exploiter si besoin + callerPage.addPageParameter(Personne.class.getSimpleName(), personneModel.getObject().getIdPersonne()); + callerPage.responsePage(this); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ReadPersonnePage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ReadPersonnePage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/ReadPersonnePage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,71 +67,71 @@ * @param callerPage Page appelante */ public ReadPersonnePage(Integer idPersonne, CallerPage callerPage) { - super(ReadPersonnePage.class); + super(ReadPersonnePage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation du modèle - personneModel = new GenericLoadableDetachableModel<Personne>(Personne.class, idPersonne); + // Initialisation du modèle + personneModel = new GenericLoadableDetachableModel<Personne>(Personne.class, idPersonne); - final Personne personne = personneModel.getObject(); + final Personne personne = personneModel.getObject(); - // Ajout du formulaire pour les actions - final Form<Personne> formView = new Form<Personne>("Form", personneModel); + // Ajout du formulaire pour les actions + final Form<Personne> formView = new Form<Personne>("Form", personneModel); - // Ajout du panel ReadPersonnePanel - final ReadPersonnePanel personnePanel = new ReadPersonnePanel("ReadPersonnePanel", personneModel); - add(personnePanel); + // Ajout du panel ReadPersonnePanel + final ReadPersonnePanel personnePanel = new ReadPersonnePanel("ReadPersonnePanel", personneModel); + add(personnePanel); - // Action : mise à jour (redirection vers le formulaire) - Link<Personne> updateLink = new Link<Personne>(getResource() + ".Personne.Update", - new Model<Personne>(personne)) { - @Override - public void onClick() { - setResponsePage(new ManagePersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(personne, getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Personne> updateLink = new Link<Personne>(getResource() + ".Personne.Update", + new Model<Personne>(personne)) { + @Override + public void onClick() { + setResponsePage(new ManagePersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(personne, getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : retour à la page précédente - formView.add(new Link<Void>(getResource() + ".Personne.Back") { - @Override - public void onClick() { - redirect(); - } - }); + // Action : retour à la page précédente + formView.add(new Link<Void>(getResource() + ".Personne.Back") { + @Override + public void onClick() { + redirect(); + } + }); - // Action : suppression de la personne - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePersonnePage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.deletePersonne(personne); - } + // Action : suppression de la personne + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePersonnePage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.deletePersonne(personne); + } - @Override - public void onSuccess() { - successNextPage(ManagePersonnePage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(personne, getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManagePersonnePage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(personne, getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - // On passe la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Personne.class.getSimpleName(), personneModel.getObject()); - callerPage.responsePage(this); + // On passe la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Personne.class.getSimpleName(), personneModel.getObject()); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ManagePersonnePanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ManagePersonnePanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ManagePersonnePanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,7 +49,8 @@ public final class ManagePersonnePanel extends Panel { /** Model validateur */ - @SpringBean(name = "webModelValidator") private ModelValidator validator; + @SpringBean(name = "webModelValidator") + private ModelValidator validator; /** Services : personne */ @SpringBean @@ -61,29 +62,29 @@ * @param personneModel Modèle */ public ManagePersonnePanel(String id, IModel<? extends Personne> personneModel) { - super(id, personneModel); + super(id, personneModel); - // liste des organismes suggérés à la saisie - final List<String> organismes = personneService.listPersonneOrganismes(); + // liste des organismes suggérés à la saisie + final List<String> organismes = personneService.listPersonneOrganismes(); - add(new TextField<String>("Personne.prenom", new PropertyModel<String>(personneModel, "prenom"))); - add(new TextField<String>("Personne.nom", new PropertyModel<String>(personneModel, "nom"))); - add(new AutoCompleteTextFieldString("Personne.organisme", - new PropertyModel<String>(personneModel, "organisme"), organismes, ComparisonMode.CONTAINS)); - add(new TextField<String>("Personne.fonction", new PropertyModel<String>(personneModel, "fonction"))); - add(new TextField<String>("Personne.tel", new PropertyModel<String>(personneModel, "tel"))); - add(new TextField<String>("Personne.fax", new PropertyModel<String>(personneModel, "fax"))); - add(new TextField<String>("Personne.courriel", new PropertyModel<String>(personneModel, "courriel"))); - add(new TextArea<String>("Personne.adressePostale", new PropertyModel<String>(personneModel, "adressePostale"))); - add(new TextField<String>("Personne.codePostal", new PropertyModel<String>(personneModel, "codePostal"))); - add(new TextField<String>("Personne.ville", new PropertyModel<String>(personneModel, "ville"))); - add(new DropDownChoice<String>("Personne.codePays", new PropertyModel<String>(personneModel, "codePays"), - WebContext.COUNTRY_CODES.get(getSession().getLocale()), new MapChoiceRenderer<String, String>( - WebContext.COUNTRIES.get(getSession().getLocale())))); - if (personneModel.getObject().getCodePays() == null) { - personneModel.getObject().setCodePays( - WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); - } + add(new TextField<String>("Personne.prenom", new PropertyModel<String>(personneModel, "prenom"))); + add(new TextField<String>("Personne.nom", new PropertyModel<String>(personneModel, "nom"))); + add(new AutoCompleteTextFieldString("Personne.organisme", + new PropertyModel<String>(personneModel, "organisme"), organismes, ComparisonMode.CONTAINS)); + add(new TextField<String>("Personne.fonction", new PropertyModel<String>(personneModel, "fonction"))); + add(new TextField<String>("Personne.tel", new PropertyModel<String>(personneModel, "tel"))); + add(new TextField<String>("Personne.fax", new PropertyModel<String>(personneModel, "fax"))); + add(new TextField<String>("Personne.courriel", new PropertyModel<String>(personneModel, "courriel"))); + add(new TextArea<String>("Personne.adressePostale", new PropertyModel<String>(personneModel, "adressePostale"))); + add(new TextField<String>("Personne.codePostal", new PropertyModel<String>(personneModel, "codePostal"))); + add(new TextField<String>("Personne.ville", new PropertyModel<String>(personneModel, "ville"))); + add(new DropDownChoice<String>("Personne.codePays", new PropertyModel<String>(personneModel, "codePays"), + WebContext.COUNTRY_CODES.get(getSession().getLocale()), new MapChoiceRenderer<String, String>( + WebContext.COUNTRIES.get(getSession().getLocale())))); + if (personneModel.getObject().getCodePays() == null) { + personneModel.getObject().setCodePays( + WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); + } } @@ -91,8 +92,8 @@ * Validation */ public void validate() { - ((TemplatePage) getPage()).addValidationErrors(validator.validate((Personne) getDefaultModelObject(), - getSession().getLocale(), "prenom", "nom", "organisme", "fonction", "tel", "fax", "courriel", - "adressePostale", "codePostal", "ville", "codePays")); + ((TemplatePage) getPage()).addValidationErrors(validator.validate((Personne) getDefaultModelObject(), + getSession().getLocale(), "prenom", "nom", "organisme", "fonction", "tel", "fax", "courriel", + "adressePostale", "codePostal", "ville", "codePays")); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ReadPersonnePanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ReadPersonnePanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/personne/panels/ReadPersonnePanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,28 +45,28 @@ * @param personneModel Modèle */ public ReadPersonnePanel(String id, IModel<? extends Personne> personneModel) { - super(id, personneModel); - add(new Label("Personne.prenom", new PropertyModel<String>(personneModel, "prenom")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.nom", new PropertyModel<String>(personneModel, "nom")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.organisme", new PropertyModel<String>(personneModel, "organisme")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.fonction", new PropertyModel<String>(personneModel, "fonction")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.tel", new PropertyModel<String>(personneModel, "tel")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.fax", new PropertyModel<String>(personneModel, "fax")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.courriel", new PropertyModel<String>(personneModel, "courriel")) - .add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Personne.adressePostale", new PropertyModel<String>(personneModel, "adressePostale")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.codePostal", new PropertyModel<String>(personneModel, "codePostal")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.ville", new PropertyModel<String>(personneModel, "ville")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Personne.codePays", new DisplayMapValuePropertyModel<String>(personneModel, "codePays", - WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); + super(id, personneModel); + add(new Label("Personne.prenom", new PropertyModel<String>(personneModel, "prenom")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.nom", new PropertyModel<String>(personneModel, "nom")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.organisme", new PropertyModel<String>(personneModel, "organisme")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.fonction", new PropertyModel<String>(personneModel, "fonction")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.tel", new PropertyModel<String>(personneModel, "tel")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.fax", new PropertyModel<String>(personneModel, "fax")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.courriel", new PropertyModel<String>(personneModel, "courriel")) + .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Personne.adressePostale", new PropertyModel<String>(personneModel, "adressePostale")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.codePostal", new PropertyModel<String>(personneModel, "codePostal")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.ville", new PropertyModel<String>(personneModel, "ville")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Personne.codePays", new DisplayMapValuePropertyModel<String>(personneModel, "codePays", + WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ListPurificationsPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ListPurificationsPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ListPurificationsPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,7 +62,7 @@ * Page de consultation des purification * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ListPurificationsPage extends TemplatePage { /** Service : manipPurification */ @@ -73,30 +73,30 @@ * Constructeur */ public ListPurificationsPage() { - super(ListPurificationsPage.class); + super(ListPurificationsPage.class); - final CallerPage currentPage = new CallerPage(ListPurificationsPage.class); + final CallerPage currentPage = new CallerPage(ListPurificationsPage.class); - add(new Link<Void>(getResource() + ".NewPurification") { - @Override - public void onClick() { - setResponsePage(new ManagePurificationPage(currentPage, true)); - } - }); + add(new Link<Void>(getResource() + ".NewPurification") { + @Override + public void onClick() { + setResponsePage(new ManagePurificationPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer purificationsRefresh = new WebMarkupContainer(getResource() + ".Purifications.Refresh"); - purificationsRefresh.setOutputMarkupId(true); - add(purificationsRefresh); - - // Liste des Purifications - final List<Purification> purifications = purificationService.listPurifications(getSession().getUtilisateur()); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer purificationsRefresh = new WebMarkupContainer(getResource() + ".Purifications.Refresh"); + purificationsRefresh.setOutputMarkupId(true); + add(purificationsRefresh); - DataTable<Purification, String> purificationsDataTable = initPurificationsDataTable(this, - "ListPurificationsPage.Purifications", currentPage, purifications, purificationService); - purificationsRefresh.add(purificationsDataTable); + // Liste des Purifications + final List<Purification> purifications = purificationService.listPurifications(getSession().getUtilisateur()); + DataTable<Purification, String> purificationsDataTable = initPurificationsDataTable(this, + "ListPurificationsPage.Purifications", currentPage, purifications, purificationService); + purificationsRefresh.add(purificationsDataTable); + } /** @@ -112,92 +112,97 @@ * @return data table component */ public static DataTable<Purification, String> initPurificationsDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<Purification> purifications, final PurificationService purificationService) { - - - LoadableDetachableSortableListDataProvider<Purification> purificationsDataProvider = new LoadableDetachableSortableListDataProvider<Purification>( - purifications, templatePage.getSession().getLocale()); + final String componentId, final CallerPage callerPage, List<Purification> purifications, + final PurificationService purificationService) { - List<IColumn<Purification, String>> columns = new ArrayList<IColumn<Purification, String>>(); + LoadableDetachableSortableListDataProvider<Purification> purificationsDataProvider = new LoadableDetachableSortableListDataProvider<Purification>( + purifications, templatePage.getSession().getLocale()); - columns.add(new LinkableImagePropertyColumn<Purification, String>("images/read.png", templatePage.getString("Read"), - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { - templatePage.setResponsePage(new ReadPurificationPage(model.getObject().getIdPurification(), callerPage)); - } - }); + List<IColumn<Purification, String>> columns = new ArrayList<IColumn<Purification, String>>(); - columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Extraction.lot")), "lotSource", - "lotSource", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { - templatePage.setResponsePage(new ReadLotPage(model.getObject().getLotSource().getIdLot(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Purification, String>("images/read.png", templatePage + .getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { + templatePage + .setResponsePage(new ReadPurificationPage(model.getObject().getIdPurification(), callerPage)); + } + }); - columns.add(new LinkProduitPropertyColumn<Purification, String>( - new Model<String>(templatePage.getString("ResultatTestBio.produit")), "produit", "produit", templatePage) { - @Override - public void onClickIfExtrait(Extrait extrait) { - templatePage.setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), callerPage)); - } + columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage + .getString("Extraction.lot")), "lotSource", "lotSource", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { + templatePage.setResponsePage(new ReadLotPage(model.getObject().getLotSource().getIdLot(), callerPage)); + } + }); - @Override - public void onClickIfFraction(Fraction fraction) { - templatePage.setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), callerPage)); - } - }); + columns.add(new LinkProduitPropertyColumn<Purification, String>(new Model<String>(templatePage + .getString("ResultatTestBio.produit")), "produit", "produit", templatePage) { + @Override + public void onClickIfExtrait(Extrait extrait) { + templatePage.setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), + callerPage)); + } - columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Purification.ref")), "ref", - "ref", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { - templatePage.setResponsePage(new ReadPurificationPage(model.getObject().getIdPurification(), callerPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + templatePage.setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), + callerPage)); + } + }); - columns.add(new ShortDatePropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Purification.date")), - "date", "date", templatePage.getLocale())); + columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage + .getString("Purification.ref")), "ref", "ref", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { + templatePage + .setResponsePage(new ReadPurificationPage(model.getObject().getIdPurification(), callerPage)); + } + }); - columns.add(new PropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Purification.methode2")), "methode", - "methode")); + columns.add(new ShortDatePropertyColumn<Purification, String>(new Model<String>(templatePage + .getString("Purification.date")), "date", "date", templatePage.getLocale())); - columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Campagne")), - "lotSource.campagne", "lotSource.campagne", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { - templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getLotSource().getCampagne().getIdCampagne(), - callerPage)); - } - }); + columns.add(new PropertyColumn<Purification, String>(new Model<String>(templatePage + .getString("Purification.methode2")), "methode", "methode")); - columns.add(new LinkableImagePropertyColumn<Purification, String>("images/edit.png", templatePage.getString("Update"), - templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Purification>> item, String componentId, - IModel<Purification> model) { - if (purificationService.updateOrdeletePurificationEnabled(model.getObject(), templatePage.getSession() - .getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + columns.add(new LinkPropertyColumn<Purification, String>(new Model<String>(templatePage.getString("Campagne")), + "lotSource.campagne", "lotSource.campagne", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { + templatePage.setResponsePage(new ReadCampagnePage(model.getObject().getLotSource().getCampagne() + .getIdCampagne(), callerPage)); + } + }); - @Override - public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { - templatePage.setResponsePage(new ManagePurificationPage(model.getObject().getIdPurification(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Purification, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Purification>> item, String componentId, + IModel<Purification> model) { + if (purificationService.updateOrdeletePurificationEnabled(model.getObject(), templatePage.getSession() + .getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - final DataTable<Purification, String> purificationsDataTable = new AjaxFallbackDefaultDataTable<Purification, String>( - componentId, columns, purificationsDataProvider, WebContext.ROWS_PER_PAGE); - purificationsDataTable.addBottomToolbar(new TableExportToolbar(purificationsDataTable, "purifications", templatePage.getSession().getLocale())); - return purificationsDataTable; + @Override + public void onClick(Item<ICellPopulator<Purification>> item, String componentId, IModel<Purification> model) { + templatePage.setResponsePage(new ManagePurificationPage(model.getObject().getIdPurification(), + callerPage)); + } + }); + final DataTable<Purification, String> purificationsDataTable = new AjaxFallbackDefaultDataTable<Purification, String>( + componentId, columns, purificationsDataProvider, WebContext.ROWS_PER_PAGE); + purificationsDataTable.addBottomToolbar(new TableExportToolbar(purificationsDataTable, "purifications", + templatePage.getSession().getLocale())); + return purificationsDataTable; + } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ManagePurificationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ManagePurificationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ManagePurificationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -92,7 +92,7 @@ * Page for adding/update/delete a new "Purification" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManagePurificationPage extends TemplatePage { /** Logger */ @@ -168,7 +168,7 @@ * @param multipleEntry Saisie multiple */ public ManagePurificationPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -177,7 +177,7 @@ * @param callerPage Page appelante */ public ManagePurificationPage(Integer idManip, CallerPage callerPage) { - this(idManip, null, callerPage, false); + this(idManip, null, callerPage, false); } /** @@ -186,7 +186,7 @@ * @param callerPage Page appelante */ public ManagePurificationPage(Purification manip, CallerPage callerPage) { - this(null, manip, callerPage, true); + this(null, manip, callerPage, true); } /** @@ -199,122 +199,122 @@ * @param multipleEntry Saisie multiple */ private ManagePurificationPage(Integer idManip, Purification manip, final CallerPage callerPage, - boolean multipleEntry) { - super(ManagePurificationPage.class); - assert idManip == null || manip == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + boolean multipleEntry) { + super(ManagePurificationPage.class); + assert idManip == null || manip == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - fractionsDeleted = new HashMap<String, Integer>(); - newFractionModel = new Model<Fraction>(new Fraction()); + fractionsDeleted = new HashMap<String, Integer>(); + newFractionModel = new Model<Fraction>(new Fraction()); - // Initialisation du modèle - try { - purificationModel = new Model<Purification>(idManip == null && manip == null ? new Purification() - : manip != null ? manip : purificationService.loadPurification(idManip)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // Initialisation du modèle + try { + purificationModel = new Model<Purification>(idManip == null && manip == null ? new Purification() + : manip != null ? manip : purificationService.loadPurification(idManip)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - createMode = idManip == null; - if (createMode) { - purificationModel.getObject().setCreateur(getSession().getUtilisateur()); - } + createMode = idManip == null; + if (createMode) { + purificationModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes (pour le dropDownChoice) - personnes = personneService.listPersonnes(); - methodes = purificationService.listMethodesPurification(); - produits = produitService.listProduits(getSession().getUtilisateur()); + // Initialisation des listes (pour le dropDownChoice) + personnes = personneService.listPersonnes(); + methodes = purificationService.listMethodesPurification(); + produits = produitService.listProduits(getSession().getUtilisateur()); - if (manip != null) { - // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que - // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas - // l'égalité entre les objets) - purificationModel.getObject().setManipulateur( - CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, purificationModel - .getObject().getManipulateur().getIdPersonne())); - } + if (manip != null) { + // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que + // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas + // l'égalité entre les objets) + purificationModel.getObject().setManipulateur( + CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, purificationModel + .getObject().getManipulateur().getIdPersonne())); + } - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - // initialisation du formulaire - initPrincipalFields(formView); - initMethodeFields(formView); - initFractionsFields(formView); + // initialisation du formulaire + initPrincipalFields(formView); + initMethodeFields(formView); + initFractionsFields(formView); - // Action : create the purification - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.createPurification(purificationModel.getObject()); - } + // Action : create the purification + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.createPurification(purificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the purification - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.updatePurification(purificationModel.getObject()); - } + // Action : update the purification + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.updatePurification(purificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePurificationPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.deletePurification(purificationModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePurificationPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.deletePurification(purificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - formView.setDefaultButton(addPurificationButton); - add(formView); + formView.setDefaultButton(addPurificationButton); + add(formView); } @@ -323,47 +323,47 @@ * @param formView le formulaire */ private void initPrincipalFields(Form<Void> formView) { - formView.add(new TextField<String>("Purification.ref", new PropertyModel<String>(purificationModel, "ref"))); + formView.add(new TextField<String>("Purification.ref", new PropertyModel<String>(purificationModel, "ref"))); - formView.add(new DropDownChoice<Personne>("Purification.manipulateur", new PropertyModel<Personne>( - purificationModel, "manipulateur"), personnes, new PersonneRenderer()).setNullValid(false)); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } + formView.add(new DropDownChoice<Personne>("Purification.manipulateur", new PropertyModel<Personne>( + purificationModel, "manipulateur"), personnes, new PersonneRenderer()).setNullValid(false)); + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } + }); - formView.add(new DateTextField("Purification.date", new PropertyModel<Date>(purificationModel, "date")) - .add(new DatePicker())); + formView.add(new DateTextField("Purification.date", new PropertyModel<Date>(purificationModel, "date")) + .add(new DatePicker())); - AbstractSingleSelectChoice<Produit> produitsChoice = new DropDownChoice<Produit>("Purification.produit", - new PropertyModel<Produit>(purificationModel, "produit"), produits); - produitsChoice.setNullValid(false); - produitsChoice.setEnabled(createMode); - formView.add(produitsChoice); + AbstractSingleSelectChoice<Produit> produitsChoice = new DropDownChoice<Produit>("Purification.produit", + new PropertyModel<Produit>(purificationModel, "produit"), produits); + produitsChoice.setNullValid(false); + produitsChoice.setEnabled(createMode); + formView.add(produitsChoice); - TextField<BigDecimal> masseDepartInput = new TextField<BigDecimal>("Purification.masseDepart", - new PropertyModel<BigDecimal>(purificationModel, "masseDepart")); - masseDepartInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - }; - }); - formView.add(masseDepartInput); + TextField<BigDecimal> masseDepartInput = new TextField<BigDecimal>("Purification.masseDepart", + new PropertyModel<BigDecimal>(purificationModel, "masseDepart")); + masseDepartInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + }; + }); + formView.add(masseDepartInput); - formView.add(new TextArea<String>("Purification.complement", new PropertyModel<String>(purificationModel, - "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("Purification.createur", new PropertyModel<String>(purificationModel, - "createur")).setEnabled(false)); + formView.add(new TextArea<String>("Purification.complement", new PropertyModel<String>(purificationModel, + "complement"))); + // Créateur en lecture seule + formView.add(new TextField<String>("Purification.createur", new PropertyModel<String>(purificationModel, + "createur")).setEnabled(false)); } /** @@ -372,73 +372,73 @@ */ private void initMethodeFields(final Form<Void> formView) { - final WebMarkupContainer methodeCont = new WebMarkupContainer("Purification.methode"); - methodeCont.setOutputMarkupId(true); - formView.add(methodeCont); + final WebMarkupContainer methodeCont = new WebMarkupContainer("Purification.methode"); + methodeCont.setOutputMarkupId(true); + formView.add(methodeCont); - // Champs pour la méthode - descriptionMethoContainer = new WebMarkupContainer("Purification.descriptionMethodeCont") { - @Override - public boolean isVisible() { - // description cachée si pas de méthode sélectionnée - return purificationModel.getObject().getMethode() != null; - } - }; - descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax - descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); - methodeCont.add(descriptionMethoContainer); - final MultiLineLabel methodeDesc = new MultiLineLabel("Purification.descriptionMethode", - new PropertyModel<String>(purificationModel, "methode.description")); - methodeDesc.setOutputMarkupId(true); - descriptionMethoContainer.add(methodeDesc); + // Champs pour la méthode + descriptionMethoContainer = new WebMarkupContainer("Purification.descriptionMethodeCont") { + @Override + public boolean isVisible() { + // description cachée si pas de méthode sélectionnée + return purificationModel.getObject().getMethode() != null; + } + }; + descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax + descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); + methodeCont.add(descriptionMethoContainer); + final MultiLineLabel methodeDesc = new MultiLineLabel("Purification.descriptionMethode", + new PropertyModel<String>(purificationModel, "methode.description")); + methodeDesc.setOutputMarkupId(true); + descriptionMethoContainer.add(methodeDesc); - // Déclaration du container des paramètres de la méthode - paramsMethoContainer = new WebMarkupContainer("Purification.paramsMethode") { - @Override - public boolean isVisible() { - // paramètres cachés si pas de méthode sélectionnée - return purificationModel.getObject().getMethode() != null; - } - }; - final MarkupContainer paramsMethoTable = new WebMarkupContainer("Purification.paramsMethode.Table"); - paramsMethoContainer.add(paramsMethoTable); - paramsMethoContainer.setOutputMarkupId(true); - paramsMethoContainer.setOutputMarkupPlaceholderTag(true); + // Déclaration du container des paramètres de la méthode + paramsMethoContainer = new WebMarkupContainer("Purification.paramsMethode") { + @Override + public boolean isVisible() { + // paramètres cachés si pas de méthode sélectionnée + return purificationModel.getObject().getMethode() != null; + } + }; + final MarkupContainer paramsMethoTable = new WebMarkupContainer("Purification.paramsMethode.Table"); + paramsMethoContainer.add(paramsMethoTable); + paramsMethoContainer.setOutputMarkupId(true); + paramsMethoContainer.setOutputMarkupPlaceholderTag(true); - paramsMethoTable.add(new ListView<ParamMethoPuriEffectif>("Purification.paramsMethode.List", - new PropertyModel<List<ParamMethoPuriEffectif>>(purificationModel, "sortedParamsMetho")) { - @Override - protected void populateItem(ListItem<ParamMethoPuriEffectif> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + paramsMethoTable.add(new ListView<ParamMethoPuriEffectif>("Purification.paramsMethode.List", + new PropertyModel<List<ParamMethoPuriEffectif>>(purificationModel, "sortedParamsMetho")) { + @Override + protected void populateItem(ListItem<ParamMethoPuriEffectif> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final ParamMethoPuriEffectif param = item.getModelObject(); - // Colonnes - item.add(new Label("Purification.paramsMethode.nom", new PropertyModel<String>(param, "param.nom"))); - item.add(new SimpleTooltipPanel("Purification.paramsMethode.nom.info", new PropertyModel<String>(param, - "param.description"))); - item.add(new TextField<String>("Purification.paramsMethode.valeur", new PropertyModel<String>(param, - "valeur"))); - } - }); + final ParamMethoPuriEffectif param = item.getModelObject(); + // Colonnes + item.add(new Label("Purification.paramsMethode.nom", new PropertyModel<String>(param, "param.nom"))); + item.add(new SimpleTooltipPanel("Purification.paramsMethode.nom.info", new PropertyModel<String>(param, + "param.description"))); + item.add(new TextField<String>("Purification.paramsMethode.valeur", new PropertyModel<String>(param, + "valeur"))); + } + }); - methodeCont.add(paramsMethoContainer); + methodeCont.add(paramsMethoContainer); - final DropDownChoice<MethodePurification> methodeChoice = new DropDownChoice<MethodePurification>( - "Purification.nomMethode", new PropertyModel<MethodePurification>(purificationModel, "methode"), - methodes); - methodeChoice.setNullValid(false); - // mise à jour de la description de la méthode et des fractions lors de la sélection de la méthode - methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - // Intialisation des paramètres - purificationService.initParamsMethoPuriEffectif(purificationModel.getObject()); - // mise à jour de la description et des paramètres - target.add(methodeCont); - } - }); - methodeCont.add(methodeChoice); + final DropDownChoice<MethodePurification> methodeChoice = new DropDownChoice<MethodePurification>( + "Purification.nomMethode", new PropertyModel<MethodePurification>(purificationModel, "methode"), + methodes); + methodeChoice.setNullValid(false); + // mise à jour de la description de la méthode et des fractions lors de la sélection de la méthode + methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + // Intialisation des paramètres + purificationService.initParamsMethoPuriEffectif(purificationModel.getObject()); + // mise à jour de la description et des paramètres + target.add(methodeCont); + } + }); + methodeCont.add(methodeChoice); } /** @@ -447,159 +447,161 @@ */ private void initFractionsFields(final Form<Void> formView) { - // Déclaration tableau des fractions - final MarkupContainer purificationsTable = new WebMarkupContainer("Purification.fractions.Table"); - purificationsTable.setOutputMarkupId(true); + // Déclaration tableau des fractions + final MarkupContainer purificationsTable = new WebMarkupContainer("Purification.fractions.Table"); + purificationsTable.setOutputMarkupId(true); - // Contenu tableaux fractions - purificationsTable.add(new ListView<Fraction>("Purification.fractions.List", new PropertyModel<List<Fraction>>( - purificationModel, "sortedFractions")) { - @Override - protected void populateItem(ListItem<Fraction> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux fractions + purificationsTable.add(new ListView<Fraction>("Purification.fractions.List", new PropertyModel<List<Fraction>>( + purificationModel, "sortedFractions")) { + @Override + protected void populateItem(ListItem<Fraction> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final Fraction fraction = item.getModelObject(); - // Colonnes - item.add(new Label("Purification.fractions.List.indice", new PropertyModel<String>(fraction, "indice"))); - item.add(new Label("Purification.fractions.List.ref", new PropertyModel<String>(fraction, "ref"))); - item.add(new Label("Purification.fractions.List.masseObtenue", new DisplayDecimalPropertyModel( - fraction, "masseObtenue", DecimalDisplFormat.LARGE, getLocale()))); + final Fraction fraction = item.getModelObject(); + // Colonnes + item + .add(new Label("Purification.fractions.List.indice", new PropertyModel<String>(fraction, + "indice"))); + item.add(new Label("Purification.fractions.List.ref", new PropertyModel<String>(fraction, "ref"))); + item.add(new Label("Purification.fractions.List.masseObtenue", new DisplayDecimalPropertyModel( + fraction, "masseObtenue", DecimalDisplFormat.LARGE, getLocale()))); - item.add(new Label("Purification.fractions.List.rendement", new DisplayPercentPropertyModel(fraction, - "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("Purification.fractions.List.rendement", new DisplayPercentPropertyModel(fraction, + "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); - // Action : suppression d'une fraction - Button deleteButton = new AjaxFallbackButton("Purification.fractions.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // vérification si des données liées existe - if (produitService.isProduitReferenced(fraction)) { - getPage().error(getString("Fraction.isReferenced")); - } else { - // Suppression - purificationModel.getObject().getFractions().remove(fraction); - // keep the id of the deleted 'fraction' for the case of a new one with the same 'ref' - fractionsDeleted.put(fraction.getRef(), fraction.getId()); - } - if (target != null) { - target.add(purificationsTable); - refreshFeedbackPage(target); - } - } + // Action : suppression d'une fraction + Button deleteButton = new AjaxFallbackButton("Purification.fractions.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // vérification si des données liées existe + if (produitService.isProduitReferenced(fraction)) { + getPage().error(getString("Fraction.isReferenced")); + } else { + // Suppression + purificationModel.getObject().getFractions().remove(fraction); + // keep the id of the deleted 'fraction' for the case of a new one with the same 'ref' + fractionsDeleted.put(fraction.getRef(), fraction.getId()); + } + if (target != null) { + target.add(purificationsTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - final FormComponent<String> indiceInput = new TextField<String>("Purification.fractions.indice", - new PropertyModel<String>(newFractionModel, "indice")); - purificationsTable.add(indiceInput); + final FormComponent<String> indiceInput = new TextField<String>("Purification.fractions.indice", + new PropertyModel<String>(newFractionModel, "indice")); + purificationsTable.add(indiceInput); - final FormComponent<String> refInput = new TextField<String>("Purification.fractions.ref", - new PropertyModel<String>(newFractionModel, "ref")); - purificationsTable.add(refInput); + final FormComponent<String> refInput = new TextField<String>("Purification.fractions.ref", + new PropertyModel<String>(newFractionModel, "ref")); + purificationsTable.add(refInput); - final FormComponent<BigDecimal> masseObtenueInput = new TextField<BigDecimal>( - "Purification.fractions.masseObtenue", new PropertyModel<BigDecimal>(newFractionModel, "masseObtenue")); - purificationsTable.add(masseObtenueInput); + final FormComponent<BigDecimal> masseObtenueInput = new TextField<BigDecimal>( + "Purification.fractions.masseObtenue", new PropertyModel<BigDecimal>(newFractionModel, "masseObtenue")); + purificationsTable.add(masseObtenueInput); - // Bouton AJAX pour ajouter une fraction - addPurificationButton = new AjaxFallbackButton("Purification.fractions.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // normalisation de la fraction - newFractionModel.getObject().setRef( - Normalizer.normalize(UniqueFieldNormalizer.class, newFractionModel.getObject().getRef())); - // ajout du type purification - newFractionModel.getObject().setPurification(purificationModel.getObject()); - // recuperate the id if an just deleted type - newFractionModel.getObject().setId(fractionsDeleted.get(newFractionModel.getObject().getRef())); + // Bouton AJAX pour ajouter une fraction + addPurificationButton = new AjaxFallbackButton("Purification.fractions.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // normalisation de la fraction + newFractionModel.getObject().setRef( + Normalizer.normalize(UniqueFieldNormalizer.class, newFractionModel.getObject().getRef())); + // ajout du type purification + newFractionModel.getObject().setPurification(purificationModel.getObject()); + // recuperate the id if an just deleted type + newFractionModel.getObject().setId(fractionsDeleted.get(newFractionModel.getObject().getRef())); - // ajout à la liste - Fraction fractionAdded = newFractionModel.getObject().clone(); - purificationModel.getObject().getFractions().add(fractionAdded); + // ajout à la liste + Fraction fractionAdded = newFractionModel.getObject().clone(); + purificationModel.getObject().getFractions().add(fractionAdded); - List<String> errors = validator.validate(newFractionModel.getObject(), getSession().getLocale()); - // test si unicité dans la base - // erreur si non unique dans la base ET extrait de même réf non supprimé de la liste (dans ce - // dernier cas, ajout avec son ancien id) ET non pris en compte par la validation de - // CollectionUniqueFieldValidator - if (!purificationService.isFractionUnique(fractionAdded) - && fractionAdded.getRef() != null - && fractionsDeleted.get(fractionAdded.getRef()) == null - && CollectionTools.countWithValue(fractionAdded.getPurification().getFractions(), "ref", - AccessType.GETTER, fractionAdded.getRef()) == 1) { - errors.add(getString("Fraction.notUnique")); - } + List<String> errors = validator.validate(newFractionModel.getObject(), getSession().getLocale()); + // test si unicité dans la base + // erreur si non unique dans la base ET extrait de même réf non supprimé de la liste (dans ce + // dernier cas, ajout avec son ancien id) ET non pris en compte par la validation de + // CollectionUniqueFieldValidator + if (!purificationService.isFractionUnique(fractionAdded) + && fractionAdded.getRef() != null + && fractionsDeleted.get(fractionAdded.getRef()) == null + && CollectionTools.countWithValue(fractionAdded.getPurification().getFractions(), "ref", + AccessType.GETTER, fractionAdded.getRef()) == 1) { + errors.add(getString("Fraction.notUnique")); + } - if (errors.isEmpty()) { - // réinit du champ ajout - newFractionModel.getObject().setIndice(null); - newFractionModel.getObject().setRef(null); - newFractionModel.getObject().setMasseObtenue(null); - } else { - purificationModel.getObject().getFractions().remove(fractionAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + if (errors.isEmpty()) { + // réinit du champ ajout + newFractionModel.getObject().setIndice(null); + newFractionModel.getObject().setRef(null); + newFractionModel.getObject().setMasseObtenue(null); + } else { + purificationModel.getObject().getFractions().remove(fractionAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - if (target != null) { - target.add(purificationsTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(purificationsTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - purificationsTable.add(addPurificationButton); + }; + purificationsTable.add(addPurificationButton); - formView.add(purificationsTable); + formView.add(purificationsTable); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Personne ou Lot) - refreshModel(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Personne ou Lot) + refreshModel(); - super.onBeforeRender(); + super.onBeforeRender(); } /** * Redirection vers une autre page. CAs où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection de nouveau vers l'écran de saisie d'une nouvelle purification - Purification nextManip = new Purification(); - nextManip.setManipulateur(purificationModel.getObject().getManipulateur()); - setResponsePage(new ManagePurificationPage(nextManip, callerPage)); - } else if (callerPage != null) { - // On passe l'id de la purification associée à cette page, en paramètre de la prochaine page, pour lui - // permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Purification.class.getSimpleName(), purificationModel.getObject() - .getIdPurification()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection de nouveau vers l'écran de saisie d'une nouvelle purification + Purification nextManip = new Purification(); + nextManip.setManipulateur(purificationModel.getObject().getManipulateur()); + setResponsePage(new ManagePurificationPage(nextManip, callerPage)); + } else if (callerPage != null) { + // On passe l'id de la purification associée à cette page, en paramètre de la prochaine page, pour lui + // permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Purification.class.getSimpleName(), purificationModel.getObject() + .getIdPurification()); + callerPage.responsePage(this); + } } /** @@ -607,31 +609,31 @@ */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Personne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(personnes, personneService.listPersonnes()); - try { - Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); - purificationModel.getObject().setManipulateur(createdPersonne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Personne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(personnes, personneService.listPersonnes()); + try { + Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); + purificationModel.getObject().setManipulateur(createdPersonne); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(purificationModel.getObject(), getSession().getLocale())); - if (!purificationService.isPurificationUnique(purificationModel.getObject())) { - error(getString("Purification.notUnique")); - } + addValidationErrors(validator.validate(purificationModel.getObject(), getSession().getLocale())); + if (!purificationService.isPurificationUnique(purificationModel.getObject())) { + error(getString("Purification.notUnique")); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ReadPurificationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ReadPurificationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/purification/ReadPurificationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -99,187 +99,189 @@ * @param callerPage Page appelante */ public ReadPurificationPage(Integer idPurification, final CallerPage callerPage) { - super(ReadPurificationPage.class); - this.callerPage = callerPage; - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + super(ReadPurificationPage.class); + this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - // Initialisation du modèle - purificationModel = new GenericLoadableDetachableModel<Purification>(Purification.class, idPurification); + // Initialisation du modèle + purificationModel = new GenericLoadableDetachableModel<Purification>(Purification.class, idPurification); - add(new Label("Purification.ref", new PropertyModel<String>(purificationModel, "ref")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Purification.manipulateur", new PropertyModel<Personne>(purificationModel, "manipulateur")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Purification.date", new PropertyModel<Date>(purificationModel, "date")) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Purification.ref", new PropertyModel<String>(purificationModel, "ref")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Purification.manipulateur", new PropertyModel<Personne>(purificationModel, "manipulateur")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Purification.date", new PropertyModel<Date>(purificationModel, "date")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkProduitPanel("Purification.produit", new PropertyModel<Produit>(purificationModel, - "produit"), (TemplatePage) getPage()) { - @Override - public void onClickIfExtrait(Extrait extrait) { - setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); - } + add(new PropertyLabelLinkProduitPanel("Purification.produit", new PropertyModel<Produit>(purificationModel, + "produit"), (TemplatePage) getPage()) { + @Override + public void onClickIfExtrait(Extrait extrait) { + setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); + } - @Override - public void onClickIfFraction(Fraction fraction) { - setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), currentPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), currentPage)); + } + }); - add(new Label("Purification.masseDepart", new PropertyModel<BigInteger>(purificationModel, "masseDepart")) - .add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Purification.complement", new PropertyModel<String>(purificationModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Purification.createur", new PropertyModel<Personne>( - purificationModel, "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); - // Méthode purification - final WebMarkupContainer methodeCont = new WebMarkupContainer("Purification.methode"); - methodeCont.add(new Label("Purification.nomMethode", new PropertyModel<MethodePurification>(purificationModel, - "methode"))); - methodeCont.setOutputMarkupId(true); - add(methodeCont); + add(new Label("Purification.masseDepart", new PropertyModel<BigInteger>(purificationModel, "masseDepart")) + .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Purification.complement", new PropertyModel<String>(purificationModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); + add(new PropertyLabelLinkPanel<Personne>("Purification.createur", new PropertyModel<Personne>( + purificationModel, "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); + // Méthode purification + final WebMarkupContainer methodeCont = new WebMarkupContainer("Purification.methode"); + methodeCont.add(new Label("Purification.nomMethode", new PropertyModel<MethodePurification>(purificationModel, + "methode"))); + methodeCont.setOutputMarkupId(true); + add(methodeCont); - // Champs pour la méthode - descriptionMethoContainer = new WebMarkupContainer("Purification.descriptionMethodeCont") { - @Override - public boolean isVisible() { - // description cachée si pas de méthode sélectionnée - return purificationModel.getObject().getMethode() != null; - } - }; - methodeCont.add(descriptionMethoContainer); - final MultiLineLabel methodeDesc = new MultiLineLabel("Purification.descriptionMethode", - new PropertyModel<String>(purificationModel, "methode.description")); - methodeDesc.setOutputMarkupId(true); - descriptionMethoContainer.add(methodeDesc); + // Champs pour la méthode + descriptionMethoContainer = new WebMarkupContainer("Purification.descriptionMethodeCont") { + @Override + public boolean isVisible() { + // description cachée si pas de méthode sélectionnée + return purificationModel.getObject().getMethode() != null; + } + }; + methodeCont.add(descriptionMethoContainer); + final MultiLineLabel methodeDesc = new MultiLineLabel("Purification.descriptionMethode", + new PropertyModel<String>(purificationModel, "methode.description")); + methodeDesc.setOutputMarkupId(true); + descriptionMethoContainer.add(methodeDesc); - // Déclaration du container des paramètres de la méthode - paramsMethoContainer = new WebMarkupContainer("Purification.paramsMethode") { - @Override - public boolean isVisible() { - // paramètres cachés si pas de méthode sélectionnée - return purificationModel.getObject().getMethode() != null; - } - }; - final MarkupContainer paramsMethoTable = new WebMarkupContainer("Purification.paramsMethode.Table"); - paramsMethoContainer.add(paramsMethoTable); + // Déclaration du container des paramètres de la méthode + paramsMethoContainer = new WebMarkupContainer("Purification.paramsMethode") { + @Override + public boolean isVisible() { + // paramètres cachés si pas de méthode sélectionnée + return purificationModel.getObject().getMethode() != null; + } + }; + final MarkupContainer paramsMethoTable = new WebMarkupContainer("Purification.paramsMethode.Table"); + paramsMethoContainer.add(paramsMethoTable); - ListView<ParamMethoPuriEffectif> paramMethodes = new ListView<ParamMethoPuriEffectif>( - "Purification.paramsMethode.List", new PropertyModel<List<ParamMethoPuriEffectif>>(purificationModel, - "sortedParamsMetho")) { - @Override - protected void populateItem(ListItem<ParamMethoPuriEffectif> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + ListView<ParamMethoPuriEffectif> paramMethodes = new ListView<ParamMethoPuriEffectif>( + "Purification.paramsMethode.List", new PropertyModel<List<ParamMethoPuriEffectif>>(purificationModel, + "sortedParamsMetho")) { + @Override + protected void populateItem(ListItem<ParamMethoPuriEffectif> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final ParamMethoPuriEffectif param = item.getModelObject(); - // Colonnes - item.add(new Label("Purification.paramsMethode.nom", new PropertyModel<String>(param, "param.nom"))); - item.add(new SimpleTooltipPanel("Purification.paramsMethode.nom.info", new PropertyModel<String>(param, - "param.description"))); - item.add(new Label("Purification.paramsMethode.valeur", new PropertyModel<String>(param, "valeur")) - .add(new ReplaceEmptyLabelBehavior())); - } - }; - paramsMethoTable.add(paramMethodes); - methodeCont.add(paramsMethoContainer); + final ParamMethoPuriEffectif param = item.getModelObject(); + // Colonnes + item.add(new Label("Purification.paramsMethode.nom", new PropertyModel<String>(param, "param.nom"))); + item.add(new SimpleTooltipPanel("Purification.paramsMethode.nom.info", new PropertyModel<String>(param, + "param.description"))); + item.add(new Label("Purification.paramsMethode.valeur", new PropertyModel<String>(param, "valeur")) + .add(new ReplaceEmptyLabelBehavior())); + } + }; + paramsMethoTable.add(paramMethodes); + methodeCont.add(paramsMethoContainer); - add(methodeCont); + add(methodeCont); - // Fractions - // Déclaration tableau des fractions - final MarkupContainer purificationsTable = new WebMarkupContainer("Purification.fractions.Table") { - @Override - public boolean isVisible() { - return purificationModel.getObject().getFractions().size() > 0; - } - }; - purificationsTable.setOutputMarkupId(true); + // Fractions + // Déclaration tableau des fractions + final MarkupContainer purificationsTable = new WebMarkupContainer("Purification.fractions.Table") { + @Override + public boolean isVisible() { + return purificationModel.getObject().getFractions().size() > 0; + } + }; + purificationsTable.setOutputMarkupId(true); - // Contenu tableaux fractions - purificationsTable.add(new ListView<Fraction>("Purification.fractions.List", new PropertyModel<List<Fraction>>( - purificationModel, "sortedFractions")) { - @Override - protected void populateItem(ListItem<Fraction> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux fractions + purificationsTable.add(new ListView<Fraction>("Purification.fractions.List", new PropertyModel<List<Fraction>>( + purificationModel, "sortedFractions")) { + @Override + protected void populateItem(ListItem<Fraction> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final Fraction fraction = item.getModelObject(); - // Colonnes - item.add(new Label("Purification.fractions.List.indice", new PropertyModel<String>(fraction, "indice"))); - item.add(new Label("Purification.fractions.List.ref", new PropertyModel<String>(fraction, "ref"))); - item.add(new Label("Purification.fractions.List.masseObtenue", new DisplayDecimalPropertyModel(item - .getModel(), "masseObtenue", DecimalDisplFormat.LARGE, getLocale()))); - item.add(new Label("Purification.fractions.List.rendement", new DisplayPercentPropertyModel(item - .getModel(), "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); - } - }); - add(purificationsTable); + final Fraction fraction = item.getModelObject(); + // Colonnes + item + .add(new Label("Purification.fractions.List.indice", new PropertyModel<String>(fraction, + "indice"))); + item.add(new Label("Purification.fractions.List.ref", new PropertyModel<String>(fraction, "ref"))); + item.add(new Label("Purification.fractions.List.masseObtenue", new DisplayDecimalPropertyModel(item + .getModel(), "masseObtenue", DecimalDisplFormat.LARGE, getLocale()))); + item.add(new Label("Purification.fractions.List.rendement", new DisplayPercentPropertyModel(item + .getModel(), "rendement", getLocale())).add(new ReplaceEmptyLabelBehavior())); + } + }); + add(purificationsTable); - // Selon la non existence d'elements dans la liste on affiche le span - add(new WebMarkupContainer("Purification.fractions.noTable") { - @Override - public boolean isVisible() { - return !purificationsTable.isVisible(); - } - }); + // Selon la non existence d'elements dans la liste on affiche le span + add(new WebMarkupContainer("Purification.fractions.noTable") { + @Override + public boolean isVisible() { + return !purificationsTable.isVisible(); + } + }); - // Formulaire des actions - final Form<Void> formView = new Form<Void>("Form"); + // Formulaire des actions + final Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<Purification> updateLink = new Link<Purification>(getResource() + ".Purification.Update", - new Model<Purification>(purificationModel.getObject())) { - @Override - public void onClick() { - setResponsePage(new ManagePurificationPage(getModelObject().getIdPurification(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(purificationService.updateOrdeletePurificationEnabled( - purificationModel.getObject(), getSession().getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Purification> updateLink = new Link<Purification>(getResource() + ".Purification.Update", + new Model<Purification>(purificationModel.getObject())) { + @Override + public void onClick() { + setResponsePage(new ManagePurificationPage(getModelObject().getIdPurification(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(purificationService.updateOrdeletePurificationEnabled(purificationModel + .getObject(), getSession().getUtilisateur())); + formView.add(updateLink); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePurificationPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - purificationService.deletePurification(purificationModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManagePurificationPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + purificationService.deletePurification(purificationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ManagePurificationPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(purificationService.updateOrdeletePurificationEnabled( - purificationModel.getObject(), getSession().getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ManagePurificationPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(purificationService.updateOrdeletePurificationEnabled(purificationModel + .getObject(), getSession().getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - // Action : retour - formView.add(new Link<Void>(getResource() + ".Purification.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); - add(formView); + // Action : retour + formView.add(new Link<Void>(getResource() + ".Purification.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/search/SearchPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/search/SearchPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/search/SearchPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,7 +67,7 @@ * * @author echatellier */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public class SearchPage extends TemplatePage { /** Form query. */ @@ -111,64 +111,66 @@ * @param query form query */ public SearchPage(String query) { - super(SearchPage.class); - this.query = query; - final CallerPage currentPage = new CallerPage(SearchPage.class); + super(SearchPage.class); + this.query = query; + final CallerPage currentPage = new CallerPage(SearchPage.class); - // ca sert a rien, mais wicket est pas content - ExternalLink link = new ExternalLink("advancedLink", "http://lucene.apache.org/core/3_6_2/queryparsersyntax.html"); - add(link); - - // search form - Form<ValueMap> searchForm = new Form<ValueMap>(getResource() + ".Form") { - protected void onSubmit() { - setResponsePage(new SearchPage(getQuery())); - } - }; - searchForm.add(new TextField<String>("query", new PropertyModel<String>(this, "query")).setType(String.class)); - add(searchForm); + // ca sert a rien, mais wicket est pas content + ExternalLink link = new ExternalLink("advancedLink", + "http://lucene.apache.org/core/3_6_2/queryparsersyntax.html"); + add(link); - // search results - Utilisateur utilisateur = getSession().getUtilisateur(); - SearchResult searchResult = searchService.search(query, utilisateur); - // Additional transformation for molecule provenances - List<Molecule> molecules = searchResult.getMolecules(); - List<MoleculeProvenanceBean> moleculeProvenances = moleculeService.listMoleculeProvenances(molecules, utilisateur); + // search form + Form<ValueMap> searchForm = new Form<ValueMap>(getResource() + ".Form") { + protected void onSubmit() { + setResponsePage(new SearchPage(getQuery())); + } + }; + searchForm.add(new TextField<String>("query", new PropertyModel<String>(this, "query")).setType(String.class)); + add(searchForm); - // specimens table - DataTable<Specimen, String> specimensDataTable = ListSpecimensPage.initSpecimensDataTable(this, - "SearchPage.Specimens.Results", currentPage, searchResult.getSpecimens(), specimenService); - add(specimensDataTable); + // search results + Utilisateur utilisateur = getSession().getUtilisateur(); + SearchResult searchResult = searchService.search(query, utilisateur); + // Additional transformation for molecule provenances + List<Molecule> molecules = searchResult.getMolecules(); + List<MoleculeProvenanceBean> moleculeProvenances = moleculeService.listMoleculeProvenances(molecules, + utilisateur); - // lot table - DataTable<Lot, String> lotsDataTable = ListLotsPage.initLotsDataTable(this, - "SearchPage.Lots.Results", currentPage, searchResult.getLots(), lotService); - add(lotsDataTable); + // specimens table + DataTable<Specimen, String> specimensDataTable = ListSpecimensPage.initSpecimensDataTable(this, + "SearchPage.Specimens.Results", currentPage, searchResult.getSpecimens(), specimenService); + add(specimensDataTable); - // extractions table - DataTable<Extraction, String> extractionsDataTable = ListExtractionsPage.initExtractionsDataTable(this, - "SearchPage.Extractions.Results", currentPage, searchResult.getExtractions(), extractionService); - add(extractionsDataTable); + // lot table + DataTable<Lot, String> lotsDataTable = ListLotsPage.initLotsDataTable(this, "SearchPage.Lots.Results", + currentPage, searchResult.getLots(), lotService); + add(lotsDataTable); - // purification table - DataTable<Purification, String> purificationsDataTable = ListPurificationsPage.initPurificationsDataTable(this, - "SearchPage.Purifications.Results", currentPage, searchResult.getPurifications(), purificationService); - add(purificationsDataTable); + // extractions table + DataTable<Extraction, String> extractionsDataTable = ListExtractionsPage.initExtractionsDataTable(this, + "SearchPage.Extractions.Results", currentPage, searchResult.getExtractions(), extractionService); + add(extractionsDataTable); - // test bio table - DataTable<ResultatTestBio, String> testBiosDataTable = ListTestsBioPage.initTestsBioDataTable(this, - "SearchPage.ResultatTestBios.Results", currentPage, searchResult.getResultatTestBios(), testBioService); - add(testBiosDataTable); + // purification table + DataTable<Purification, String> purificationsDataTable = ListPurificationsPage.initPurificationsDataTable(this, + "SearchPage.Purifications.Results", currentPage, searchResult.getPurifications(), purificationService); + add(purificationsDataTable); - // stations table - DataTable<Station, String> stationsDataTable = ListStationsPage.initStationsDataTable(this, - "SearchPage.Stations.Results", currentPage, searchResult.getStations(), stationService); - add(stationsDataTable); + // test bio table + DataTable<ResultatTestBio, String> testBiosDataTable = ListTestsBioPage.initTestsBioDataTable(this, + "SearchPage.ResultatTestBios.Results", currentPage, searchResult.getResultatTestBios(), testBioService); + add(testBiosDataTable); - // molecule table - DataTable<MoleculeProvenanceBean, String> moleculesDataTable = ListMoleculesPage.initMoleculesDataTable(this, - "SearchPage.Molecules.Results", currentPage, moleculeProvenances); - add(moleculesDataTable); + // stations table + DataTable<Station, String> stationsDataTable = ListStationsPage.initStationsDataTable(this, + "SearchPage.Stations.Results", currentPage, searchResult.getStations(), stationService); + add(stationsDataTable); + + // molecule table + DataTable<MoleculeProvenanceBean, String> moleculesDataTable = ListMoleculesPage.initMoleculesDataTable(this, + "SearchPage.Molecules.Results", currentPage, moleculeProvenances); + add(moleculesDataTable); } /** @@ -177,6 +179,6 @@ * @return form query value */ public String getQuery() { - return query; + return query; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ListSpecimensPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ListSpecimensPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ListSpecimensPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -59,7 +59,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ListSpecimensPage extends TemplatePage { /** Service : specimen */ @@ -70,28 +70,28 @@ * Constructeur */ public ListSpecimensPage() { - super(ListSpecimensPage.class); + super(ListSpecimensPage.class); - final CallerPage currentPage = new CallerPage(ListSpecimensPage.class); + final CallerPage currentPage = new CallerPage(ListSpecimensPage.class); - add(new Link<Void>(getResource() + ".NewSpecimen") { - @Override - public void onClick() { - setResponsePage(new ManageSpecimenPage(currentPage, true)); - } - }); + add(new Link<Void>(getResource() + ".NewSpecimen") { + @Override + public void onClick() { + setResponsePage(new ManageSpecimenPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer specimensRefresh = new WebMarkupContainer(getResource() + ".Specimens.Refresh"); - specimensRefresh.setOutputMarkupId(true); - add(specimensRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer specimensRefresh = new WebMarkupContainer(getResource() + ".Specimens.Refresh"); + specimensRefresh.setOutputMarkupId(true); + add(specimensRefresh); - // Liste des Specimens - final List<Specimen> specimens = specimenService.listSpecimens(getSession().getUtilisateur()); - DataTable<Specimen, String> specimensDataTable = initSpecimensDataTable(this, - "ListSpecimensPage.Specimens", currentPage, specimens, specimenService); - specimensRefresh.add(specimensDataTable); + // Liste des Specimens + final List<Specimen> specimens = specimenService.listSpecimens(getSession().getUtilisateur()); + DataTable<Specimen, String> specimensDataTable = initSpecimensDataTable(this, "ListSpecimensPage.Specimens", + currentPage, specimens, specimenService); + specimensRefresh.add(specimensDataTable); } /** @@ -107,79 +107,82 @@ * @return data table component */ public static DataTable<Specimen, String> initSpecimensDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<Specimen> specimens, final SpecimenService specimenService) { + final String componentId, final CallerPage callerPage, List<Specimen> specimens, + final SpecimenService specimenService) { - - LoadableDetachableSortableListDataProvider<Specimen> specimensDataProvider = new LoadableDetachableSortableListDataProvider<Specimen>( - specimens, templatePage.getSession().getLocale()); + LoadableDetachableSortableListDataProvider<Specimen> specimensDataProvider = new LoadableDetachableSortableListDataProvider<Specimen>( + specimens, templatePage.getSession().getLocale()); - List<IColumn<Specimen, String>> columns = new ArrayList<IColumn<Specimen, String>>(); + List<IColumn<Specimen, String>> columns = new ArrayList<IColumn<Specimen, String>>(); - columns.add(new LinkableImagePropertyColumn<Specimen, String>("images/read.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { - templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Specimen, String>("images/read.png", + templatePage.getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { + templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.ref")), "ref", "ref", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { - templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.ref")), + "ref", "ref", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { + templatePage.setResponsePage(new ReadSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); + } + }); - columns.add(new EnumPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.typeOrganisme")), - "typeOrganisme", "typeOrganisme", templatePage)); + columns.add(new EnumPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.typeOrganisme")), "typeOrganisme", "typeOrganisme", templatePage)); - columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.embranchement")), - "embranchement", "embranchement")); + columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.embranchement")), "embranchement", "embranchement")); - columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.famille")), "famille", - "famille")); + columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.famille")), "famille", "famille")); - columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.genre")), "genre", - "genre")); + columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.genre")), "genre", "genre")); - columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.espece")), "espece", - "espece")); + columns.add(new TaxonomyPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.espece")), "espece", "espece")); - columns.add(new LinkPropertyColumn<Specimen, String>(new Model<String>(templatePage.getString("Specimen.station2")), "station", - "station", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { - templatePage.setResponsePage(new ReadStationPage(model.getObject().getStation().getIdStation(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Specimen, String>(new Model<String>(templatePage + .getString("Specimen.station2")), "station", "station", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { + templatePage.setResponsePage(new ReadStationPage(model.getObject().getStation().getIdStation(), + callerPage)); + } + }); - columns.add(new LinkableImagePropertyColumn<Specimen, String>("images/edit.png", templatePage.getString("Update"), - templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + columns.add(new LinkableImagePropertyColumn<Specimen, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - if (specimenService.updateOrdeleteSpecimenEnabled(model.getObject(), templatePage.getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + if (specimenService.updateOrdeleteSpecimenEnabled(model.getObject(), templatePage.getSession() + .getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { - templatePage.setResponsePage(new ManageSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<Specimen>> item, String componentId, IModel<Specimen> model) { + templatePage.setResponsePage(new ManageSpecimenPage(model.getObject().getIdSpecimen(), callerPage)); + } + }); - final DataTable<Specimen, String> specimensDataTable = new AjaxFallbackDefaultDataTable<Specimen, String>( - componentId, columns, specimensDataProvider, WebContext.ROWS_PER_PAGE); - specimensDataTable.addBottomToolbar(new TableExportToolbar(specimensDataTable, "specimens", templatePage.getSession().getLocale())); - return specimensDataTable; + final DataTable<Specimen, String> specimensDataTable = new AjaxFallbackDefaultDataTable<Specimen, String>( + componentId, columns, specimensDataProvider, WebContext.ROWS_PER_PAGE); + specimensDataTable.addBottomToolbar(new TableExportToolbar(specimensDataTable, "specimens", templatePage + .getSession().getLocale())); + return specimensDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ManageSpecimenPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ManageSpecimenPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ManageSpecimenPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -76,7 +76,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.USER, AuthRole.ADMIN }) +@AuthRoles( { AuthRole.USER, AuthRole.ADMIN }) public final class ManageSpecimenPage extends TemplatePage { /** Action : create */ @@ -128,7 +128,7 @@ * @param multipleEntry Saisie multiple */ public ManageSpecimenPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -137,7 +137,7 @@ * @param callerPage Page appelante */ public ManageSpecimenPage(Integer idSpecimen, CallerPage callerPage) { - this(idSpecimen, null, callerPage, false); + this(idSpecimen, null, callerPage, false); } /** @@ -146,7 +146,7 @@ * @param callerPage Page appelante */ public ManageSpecimenPage(Specimen specimen, CallerPage callerPage) { - this(null, specimen, callerPage, true); + this(null, specimen, callerPage, true); } /** @@ -159,229 +159,230 @@ * @param multipleEntry Saisie multiple */ private ManageSpecimenPage(Integer idSpecimen, Specimen specimen, final CallerPage callerPage, boolean multipleEntry) { - super(ManageSpecimenPage.class); - assert idSpecimen == null || specimen == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManageSpecimenPage.class); + assert idSpecimen == null || specimen == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - final CallerPage currentPage = new CallerPage(this); + final CallerPage currentPage = new CallerPage(this); - // Initialisation du modèle - try { - specimenModel = new Model<Specimen>(idSpecimen == null && specimen == null ? new Specimen() - : specimen != null ? specimen : specimenService.loadSpecimen(idSpecimen)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - boolean createMode = idSpecimen == null; - if (createMode) { - specimenModel.getObject().setCreateur(getSession().getUtilisateur()); - } + // Initialisation du modèle + try { + specimenModel = new Model<Specimen>(idSpecimen == null && specimen == null ? new Specimen() + : specimen != null ? specimen : specimenService.loadSpecimen(idSpecimen)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + boolean createMode = idSpecimen == null; + if (createMode) { + specimenModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes (pour le dropDownChoice) - personnes = personneService.listPersonnes(); - stations = stationService.listStations(getSession().getUtilisateur()); + // Initialisation des listes (pour le dropDownChoice) + personnes = personneService.listPersonnes(); + stations = stationService.listStations(getSession().getUtilisateur()); - // Initialisation des listes (pour le AutoCompleteTextField) - // liste des valeurs déjà existantes pour la propriété correspondante - List<String> embranchements = specimenService.listSpecimenEmbranchements(); - List<String> familles = specimenService.listSpecimenFamilles(); - List<String> genres = specimenService.listSpecimenGenres(); - List<String> especes = specimenService.listSpecimenEspeces(); - List<String> sousEspeces = specimenService.listSpecimenSousEspeces(); - List<String> varietes = specimenService.listSpecimenVarietes(); - List<String> lieuxDepot = specimenService.listLieuxDepot(); + // Initialisation des listes (pour le AutoCompleteTextField) + // liste des valeurs déjà existantes pour la propriété correspondante + List<String> embranchements = specimenService.listSpecimenEmbranchements(); + List<String> familles = specimenService.listSpecimenFamilles(); + List<String> genres = specimenService.listSpecimenGenres(); + List<String> especes = specimenService.listSpecimenEspeces(); + List<String> sousEspeces = specimenService.listSpecimenSousEspeces(); + List<String> varietes = specimenService.listSpecimenVarietes(); + List<String> lieuxDepot = specimenService.listLieuxDepot(); - if (specimen != null) { - // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que - // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas - // l'égalité entre les objets) - if (specimenModel.getObject().getIdentificateur() != null) { - specimenModel.getObject().setIdentificateur( - CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, specimenModel - .getObject().getIdentificateur().getIdPersonne())); - } - if (specimenModel.getObject().getStation() != null) { - specimenModel.getObject().setStation( - CollectionTools.findWithValue(stations, "idStation", AccessType.GETTER, specimenModel - .getObject().getStation().getIdStation())); - } - } + if (specimen != null) { + // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que + // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas + // l'égalité entre les objets) + if (specimenModel.getObject().getIdentificateur() != null) { + specimenModel.getObject().setIdentificateur( + CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, specimenModel + .getObject().getIdentificateur().getIdPersonne())); + } + if (specimenModel.getObject().getStation() != null) { + specimenModel.getObject().setStation( + CollectionTools.findWithValue(stations, "idStation", AccessType.GETTER, specimenModel + .getObject().getStation().getIdStation())); + } + } - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("Specimen.ref", new PropertyModel<String>(specimenModel, "ref"))); - formView.add(new AutoCompleteTextFieldString("Specimen.embranchement", new PropertyModel<String>(specimenModel, - "embranchement"), embranchements, ComparisonMode.CONTAINS)); - formView.add(new AutoCompleteTextFieldString("Specimen.famille", new PropertyModel<String>(specimenModel, - "famille"), familles, ComparisonMode.CONTAINS)); - formView.add(new AutoCompleteTextFieldString("Specimen.genre", - new PropertyModel<String>(specimenModel, "genre"), genres, ComparisonMode.CONTAINS)); - formView.add(new AutoCompleteTextFieldString("Specimen.espece", new PropertyModel<String>(specimenModel, - "espece"), especes, ComparisonMode.CONTAINS)); - formView.add(new AutoCompleteTextFieldString("Specimen.sousEspece", new PropertyModel<String>(specimenModel, - "sousEspece"), sousEspeces, ComparisonMode.CONTAINS)); - formView.add(new AutoCompleteTextFieldString("Specimen.variete", new PropertyModel<String>(specimenModel, - "variete"), varietes, ComparisonMode.CONTAINS)); + formView.add(new TextField<String>("Specimen.ref", new PropertyModel<String>(specimenModel, "ref"))); + formView.add(new AutoCompleteTextFieldString("Specimen.embranchement", new PropertyModel<String>(specimenModel, + "embranchement"), embranchements, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("Specimen.famille", new PropertyModel<String>(specimenModel, + "famille"), familles, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("Specimen.genre", + new PropertyModel<String>(specimenModel, "genre"), genres, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("Specimen.espece", new PropertyModel<String>(specimenModel, + "espece"), especes, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("Specimen.sousEspece", new PropertyModel<String>(specimenModel, + "sousEspece"), sousEspeces, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("Specimen.variete", new PropertyModel<String>(specimenModel, + "variete"), varietes, ComparisonMode.CONTAINS)); - DropDownChoice<TypeOrganisme> typeOrganismeInput = new DropDownChoice<TypeOrganisme>("Specimen.typeOrganisme", - new PropertyModel<TypeOrganisme>(specimenModel, "typeOrganisme"), - Arrays.asList(TypeOrganisme.values()), new EnumChoiceRenderer<TypeOrganisme>(this)); - typeOrganismeInput.setNullValid(false); - formView.add(typeOrganismeInput); + DropDownChoice<TypeOrganisme> typeOrganismeInput = new DropDownChoice<TypeOrganisme>("Specimen.typeOrganisme", + new PropertyModel<TypeOrganisme>(specimenModel, "typeOrganisme"), + Arrays.asList(TypeOrganisme.values()), new EnumChoiceRenderer<TypeOrganisme>(this)); + typeOrganismeInput.setNullValid(false); + formView.add(typeOrganismeInput); - formView.add(new DropDownChoice<Personne>("Specimen.identificateur", new PropertyModel<Personne>(specimenModel, - "identificateur"), personnes, new PersonneRenderer()).setNullValid(true)); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManagePersonnePage(currentPage, false)); - } + formView.add(new DropDownChoice<Personne>("Specimen.identificateur", new PropertyModel<Personne>(specimenModel, + "identificateur"), personnes, new PersonneRenderer()).setNullValid(true)); + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManagePersonnePage(currentPage, false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(currentPage, false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(currentPage, false)); + } + }); - formView.add(new DropDownChoice<Station>("Specimen.station", new PropertyModel<Station>(specimenModel, - "station"), stations).setNullValid(true)); + formView.add(new DropDownChoice<Station>("Specimen.station", new PropertyModel<Station>(specimenModel, + "station"), stations).setNullValid(true)); - // Action : création d'une nouvelle station - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewStation") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManageStationPage(currentPage, false)); - } + // Action : création d'une nouvelle station + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewStation") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManageStationPage(currentPage, false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManageStationPage(currentPage, false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManageStationPage(currentPage, false)); + } + }); - formView.add(new TextArea<String>("Specimen.complement", new PropertyModel<String>(specimenModel, "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("Specimen.createur", new PropertyModel<String>(specimenModel, "createur")) - .setEnabled(false)); + formView + .add(new TextArea<String>("Specimen.complement", new PropertyModel<String>(specimenModel, "complement"))); + // Créateur en lecture seule + formView.add(new TextField<String>("Specimen.createur", new PropertyModel<String>(specimenModel, "createur")) + .setEnabled(false)); - // champs dépôt - formView.add(new TextField<String>("Specimen.numDepot", new PropertyModel<String>(specimenModel, "numDepot"))); - formView.add(new DateTextField("Specimen.dateDepot", new PropertyModel<Date>(specimenModel, "dateDepot")) - .add(new DatePicker())); - formView.add(new AutoCompleteTextFieldString("Specimen.lieuDepot", new PropertyModel<String>(specimenModel, - "lieuDepot"), lieuxDepot, ComparisonMode.CONTAINS)); + // champs dépôt + formView.add(new TextField<String>("Specimen.numDepot", new PropertyModel<String>(specimenModel, "numDepot"))); + formView.add(new DateTextField("Specimen.dateDepot", new PropertyModel<Date>(specimenModel, "dateDepot")) + .add(new DatePicker())); + formView.add(new AutoCompleteTextFieldString("Specimen.lieuDepot", new PropertyModel<String>(specimenModel, + "lieuDepot"), lieuxDepot, ComparisonMode.CONTAINS)); - // Action : création du specimen - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - specimenService.createSpecimen(specimenModel.getObject()); - } + // Action : création du specimen + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + specimenService.createSpecimen(specimenModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : mise à jour du specimen - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - specimenService.updateSpecimen(specimenModel.getObject()); - } + // Action : mise à jour du specimen + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + specimenService.updateSpecimen(specimenModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode - && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() - .getUtilisateur())); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode + && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateButton); - // Action : suppression du specimen - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - specimenService.deleteSpecimen(specimenModel.getObject()); - } + // Action : suppression du specimen + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + specimenService.deleteSpecimen(specimenModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode - && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode + && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - add(formView); + add(formView); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Station, Spécimen ou Campagne) - refreshModel(); - super.onBeforeRender(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Station, Spécimen ou Campagne) + refreshModel(); + super.onBeforeRender(); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection de nouveau vers l'écran de saisie d'un nouveau spécimen - Specimen nextSpecimen = new Specimen(); - nextSpecimen.setTypeOrganisme(specimenModel.getObject().getTypeOrganisme()); - nextSpecimen.setEmbranchement(specimenModel.getObject().getEmbranchement()); - nextSpecimen.setIdentificateur(specimenModel.getObject().getIdentificateur()); - nextSpecimen.setStation(specimenModel.getObject().getStation()); - nextSpecimen.setLieuDepot(specimenModel.getObject().getLieuDepot()); + if (multipleEntry) { + // Redirection de nouveau vers l'écran de saisie d'un nouveau spécimen + Specimen nextSpecimen = new Specimen(); + nextSpecimen.setTypeOrganisme(specimenModel.getObject().getTypeOrganisme()); + nextSpecimen.setEmbranchement(specimenModel.getObject().getEmbranchement()); + nextSpecimen.setIdentificateur(specimenModel.getObject().getIdentificateur()); + nextSpecimen.setStation(specimenModel.getObject().getStation()); + nextSpecimen.setLieuDepot(specimenModel.getObject().getLieuDepot()); - setResponsePage(new ManageSpecimenPage(nextSpecimen, callerPage)); - } else if (callerPage != null) { - // On passe l'id du specimen associée à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Specimen.class.getSimpleName(), specimenModel.getObject().getIdSpecimen()); - callerPage.responsePage(this); - } + setResponsePage(new ManageSpecimenPage(nextSpecimen, callerPage)); + } else if (callerPage != null) { + // On passe l'id du specimen associée à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Specimen.class.getSimpleName(), specimenModel.getObject().getIdSpecimen()); + callerPage.responsePage(this); + } } /** @@ -389,43 +390,43 @@ */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Personne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(personnes, personneService.listPersonnes()); - try { - Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); - specimenModel.getObject().setIdentificateur(createdPersonne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } - key = Station.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(stations, stationService.listStations(getSession().getUtilisateur())); - try { - Station createdStation = stationService.loadStation(getPageParameters().get(key).toInt()); - specimenModel.getObject().setStation(createdStation); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Personne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(personnes, personneService.listPersonnes()); + try { + Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); + specimenModel.getObject().setIdentificateur(createdPersonne); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } + key = Station.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(stations, stationService.listStations(getSession().getUtilisateur())); + try { + Station createdStation = stationService.loadStation(getPageParameters().get(key).toInt()); + specimenModel.getObject().setStation(createdStation); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(specimenModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(specimenModel.getObject(), getSession().getLocale())); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ReadSpecimenPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ReadSpecimenPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/specimen/ReadSpecimenPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -78,121 +78,121 @@ * @param callerPage Page appelante */ public ReadSpecimenPage(Integer idSpecimen, final CallerPage callerPage) { - super(ReadSpecimenPage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + super(ReadSpecimenPage.class); + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation du modèle - specimenModel = new GenericLoadableDetachableModel<Specimen>(Specimen.class, idSpecimen); + // Initialisation du modèle + specimenModel = new GenericLoadableDetachableModel<Specimen>(Specimen.class, idSpecimen); - boolean createMode = idSpecimen == null; - if (createMode) { - specimenModel.getObject().setCreateur(getSession().getUtilisateur()); - } - final Specimen specimen = specimenModel.getObject(); + boolean createMode = idSpecimen == null; + if (createMode) { + specimenModel.getObject().setCreateur(getSession().getUtilisateur()); + } + final Specimen specimen = specimenModel.getObject(); - // Mapping - add(new Label("Specimen.ref", new PropertyModel<String>(specimenModel, "ref")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.embranchement", new PropertyModel<String>(specimenModel, "embranchement")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.famille", new PropertyModel<String>(specimenModel, "famille")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.genre", new PropertyModel<String>(specimenModel, "genre")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.espece", new PropertyModel<String>(specimenModel, "espece")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.sousEspece", new PropertyModel<String>(specimenModel, "sousEspece")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.variete", new PropertyModel<String>(specimenModel, "variete")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.typeOrganisme", new DisplayEnumPropertyModel(specimenModel, "typeOrganisme", this))); + // Mapping + add(new Label("Specimen.ref", new PropertyModel<String>(specimenModel, "ref")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.embranchement", new PropertyModel<String>(specimenModel, "embranchement")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.famille", new PropertyModel<String>(specimenModel, "famille")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.genre", new PropertyModel<String>(specimenModel, "genre")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.espece", new PropertyModel<String>(specimenModel, "espece")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.sousEspece", new PropertyModel<String>(specimenModel, "sousEspece")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.variete", new PropertyModel<String>(specimenModel, "variete")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.typeOrganisme", new DisplayEnumPropertyModel(specimenModel, "typeOrganisme", this))); - add(new PropertyLabelLinkPanel<Personne>("Specimen.identificateur", new PropertyModel<Personne>(specimenModel, - "identificateur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Specimen.identificateur", new PropertyModel<Personne>(specimenModel, + "identificateur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - add(new PropertyLabelLinkPanel<Station>("Specimen.station", - new PropertyModel<Station>(specimenModel, "station"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); - } - }.add(new ReplaceEmptyLabelBehavior())); + add(new PropertyLabelLinkPanel<Station>("Specimen.station", + new PropertyModel<Station>(specimenModel, "station"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadStationPage(getModelObject().getIdStation(), currentPage)); + } + }.add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("Specimen.complement", new PropertyModel<String>(specimenModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("Specimen.complement", new PropertyModel<String>(specimenModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Specimen.createur", new PropertyModel<Personne>(specimenModel, - "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("Specimen.createur", new PropertyModel<Personne>(specimenModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - // champs dépôt - add(new Label("Specimen.numDepot", new PropertyModel<String>(specimenModel, "numDepot")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.dateDepot", new PropertyModel<Date>(specimenModel, "dateDepot")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Specimen.lieuDepot", new PropertyModel<String>(specimenModel, "lieuDepot")) - .add(new ReplaceEmptyLabelBehavior())); + // champs dépôt + add(new Label("Specimen.numDepot", new PropertyModel<String>(specimenModel, "numDepot")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.dateDepot", new PropertyModel<Date>(specimenModel, "dateDepot")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Specimen.lieuDepot", new PropertyModel<String>(specimenModel, "lieuDepot")) + .add(new ReplaceEmptyLabelBehavior())); - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour - Link<Specimen> updateLink = new Link<Specimen>(getResource() + ".Specimen.Update", - new Model<Specimen>(specimen)) { - @Override - public void onClick() { - setResponsePage(new ManageSpecimenPage(getModelObject().getIdSpecimen(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(specimenService.updateOrdeleteSpecimenEnabled(specimen, getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour + Link<Specimen> updateLink = new Link<Specimen>(getResource() + ".Specimen.Update", + new Model<Specimen>(specimen)) { + @Override + public void onClick() { + setResponsePage(new ManageSpecimenPage(getModelObject().getIdSpecimen(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(specimenService.updateOrdeleteSpecimenEnabled(specimen, getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : suppression du specimen - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageSpecimenPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - specimenService.deleteSpecimen(specimenModel.getObject()); - } + // Action : suppression du specimen + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageSpecimenPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + specimenService.deleteSpecimen(specimenModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ManageSpecimenPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(!createMode - && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ManageSpecimenPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(!createMode + && specimenService.updateOrdeleteSpecimenEnabled(specimenModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - // Action : retour - formView.add(new Link<Void>(getResource() + ".Specimen.Back") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + // Action : retour + formView.add(new Link<Void>(getResource() + ".Specimen.Back") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - add(formView); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ListStationsPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ListStationsPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ListStationsPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,7 +58,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ListStationsPage extends TemplatePage { /** Service : station */ @@ -69,30 +69,30 @@ * Constructeur */ public ListStationsPage() { - super(ListStationsPage.class); + super(ListStationsPage.class); - final CallerPage currentPage = new CallerPage(ListStationsPage.class); + final CallerPage currentPage = new CallerPage(ListStationsPage.class); - // Lien pour ajouter une nouvelle station - add(new Link<Station>(getResource() + ".NewStation") { - @Override - public void onClick() { - setResponsePage(new ManageStationPage(currentPage, true)); - } - }); + // Lien pour ajouter une nouvelle station + add(new Link<Station>(getResource() + ".NewStation") { + @Override + public void onClick() { + setResponsePage(new ManageStationPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer stationsRefresh = new WebMarkupContainer(getResource() + ".Stations.Refresh"); - stationsRefresh.setOutputMarkupId(true); - add(stationsRefresh); - - // Liste des stations - final List<Station> stations = stationService.listStations(getSession().getUtilisateur()); - DataTable<Station, String> stationsDataTable = initStationsDataTable(this, - "ListStationsPage.Stations", currentPage, stations, stationService); - stationsRefresh.add(stationsDataTable); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer stationsRefresh = new WebMarkupContainer(getResource() + ".Stations.Refresh"); + stationsRefresh.setOutputMarkupId(true); + add(stationsRefresh); + // Liste des stations + final List<Station> stations = stationService.listStations(getSession().getUtilisateur()); + DataTable<Station, String> stationsDataTable = initStationsDataTable(this, "ListStationsPage.Stations", + currentPage, stations, stationService); + stationsRefresh.add(stationsDataTable); + } /** @@ -108,67 +108,71 @@ * @return data table component */ public static DataTable<Station, String> initStationsDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<Station> stations, final StationService stationService) { + final String componentId, final CallerPage callerPage, List<Station> stations, + final StationService stationService) { - LoadableDetachableSortableListDataProvider<Station> stationsDataProvider = new LoadableDetachableSortableListDataProvider<Station>( - stations, templatePage.getSession().getLocale()); + LoadableDetachableSortableListDataProvider<Station> stationsDataProvider = new LoadableDetachableSortableListDataProvider<Station>( + stations, templatePage.getSession().getLocale()); - List<IColumn<Station, String>> columns = new ArrayList<IColumn<Station, String>>(); + List<IColumn<Station, String>> columns = new ArrayList<IColumn<Station, String>>(); - columns.add(new LinkableImagePropertyColumn<Station, String>("images/read.png", templatePage.getString("Read"), templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { - templatePage.setResponsePage(new ReadStationPage(model.getObject().getIdStation(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<Station, String>("images/read.png", templatePage.getString("Read"), + templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { + templatePage.setResponsePage(new ReadStationPage(model.getObject().getIdStation(), callerPage)); + } + }); - columns.add(new LinkPropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.nom")), "nom", "nom", - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { - templatePage.setResponsePage(new ReadStationPage(model.getObject().getIdStation(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.nom")), + "nom", "nom", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { + templatePage.setResponsePage(new ReadStationPage(model.getObject().getIdStation(), callerPage)); + } + }); - columns.add(new MapValuePropertyColumn<Station, String, String>(new Model<String>(templatePage.getString("Station.codePays")), - "codePays", "codePays", WebContext.COUNTRIES.get(templatePage.getSession().getLocale()))); + columns.add(new MapValuePropertyColumn<Station, String, String>(new Model<String>(templatePage + .getString("Station.codePays")), "codePays", "codePays", WebContext.COUNTRIES.get(templatePage + .getSession().getLocale()))); - columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.localite")), "localite", - "localite")); + columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.localite")), + "localite", "localite")); - columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.latitude")), "latitude", - "latitude")); + columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.latitude")), + "latitude", "latitude")); - columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.longitude")), "longitude", - "longitude")); + columns.add(new PropertyColumn<Station, String>(new Model<String>(templatePage.getString("Station.longitude")), + "longitude", "longitude")); - columns.add(new LinkableImagePropertyColumn<Station, String>("images/edit.png", templatePage.getString("Update"), - templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + columns.add(new LinkableImagePropertyColumn<Station, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - if (stationService.updateOrdeleteStationEnabled(model.getObject(), templatePage.getSession().getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + if (stationService.updateOrdeleteStationEnabled(model.getObject(), templatePage.getSession() + .getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { - templatePage.setResponsePage(new ManageStationPage(model.getObject().getIdStation(), callerPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<Station>> item, String componentId, IModel<Station> model) { + templatePage.setResponsePage(new ManageStationPage(model.getObject().getIdStation(), callerPage)); + } + }); - final DataTable<Station, String> stationsDataTable = new AjaxFallbackDefaultDataTable<Station, String>( - componentId, columns, stationsDataProvider, WebContext.ROWS_PER_PAGE); - stationsDataTable.addBottomToolbar(new TableExportToolbar(stationsDataTable, "stations", templatePage.getSession().getLocale())); - return stationsDataTable; + final DataTable<Station, String> stationsDataTable = new AjaxFallbackDefaultDataTable<Station, String>( + componentId, columns, stationsDataProvider, WebContext.ROWS_PER_PAGE); + stationsDataTable.addBottomToolbar(new TableExportToolbar(stationsDataTable, "stations", templatePage + .getSession().getLocale())); + return stationsDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ManageStationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ManageStationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ManageStationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -66,7 +66,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManageStationPage extends TemplatePage { /** Action : create */ @@ -107,7 +107,7 @@ * @param multipleEntry Saisie de stations multiples */ public ManageStationPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -116,7 +116,7 @@ * @param callerPage Page appelante */ public ManageStationPage(Integer idStation, CallerPage callerPage) { - this(idStation, null, callerPage, false); + this(idStation, null, callerPage, false); } /** @@ -125,7 +125,7 @@ * @param callerPage Page appelante */ public ManageStationPage(Station station, CallerPage callerPage) { - this(null, station, callerPage, true); + this(null, station, callerPage, true); } /** @@ -138,266 +138,266 @@ * @param multipleEntry Saisie de stations multiples */ private ManageStationPage(Integer idStation, Station station, final CallerPage callerPage, - final boolean multipleEntry) { - super(ManageStationPage.class); - assert idStation == null || station == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + final boolean multipleEntry) { + super(ManageStationPage.class); + assert idStation == null || station == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - // Initialisation du modèle - manageStationModel = new Model<ManageStationModel>(new ManageStationModel()); - try { - stationModel = new Model<Station>(idStation == null && station == null ? new Station() - : station != null ? station : stationService.loadStation(idStation)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - boolean createMode = idStation == null; - if (createMode) { - stationModel.getObject().setCreateur(getSession().getUtilisateur()); - if (station != null) { - // cas où édition d'une station à partir de champs préremplies de l'ancienne station - // on met à jour le modèle intermédiaire pour les coordonnées (pas les minutes de longitude et latitude - // par contre) - manageStationModel.getObject().setLatitudeDegrees( - CoordTools.latitudeDegrees(stationModel.getObject().getLatitude())); - manageStationModel.getObject().setLatitudeOrientation( - CoordTools.latitudeOrientation(stationModel.getObject().getLatitude())); - manageStationModel.getObject().setLongitudeDegrees( - CoordTools.longitudeDegrees(stationModel.getObject().getLongitude())); - manageStationModel.getObject().setLongitudeOrientation( - CoordTools.longitudeOrientation(stationModel.getObject().getLongitude())); - } - } else { - // mode édition, mise à jour du modèle intermédiaire pour les coordonnées - manageStationModel.getObject().setLatitudeDegrees( - CoordTools.latitudeDegrees(stationModel.getObject().getLatitude())); - manageStationModel.getObject().setLatitudeMinutes( - CoordTools.latitudeMinutes(stationModel.getObject().getLatitude())); - manageStationModel.getObject().setLatitudeOrientation( - CoordTools.latitudeOrientation(stationModel.getObject().getLatitude())); - manageStationModel.getObject().setLongitudeDegrees( - CoordTools.longitudeDegrees(stationModel.getObject().getLongitude())); - manageStationModel.getObject().setLongitudeMinutes( - CoordTools.longitudeMinutes(stationModel.getObject().getLongitude())); - manageStationModel.getObject().setLongitudeOrientation( - CoordTools.longitudeOrientation(stationModel.getObject().getLongitude())); - } + // Initialisation du modèle + manageStationModel = new Model<ManageStationModel>(new ManageStationModel()); + try { + stationModel = new Model<Station>(idStation == null && station == null ? new Station() + : station != null ? station : stationService.loadStation(idStation)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + boolean createMode = idStation == null; + if (createMode) { + stationModel.getObject().setCreateur(getSession().getUtilisateur()); + if (station != null) { + // cas où édition d'une station à partir de champs préremplies de l'ancienne station + // on met à jour le modèle intermédiaire pour les coordonnées (pas les minutes de longitude et latitude + // par contre) + manageStationModel.getObject().setLatitudeDegrees( + CoordTools.latitudeDegrees(stationModel.getObject().getLatitude())); + manageStationModel.getObject().setLatitudeOrientation( + CoordTools.latitudeOrientation(stationModel.getObject().getLatitude())); + manageStationModel.getObject().setLongitudeDegrees( + CoordTools.longitudeDegrees(stationModel.getObject().getLongitude())); + manageStationModel.getObject().setLongitudeOrientation( + CoordTools.longitudeOrientation(stationModel.getObject().getLongitude())); + } + } else { + // mode édition, mise à jour du modèle intermédiaire pour les coordonnées + manageStationModel.getObject().setLatitudeDegrees( + CoordTools.latitudeDegrees(stationModel.getObject().getLatitude())); + manageStationModel.getObject().setLatitudeMinutes( + CoordTools.latitudeMinutes(stationModel.getObject().getLatitude())); + manageStationModel.getObject().setLatitudeOrientation( + CoordTools.latitudeOrientation(stationModel.getObject().getLatitude())); + manageStationModel.getObject().setLongitudeDegrees( + CoordTools.longitudeDegrees(stationModel.getObject().getLongitude())); + manageStationModel.getObject().setLongitudeMinutes( + CoordTools.longitudeMinutes(stationModel.getObject().getLongitude())); + manageStationModel.getObject().setLongitudeOrientation( + CoordTools.longitudeOrientation(stationModel.getObject().getLongitude())); + } - // Initialisation des listes - List<String> localites = stationService.listStationLocalites(); - final Form<Void> formView = new Form<Void>("Form"); - formView.add(new TextField<String>("Station.nom", new PropertyModel<String>(stationModel, "nom"))); - formView.add(new DropDownChoice<String>("Station.codePays", - new PropertyModel<String>(stationModel, "codePays"), WebContext.COUNTRY_CODES.get(getSession() - .getLocale()), new MapChoiceRenderer<String, String>(WebContext.COUNTRIES.get(getSession() - .getLocale())))); - formView.add(new AutoCompleteTextFieldString("Station.localite", new PropertyModel<String>(stationModel, - "localite"), localites, ComparisonMode.CONTAINS)); - formView.add(new TextArea<String>("Station.complement", new PropertyModel<String>(stationModel, "complement"))); + // Initialisation des listes + List<String> localites = stationService.listStationLocalites(); + final Form<Void> formView = new Form<Void>("Form"); + formView.add(new TextField<String>("Station.nom", new PropertyModel<String>(stationModel, "nom"))); + formView.add(new DropDownChoice<String>("Station.codePays", + new PropertyModel<String>(stationModel, "codePays"), WebContext.COUNTRY_CODES.get(getSession() + .getLocale()), new MapChoiceRenderer<String, String>(WebContext.COUNTRIES.get(getSession() + .getLocale())))); + formView.add(new AutoCompleteTextFieldString("Station.localite", new PropertyModel<String>(stationModel, + "localite"), localites, ComparisonMode.CONTAINS)); + formView.add(new TextArea<String>("Station.complement", new PropertyModel<String>(stationModel, "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("Station.createur", new PropertyModel<String>(stationModel, "createur")) - .setEnabled(false)); + // Créateur en lecture seule + formView.add(new TextField<String>("Station.createur", new PropertyModel<String>(stationModel, "createur")) + .setEnabled(false)); - formView.add(new TextField<Integer>("ManageStationModel.latitudeDegrees", new PropertyModel<Integer>( - manageStationModel, "latitudeDegrees"))); - formView.add(new Label("Coordonnate.degrees.latitude", String.valueOf(CoordTools.DEGREES))); - formView.add(new TextField<BigDecimal>("ManageStationModel.latitudeMinutes", new PropertyModel<BigDecimal>( - manageStationModel, "latitudeMinutes"))); - formView.add(new Label("Coordonnate.minutes.latitude", String.valueOf(CoordTools.MINUTES))); - formView.add(new DropDownChoice<Character>("ManageStationModel.latitudeOrientation", - new PropertyModel<Character>(manageStationModel, "latitudeOrientation"), Arrays - .asList(CoordTools.LATITUDE_ORIENTATIONS))); - formView.add(new TextField<Integer>("ManageStationModel.longitudeDegrees", new PropertyModel<Integer>( - manageStationModel, "longitudeDegrees"))); - formView.add(new Label("Coordonnate.degrees.longitude", String.valueOf(CoordTools.DEGREES))); - formView.add(new TextField<BigDecimal>("ManageStationModel.longitudeMinutes", new PropertyModel<BigDecimal>( - manageStationModel, "longitudeMinutes"))); - formView.add(new Label("Coordonnate.minutes.longitude", String.valueOf(CoordTools.MINUTES))); - formView.add(new DropDownChoice<Character>("ManageStationModel.longitudeOrientation", - new PropertyModel<Character>(manageStationModel, "longitudeOrientation"), Arrays - .asList(CoordTools.LONGITUDE_ORIENTATIONS))); + formView.add(new TextField<Integer>("ManageStationModel.latitudeDegrees", new PropertyModel<Integer>( + manageStationModel, "latitudeDegrees"))); + formView.add(new Label("Coordonnate.degrees.latitude", String.valueOf(CoordTools.DEGREES))); + formView.add(new TextField<BigDecimal>("ManageStationModel.latitudeMinutes", new PropertyModel<BigDecimal>( + manageStationModel, "latitudeMinutes"))); + formView.add(new Label("Coordonnate.minutes.latitude", String.valueOf(CoordTools.MINUTES))); + formView.add(new DropDownChoice<Character>("ManageStationModel.latitudeOrientation", + new PropertyModel<Character>(manageStationModel, "latitudeOrientation"), Arrays + .asList(CoordTools.LATITUDE_ORIENTATIONS))); + formView.add(new TextField<Integer>("ManageStationModel.longitudeDegrees", new PropertyModel<Integer>( + manageStationModel, "longitudeDegrees"))); + formView.add(new Label("Coordonnate.degrees.longitude", String.valueOf(CoordTools.DEGREES))); + formView.add(new TextField<BigDecimal>("ManageStationModel.longitudeMinutes", new PropertyModel<BigDecimal>( + manageStationModel, "longitudeMinutes"))); + formView.add(new Label("Coordonnate.minutes.longitude", String.valueOf(CoordTools.MINUTES))); + formView.add(new DropDownChoice<Character>("ManageStationModel.longitudeOrientation", + new PropertyModel<Character>(manageStationModel, "longitudeOrientation"), Arrays + .asList(CoordTools.LONGITUDE_ORIENTATIONS))); - formView.add(new DropDownChoice<Integer>("Station.referentiel", new PropertyModel<Integer>(stationModel, - "referentiel"), WebContext.REFERENTIEL_CODES, new MapChoiceRenderer<Integer, String>( - DataContext.REFERENTIELS))); + formView.add(new DropDownChoice<Integer>("Station.referentiel", new PropertyModel<Integer>(stationModel, + "referentiel"), WebContext.REFERENTIEL_CODES, new MapChoiceRenderer<Integer, String>( + DataContext.REFERENTIELS))); - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - if (manageStationModel.getObject().getLatitudeDegrees() == null) { - stationModel.getObject().setReferentiel(null); - } - stationService.createStation(stationModel.getObject()); - } + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + if (manageStationModel.getObject().getLatitudeDegrees() == null) { + stationModel.getObject().setReferentiel(null); + } + stationService.createStation(stationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - if (manageStationModel.getObject().getLatitudeDegrees() == null) { - stationModel.getObject().setReferentiel(null); - } - stationService.updateStation(stationModel.getObject()); - } + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + if (manageStationModel.getObject().getLatitudeDegrees() == null) { + stationModel.getObject().setReferentiel(null); + } + stationService.updateStation(stationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton - .setVisibilityAllowed(!createMode - && stationService.updateOrdeleteStationEnabled(stationModel.getObject(), getSession() - .getUtilisateur())); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton + .setVisibilityAllowed(!createMode + && stationService.updateOrdeleteStationEnabled(stationModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateButton); - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - stationService.deleteStation(stationModel.getObject()); - } + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + stationService.deleteStation(stationModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - redirect(); - } - }); - deleteButton - .setVisibilityAllowed(!createMode - && stationService.updateOrdeleteStationEnabled(stationModel.getObject(), getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - deleteButton.setDefaultFormProcessing(false); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + redirect(); + } + }); + deleteButton + .setVisibilityAllowed(!createMode + && stationService.updateOrdeleteStationEnabled(stationModel.getObject(), getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + deleteButton.setDefaultFormProcessing(false); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) this.getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) this.getPage()); + } + }); - if (createMode) { - // Données par défaut du modèle - if (stationModel.getObject().getCodePays() == null) { - stationModel.getObject().setCodePays( - WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); - } - if (stationModel.getObject().getReferentiel() == null) { - stationModel.getObject().setReferentiel(WebContext.REFERENTIEL_CODES.get(0)); - } - // Données par défaut du modèle intermédiaire - if (manageStationModel.getObject().getLatitudeOrientation() == null) { - manageStationModel.getObject().setLatitudeOrientation(CoordTools.LATITUDE_ORIENTATIONS[1]); - } - if (manageStationModel.getObject().getLongitudeOrientation() == null) { - manageStationModel.getObject().setLongitudeOrientation(CoordTools.LONGITUDE_ORIENTATIONS[0]); - } - } + if (createMode) { + // Données par défaut du modèle + if (stationModel.getObject().getCodePays() == null) { + stationModel.getObject().setCodePays( + WebContext.COUNTRIES.get(getSession().getLocale()).entrySet().iterator().next().getKey()); + } + if (stationModel.getObject().getReferentiel() == null) { + stationModel.getObject().setReferentiel(WebContext.REFERENTIEL_CODES.get(0)); + } + // Données par défaut du modèle intermédiaire + if (manageStationModel.getObject().getLatitudeOrientation() == null) { + manageStationModel.getObject().setLatitudeOrientation(CoordTools.LATITUDE_ORIENTATIONS[1]); + } + if (manageStationModel.getObject().getLongitudeOrientation() == null) { + manageStationModel.getObject().setLongitudeOrientation(CoordTools.LONGITUDE_ORIENTATIONS[0]); + } + } - add(formView); + add(formView); } /** * Page redirection. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection vers l'écran de saisie d'une nouvelle station, en fournissant déjà quelques données - Station nextStation = new Station(); - nextStation.setCodePays(stationModel.getObject().getCodePays()); - if (manageStationModel.getObject().getLatitudeDegrees() != null) { - nextStation.setLatitude(stationModel.getObject().getLatitude()); - nextStation.setLongitude(stationModel.getObject().getLongitude()); - nextStation.setReferentiel(stationModel.getObject().getReferentiel()); - } - setResponsePage(new ManageStationPage(nextStation, callerPage)); - } else { - // On passe l'id de la station associée à cette page, en paramètre de la prochaine page, pour lui permettre - // de - // l'exploiter si besoin - callerPage.addPageParameter(Station.class.getSimpleName(), stationModel.getObject().getIdStation()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection vers l'écran de saisie d'une nouvelle station, en fournissant déjà quelques données + Station nextStation = new Station(); + nextStation.setCodePays(stationModel.getObject().getCodePays()); + if (manageStationModel.getObject().getLatitudeDegrees() != null) { + nextStation.setLatitude(stationModel.getObject().getLatitude()); + nextStation.setLongitude(stationModel.getObject().getLongitude()); + nextStation.setReferentiel(stationModel.getObject().getReferentiel()); + } + setResponsePage(new ManageStationPage(nextStation, callerPage)); + } else { + // On passe l'id de la station associée à cette page, en paramètre de la prochaine page, pour lui permettre + // de + // l'exploiter si besoin + callerPage.addPageParameter(Station.class.getSimpleName(), stationModel.getObject().getIdStation()); + callerPage.responsePage(this); + } } /** * Validate the campagne model (for update & create) */ private void validateModel() { - if (stationModel.getObject().getCreateur() == null) { - stationModel.getObject().setCreateur(getSession().getUtilisateur()); - } + if (stationModel.getObject().getCreateur() == null) { + stationModel.getObject().setCreateur(getSession().getUtilisateur()); + } - List<String> referentielErrors = validator.validate(stationModel.getObject(), getSession().getLocale(), - "referentiel"); - List<String> coordErrors = validator.validate(manageStationModel.getObject(), getSession().getLocale()); + List<String> referentielErrors = validator.validate(stationModel.getObject(), getSession().getLocale(), + "referentiel"); + List<String> coordErrors = validator.validate(manageStationModel.getObject(), getSession().getLocale()); - // On ne considère les coordonnées que si au moins un des champs a été renseigné - if (manageStationModel.getObject().getLatitudeDegrees() != null - || manageStationModel.getObject().getLatitudeMinutes() != null - || manageStationModel.getObject().getLongitudeDegrees() != null - || manageStationModel.getObject().getLongitudeMinutes() != null) { - // Tous les champs doivent avoir été renseignées pour que les coordonnées soient valides - if (manageStationModel.getObject().getLatitudeDegrees() != null - && manageStationModel.getObject().getLatitudeMinutes() != null - && manageStationModel.getObject().getLatitudeOrientation() != null - && manageStationModel.getObject().getLongitudeDegrees() != null - && manageStationModel.getObject().getLongitudeMinutes() != null - && manageStationModel.getObject().getLongitudeOrientation() != null - && stationModel.getObject().getReferentiel() != null) { - // Construction des coordonnées - if (referentielErrors.isEmpty() && coordErrors.isEmpty()) { - stationModel.getObject().setLatitude( - CoordTools.latitude(manageStationModel.getObject().getLatitudeDegrees(), manageStationModel - .getObject().getLatitudeMinutes(), manageStationModel.getObject() - .getLatitudeOrientation())); - stationModel.getObject().setLongitude( - CoordTools.longitude(manageStationModel.getObject().getLongitudeDegrees(), - manageStationModel.getObject().getLongitudeMinutes(), manageStationModel - .getObject().getLongitudeOrientation())); - } - } else { - getPage().error(getString("Station.coordonnees.KO")); - } - } else { - // si tous les champs sont vide, on met à null les coordonnées - if (manageStationModel.getObject().getLatitudeDegrees() == null - && manageStationModel.getObject().getLatitudeMinutes() == null - && manageStationModel.getObject().getLongitudeDegrees() == null - && manageStationModel.getObject().getLongitudeMinutes() == null) { - stationModel.getObject().setLatitude(null); - stationModel.getObject().setLongitude(null); - } - } + // On ne considère les coordonnées que si au moins un des champs a été renseigné + if (manageStationModel.getObject().getLatitudeDegrees() != null + || manageStationModel.getObject().getLatitudeMinutes() != null + || manageStationModel.getObject().getLongitudeDegrees() != null + || manageStationModel.getObject().getLongitudeMinutes() != null) { + // Tous les champs doivent avoir été renseignées pour que les coordonnées soient valides + if (manageStationModel.getObject().getLatitudeDegrees() != null + && manageStationModel.getObject().getLatitudeMinutes() != null + && manageStationModel.getObject().getLatitudeOrientation() != null + && manageStationModel.getObject().getLongitudeDegrees() != null + && manageStationModel.getObject().getLongitudeMinutes() != null + && manageStationModel.getObject().getLongitudeOrientation() != null + && stationModel.getObject().getReferentiel() != null) { + // Construction des coordonnées + if (referentielErrors.isEmpty() && coordErrors.isEmpty()) { + stationModel.getObject().setLatitude( + CoordTools.latitude(manageStationModel.getObject().getLatitudeDegrees(), manageStationModel + .getObject().getLatitudeMinutes(), manageStationModel.getObject() + .getLatitudeOrientation())); + stationModel.getObject().setLongitude( + CoordTools.longitude(manageStationModel.getObject().getLongitudeDegrees(), + manageStationModel.getObject().getLongitudeMinutes(), manageStationModel + .getObject().getLongitudeOrientation())); + } + } else { + getPage().error(getString("Station.coordonnees.KO")); + } + } else { + // si tous les champs sont vide, on met à null les coordonnées + if (manageStationModel.getObject().getLatitudeDegrees() == null + && manageStationModel.getObject().getLatitudeMinutes() == null + && manageStationModel.getObject().getLongitudeDegrees() == null + && manageStationModel.getObject().getLongitudeMinutes() == null) { + stationModel.getObject().setLatitude(null); + stationModel.getObject().setLongitude(null); + } + } - addValidationErrors(validator.validate(stationModel.getObject(), getSession().getLocale(), "nom", "codePays", - "localite", "complement", "createur", "latitude", "longitude")); - addValidationErrors(referentielErrors); - addValidationErrors(coordErrors); + addValidationErrors(validator.validate(stationModel.getObject(), getSession().getLocale(), "nom", "codePays", + "localite", "complement", "createur", "latitude", "longitude")); + addValidationErrors(referentielErrors); + addValidationErrors(coordErrors); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ReadStationPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ReadStationPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/station/ReadStationPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -76,87 +76,87 @@ * @param callerPage Page appelante */ public ReadStationPage(Integer idStation, CallerPage callerPage) { - super(ReadStationPage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + super(ReadStationPage.class); + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation des modèles - stationModel = new GenericLoadableDetachableModel<Station>(Station.class, idStation); + // Initialisation des modèles + stationModel = new GenericLoadableDetachableModel<Station>(Station.class, idStation); - final Station station = stationModel.getObject(); + final Station station = stationModel.getObject(); - // Mapping des champs du modèle - add(new Label("Station.nom", new PropertyModel<String>(stationModel, "nom")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Station.codePays", new DisplayMapValuePropertyModel<String>(stationModel, "codePays", - WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); - add(new Label("Station.localite", new PropertyModel<String>(stationModel, "localite")) - .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("Station.createur", new PropertyModel<Personne>(stationModel, - "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); - add(new MultiLineLabel("Station.complement", new PropertyModel<String>(stationModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Station.latitude", new PropertyModel<String>(stationModel, "latitude")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Station.longitude", new PropertyModel<String>(stationModel, "longitude")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("Station.referentiel", new DisplayMapValuePropertyModel<Integer>(stationModel, "referentiel", - DataContext.REFERENTIELS)).add(new ReplaceEmptyLabelBehavior())); + // Mapping des champs du modèle + add(new Label("Station.nom", new PropertyModel<String>(stationModel, "nom")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Station.codePays", new DisplayMapValuePropertyModel<String>(stationModel, "codePays", + WebContext.COUNTRIES.get(getSession().getLocale()))).add(new ReplaceEmptyLabelBehavior())); + add(new Label("Station.localite", new PropertyModel<String>(stationModel, "localite")) + .add(new ReplaceEmptyLabelBehavior())); + add(new PropertyLabelLinkPanel<Personne>("Station.createur", new PropertyModel<Personne>(stationModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); + add(new MultiLineLabel("Station.complement", new PropertyModel<String>(stationModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Station.latitude", new PropertyModel<String>(stationModel, "latitude")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Station.longitude", new PropertyModel<String>(stationModel, "longitude")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("Station.referentiel", new DisplayMapValuePropertyModel<Integer>(stationModel, "referentiel", + DataContext.REFERENTIELS)).add(new ReplaceEmptyLabelBehavior())); - // Ajout du formulaire pour les actions - Form<Void> formView = new Form<Void>("Form"); + // Ajout du formulaire pour les actions + Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<Station> updateLink = new Link<Station>(getResource() + ".Station.Update", new Model<Station>(station)) { - @Override - public void onClick() { - setResponsePage(new ManageStationPage(getModelObject().getIdStation(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(stationService.updateOrdeleteStationEnabled(station, getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Station> updateLink = new Link<Station>(getResource() + ".Station.Update", new Model<Station>(station)) { + @Override + public void onClick() { + setResponsePage(new ManageStationPage(getModelObject().getIdStation(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(stationService.updateOrdeleteStationEnabled(station, getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : retour à la page précédente - formView.add(new Link<Void>(getResource() + ".Station.Back") { - @Override - public void onClick() { - redirect(); - } - }); + // Action : retour à la page précédente + formView.add(new Link<Void>(getResource() + ".Station.Back") { + @Override + public void onClick() { + redirect(); + } + }); - // Action : suppression de la station - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageStationPage.class, - new SubmittableButtonEvents() { + // Action : suppression de la station + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageStationPage.class, + new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - stationService.deleteStation(station); - } + @Override + public void onProcess() throws DataConstraintException { + stationService.deleteStation(station); + } - @Override - public void onSuccess() { - successNextPage(ManageStationPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(stationService.updateOrdeleteStationEnabled(station, getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManageStationPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(stationService.updateOrdeleteStationEnabled(station, getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ListTestsBioPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ListTestsBioPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ListTestsBioPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -67,7 +67,7 @@ * Page de consultation des résultats des tests biologiques * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ListTestsBioPage extends TemplatePage { /** Service : test biologique */ @@ -78,28 +78,28 @@ * Constructeur */ public ListTestsBioPage() { - super(ListTestsBioPage.class); + super(ListTestsBioPage.class); - final CallerPage currentPage = new CallerPage(ListTestsBioPage.class); + final CallerPage currentPage = new CallerPage(ListTestsBioPage.class); - add(new Link<Void>("ListTestsBioPage.NewTestBio") { - @Override - public void onClick() { - setResponsePage(new ManageTestBioPage(currentPage, true)); - } - }); + add(new Link<Void>("ListTestsBioPage.NewTestBio") { + @Override + public void onClick() { + setResponsePage(new ManageTestBioPage(currentPage, true)); + } + }); - // On englobe le "DataView" dans un composant neutre que l'on pourra - // rafraichir quand la liste évoluera - final MarkupContainer resTestsBiosRefresh = new WebMarkupContainer("ListTestsBioPage.ResultatsTestsBio.Refresh"); - resTestsBiosRefresh.setOutputMarkupId(true); - add(resTestsBiosRefresh); + // On englobe le "DataView" dans un composant neutre que l'on pourra + // rafraichir quand la liste évoluera + final MarkupContainer resTestsBiosRefresh = new WebMarkupContainer("ListTestsBioPage.ResultatsTestsBio.Refresh"); + resTestsBiosRefresh.setOutputMarkupId(true); + add(resTestsBiosRefresh); - // Liste des résultats de tests biologiques - final List<ResultatTestBio> resTestsBios = testBioService.listResultatsTestBio(getSession().getUtilisateur()); - DataTable<ResultatTestBio, String> resTestsBiosDataTable = initTestsBioDataTable(this, - "ListTestsBioPage.ResultatsTestsBio", currentPage, resTestsBios, testBioService); - resTestsBiosRefresh.add(resTestsBiosDataTable); + // Liste des résultats de tests biologiques + final List<ResultatTestBio> resTestsBios = testBioService.listResultatsTestBio(getSession().getUtilisateur()); + DataTable<ResultatTestBio, String> resTestsBiosDataTable = initTestsBioDataTable(this, + "ListTestsBioPage.ResultatsTestsBio", currentPage, resTestsBios, testBioService); + resTestsBiosRefresh.add(resTestsBiosDataTable); } /** @@ -115,119 +115,127 @@ * @return data table component */ public static DataTable<ResultatTestBio, String> initTestsBioDataTable(final TemplatePage templatePage, - final String componentId, final CallerPage callerPage, - List<ResultatTestBio> resTestsBios, final TestBioService testBioService) { + final String componentId, final CallerPage callerPage, List<ResultatTestBio> resTestsBios, + final TestBioService testBioService) { - LoadableDetachableSortableListDataProvider<ResultatTestBio> resTestBiosDataProvider = new LoadableDetachableSortableListDataProvider<ResultatTestBio>( - resTestsBios, templatePage.getSession().getLocale()); + LoadableDetachableSortableListDataProvider<ResultatTestBio> resTestBiosDataProvider = new LoadableDetachableSortableListDataProvider<ResultatTestBio>( + resTestsBios, templatePage.getSession().getLocale()); - List<IColumn<ResultatTestBio, String>> columns = new ArrayList<IColumn<ResultatTestBio, String>>(); + List<IColumn<ResultatTestBio, String>> columns = new ArrayList<IColumn<ResultatTestBio, String>>(); - columns.add(new LinkableImagePropertyColumn<ResultatTestBio, String>("images/read.png", templatePage.getString("Read"), - templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, - IModel<ResultatTestBio> model) { - templatePage.setResponsePage(new ReadTestBioPage(model.getObject().getTestBio().getIdTestBio(), callerPage)); - } - }); + columns.add(new LinkableImagePropertyColumn<ResultatTestBio, String>("images/read.png", templatePage + .getString("Read"), templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, + IModel<ResultatTestBio> model) { + templatePage.setResponsePage(new ReadTestBioPage(model.getObject().getTestBio().getIdTestBio(), + callerPage)); + } + }); - columns.add(new TextFilteredPropertyColumn<ResultatTestBio, String, String>(new Model<String>( - templatePage.getString("MethodeTestBio.cible2")), "testBio.methode.cible", "testBio.methode.cible")); + columns.add(new TextFilteredPropertyColumn<ResultatTestBio, String, String>(new Model<String>(templatePage + .getString("MethodeTestBio.cible2")), "testBio.methode.cible", "testBio.methode.cible")); - columns.add(new DecimalPropertyColumn<ResultatTestBio, String>(new Model<String>( - templatePage.getString("ResultatTestBio.concMasse2")), "concMasse", "concMasse", DecimalDisplFormat.SMALL, - templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("ResultatTestBio.concMasse2")), "concMasse", "concMasse", DecimalDisplFormat.SMALL, + templatePage.getLocale())); - columns.add(new EnumPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("TestBio.uniteConcMasse2")), - "uniteConcMasse", "uniteConcMasse", templatePage)); + columns.add(new EnumPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("TestBio.uniteConcMasse2")), "uniteConcMasse", "uniteConcMasse", templatePage)); - columns.add(new LinkProduitPropertyColumn<ResultatTestBio, String>(new Model<String>( - templatePage.getString("ResultatTestBio.produit")), "produit", "produit", templatePage) { - @Override - public void onClickIfExtrait(Extrait extrait) { - templatePage.setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), callerPage)); - } + columns.add(new LinkProduitPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("ResultatTestBio.produit")), "produit", "produit", templatePage) { + @Override + public void onClickIfExtrait(Extrait extrait) { + templatePage.setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), + callerPage)); + } - @Override - public void onClickIfFraction(Fraction fraction) { - templatePage.setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), callerPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + templatePage.setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), + callerPage)); + } + }); - columns.add(new DecimalPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("ResultatTestBio.valeur")), - "valeur", "valeur", DecimalDisplFormat.SMALL, templatePage.getLocale())); + columns.add(new DecimalPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("ResultatTestBio.valeur")), "valeur", "valeur", DecimalDisplFormat.SMALL, templatePage + .getLocale())); - columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("MethodeTestBio.uniteResultat2")), - "testBio.methode.uniteResultat", "testBio.methode.uniteResultat")); + columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("MethodeTestBio.uniteResultat2")), "testBio.methode.uniteResultat", + "testBio.methode.uniteResultat")); - columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("Extrait.typeExtrait2")), - "typeExtraitSource", "typeExtraitSource")); + columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("Extrait.typeExtrait2")), "typeExtraitSource", "typeExtraitSource")); - columns.add(new BooleanPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("ResultatTestBio.actif")), - "actif", "actif", templatePage)); + columns.add(new BooleanPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("ResultatTestBio.actif")), "actif", "actif", templatePage)); - columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("Specimen.famille")), - "lotSource.specimenRef.famille", "lotSource.specimenRef.famille")); + columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("Specimen.famille")), "lotSource.specimenRef.famille", "lotSource.specimenRef.famille")); - columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("Specimen.genre")), - "lotSource.specimenRef.genre", "lotSource.specimenRef.genre")); + columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("Specimen.genre")), "lotSource.specimenRef.genre", "lotSource.specimenRef.genre")); - columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("Specimen.espece")), - "lotSource.specimenRef.espece", "lotSource.specimenRef.espece")); + columns.add(new TaxonomyPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("Specimen.espece")), "lotSource.specimenRef.espece", "lotSource.specimenRef.espece")); - columns.add(new MapValuePropertyColumn<ResultatTestBio, String, String>(new Model<String>( - templatePage.getString("Campagne.codePays")), "lotSource.campagne.codePays", "lotSource.campagne.codePays", - WebContext.COUNTRIES.get(templatePage.getSession().getLocale()))); + columns.add(new MapValuePropertyColumn<ResultatTestBio, String, String>(new Model<String>(templatePage + .getString("Campagne.codePays")), "lotSource.campagne.codePays", "lotSource.campagne.codePays", + WebContext.COUNTRIES.get(templatePage.getSession().getLocale()))); - columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("ResultatTestBio.repere")), - "repere", "repere")); + columns.add(new PropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("ResultatTestBio.repere")), "repere", "repere")); - columns.add(new LinkPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage.getString("TestBio.ref")), "testBio.ref", - "testBio.ref", templatePage.getString("Read")) { - @Override - public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, - IModel<ResultatTestBio> model) { - templatePage.setResponsePage(new ReadTestBioPage(model.getObject().getTestBio().getIdTestBio(), callerPage)); - } - }); + columns.add(new LinkPropertyColumn<ResultatTestBio, String>(new Model<String>(templatePage + .getString("TestBio.ref")), "testBio.ref", "testBio.ref", templatePage.getString("Read")) { + @Override + public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, + IModel<ResultatTestBio> model) { + templatePage.setResponsePage(new ReadTestBioPage(model.getObject().getTestBio().getIdTestBio(), + callerPage)); + } + }); - columns.add(new LinkableImagePropertyColumn<ResultatTestBio, String>("images/edit.png", templatePage.getString("Update"), - templatePage.getString("Update")) { - // pas de lien d'édition si l'utilisateur n'a pas les droits - @Override - public void populateItem(Item<ICellPopulator<ResultatTestBio>> item, String componentId, - IModel<ResultatTestBio> model) { - if (testBioService.updateOrdeleteTestBioEnabled(model.getObject().getTestBio(), templatePage.getSession() - .getUtilisateur())) { - item.add(new LinkableImagePanel(item, componentId, model)); - } else { - // label vide - item.add(new Label(componentId)); - } - } + columns.add(new LinkableImagePropertyColumn<ResultatTestBio, String>("images/edit.png", templatePage + .getString("Update"), templatePage.getString("Update")) { + // pas de lien d'édition si l'utilisateur n'a pas les droits + @Override + public void populateItem(Item<ICellPopulator<ResultatTestBio>> item, String componentId, + IModel<ResultatTestBio> model) { + if (testBioService.updateOrdeleteTestBioEnabled(model.getObject().getTestBio(), templatePage + .getSession().getUtilisateur())) { + item.add(new LinkableImagePanel(item, componentId, model)); + } else { + // label vide + item.add(new Label(componentId)); + } + } - @Override - public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, - IModel<ResultatTestBio> model) { - templatePage.setResponsePage(new ManageTestBioPage(model.getObject().getTestBio().getIdTestBio(), callerPage)); - } - }); + @Override + public void onClick(Item<ICellPopulator<ResultatTestBio>> item, String componentId, + IModel<ResultatTestBio> model) { + templatePage.setResponsePage(new ManageTestBioPage(model.getObject().getTestBio().getIdTestBio(), + callerPage)); + } + }); - final DataTable<ResultatTestBio, String> resTestBiosDataTable = new AjaxFallbackDefaultDataTable<ResultatTestBio, String>( - componentId, columns, resTestBiosDataProvider, WebContext.ROWS_PER_PAGE); - resTestBiosDataTable.addBottomToolbar(new TableExportToolbar(resTestBiosDataTable, "testsbio", templatePage.getSession().getLocale())); - // DRAFT FOR FILTER TABLE - // resTestBiosDataTable.addTopToolbar(new NavigationToolbar(resTestBiosDataTable)); - // resTestBiosDataTable.addTopToolbar(new HeadersToolbar(resTestBiosDataTable, resTestBiosDataProvider)); + final DataTable<ResultatTestBio, String> resTestBiosDataTable = new AjaxFallbackDefaultDataTable<ResultatTestBio, String>( + componentId, columns, resTestBiosDataProvider, WebContext.ROWS_PER_PAGE); + resTestBiosDataTable.addBottomToolbar(new TableExportToolbar(resTestBiosDataTable, "testsbio", templatePage + .getSession().getLocale())); + // DRAFT FOR FILTER TABLE + // resTestBiosDataTable.addTopToolbar(new NavigationToolbar(resTestBiosDataTable)); + // resTestBiosDataTable.addTopToolbar(new HeadersToolbar(resTestBiosDataTable, resTestBiosDataProvider)); - // create the form used to contain all filter components - /* - * final FilterForm filterForm = new FilterForm("filter-form", resTestBiosDataProvider) { private static final - * long serialVersionUID = 1L; - * @Override protected void onSubmit() { resTestBiosDataTable.setCurrentPage(0); } }; resTestBiosDataTable - * .addTopToolbar(new FilterToolbar(resTestBiosDataTable, filterForm, resTestBiosDataProvider)); - */ - return resTestBiosDataTable; + // create the form used to contain all filter components + /* + * final FilterForm filterForm = new FilterForm("filter-form", resTestBiosDataProvider) { private static final + * long serialVersionUID = 1L; + * @Override protected void onSubmit() { resTestBiosDataTable.setCurrentPage(0); } }; resTestBiosDataTable + * .addTopToolbar(new FilterToolbar(resTestBiosDataTable, filterForm, resTestBiosDataProvider)); + */ + return resTestBiosDataTable; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ManageTestBioPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ManageTestBioPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ManageTestBioPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -103,7 +103,7 @@ * Page for adding/update/delete a new "Test biologique" * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN, AuthRole.USER }) +@AuthRoles( { AuthRole.ADMIN, AuthRole.USER }) public final class ManageTestBioPage extends TemplatePage { /** Logger */ @@ -194,7 +194,7 @@ * @param multipleEntry Saisie multiple */ public ManageTestBioPage(CallerPage callerPage, boolean multipleEntry) { - this(null, null, callerPage, multipleEntry); + this(null, null, callerPage, multipleEntry); } /** @@ -203,7 +203,7 @@ * @param callerPage Page appelante */ public ManageTestBioPage(Integer idManip, CallerPage callerPage) { - this(idManip, null, callerPage, false); + this(idManip, null, callerPage, false); } /** @@ -212,7 +212,7 @@ * @param callerPage Page appelante */ public ManageTestBioPage(TestBio manip, CallerPage callerPage) { - this(null, manip, callerPage, true); + this(null, manip, callerPage, true); } /** @@ -225,126 +225,126 @@ * @param multipleEntry Saisie multiple */ private ManageTestBioPage(Integer idManip, TestBio manip, final CallerPage callerPage, boolean multipleEntry) { - super(ManageTestBioPage.class); - assert idManip == null || manip == null; - this.callerPage = callerPage; - this.multipleEntry = multipleEntry; + super(ManageTestBioPage.class); + assert idManip == null || manip == null; + this.callerPage = callerPage; + this.multipleEntry = multipleEntry; - newResultatModel = new Model<ResultatTestBio>(new ResultatTestBio()); + newResultatModel = new Model<ResultatTestBio>(new ResultatTestBio()); - // Initialisation du modèle - try { - testBioModel = new Model<TestBio>(idManip == null && manip == null ? new TestBio() : manip != null ? manip - : testBioService.loadTestBio(idManip)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - boolean createMode = idManip == null; - if (createMode) { - testBioModel.getObject().setCreateur(getSession().getUtilisateur()); - } + // Initialisation du modèle + try { + testBioModel = new Model<TestBio>(idManip == null && manip == null ? new TestBio() : manip != null ? manip + : testBioService.loadTestBio(idManip)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + boolean createMode = idManip == null; + if (createMode) { + testBioModel.getObject().setCreateur(getSession().getUtilisateur()); + } - // Initialisation des listes (pour le dropDownChoice) - personnes = personneService.listPersonnes(); - methodes = testBioService.listMethodesTestBio(); - produits = produitService.listProduits((Utilisateur) getSession().getUtilisateur()); - erreurs = testBioService.listErreursTestBio(); + // Initialisation des listes (pour le dropDownChoice) + personnes = personneService.listPersonnes(); + methodes = testBioService.listMethodesTestBio(); + produits = produitService.listProduits((Utilisateur) getSession().getUtilisateur()); + erreurs = testBioService.listErreursTestBio(); - if (manip != null) { - // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que - // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas - // l'égalité entre les objets) - testBioModel.getObject().setManipulateur( - CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, testBioModel.getObject() - .getManipulateur().getIdPersonne())); - testBioModel.getObject().setMethode( - CollectionTools.findWithValue(methodes, "idMethodeTest", AccessType.GETTER, testBioModel - .getObject().getMethode().getIdMethodeTest())); - } + if (manip != null) { + // qd saisie multiple avec préremplissage, hack nécessaire afin d'avoir dans le model le même objet que + // celui de la liste de choix (sinon comme les objets viennent de sessions hibernate différentes, on n'a pas + // l'égalité entre les objets) + testBioModel.getObject().setManipulateur( + CollectionTools.findWithValue(personnes, "idPersonne", AccessType.GETTER, testBioModel.getObject() + .getManipulateur().getIdPersonne())); + testBioModel.getObject().setMethode( + CollectionTools.findWithValue(methodes, "idMethodeTest", AccessType.GETTER, testBioModel + .getObject().getMethode().getIdMethodeTest())); + } - // liste des organismes suggérés à la saisie - organismes = personneService.listPersonneOrganismes(); - produitsTemoins = testBioService.listProduitsTemoins(); + // liste des organismes suggérés à la saisie + organismes = personneService.listPersonneOrganismes(); + produitsTemoins = testBioService.listProduitsTemoins(); - // bind with markup - final Form<Void> formView = new Form<Void>("Form"); + // bind with markup + final Form<Void> formView = new Form<Void>("Form"); - // initialisation du formulaire - initPrincipalFields(formView); - initMethodeFields(formView); - initResultatsFields(formView); + // initialisation du formulaire + initPrincipalFields(formView); + initMethodeFields(formView); + initResultatsFields(formView); - // Action : create the testBio - Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testBioService.createTestBio(testBioModel.getObject()); - } + // Action : create the testBio + Button createButton = new SubmittableButton(ACTION_CREATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testBioService.createTestBio(testBioModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_CREATE); - redirect(); - } + @Override + public void onSuccess() { + successNextPage(ACTION_CREATE); + redirect(); + } - @Override - public void onValidate() { - validateModel(); - } - }); - createButton.setVisibilityAllowed(createMode); - formView.add(createButton); + @Override + public void onValidate() { + validateModel(); + } + }); + createButton.setVisibilityAllowed(createMode); + formView.add(createButton); - // Action : update the testBio - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testBioService.updateTestBio(testBioModel.getObject()); - } + // Action : update the testBio + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testBioService.updateTestBio(testBioModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - validateModel(); - } - }); - updateButton.setVisibilityAllowed(!createMode); - formView.add(updateButton); + @Override + public void onValidate() { + validateModel(); + } + }); + updateButton.setVisibilityAllowed(!createMode); + formView.add(updateButton); - // Action : suppression - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testBioService.deleteTestBio(testBioModel.getObject()); - } + // Action : suppression + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + testBioService.deleteTestBio(testBioModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - deleteButton.setVisibilityAllowed(!createMode); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + deleteButton.setVisibilityAllowed(!createMode); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - formView.add(new Link<Void>("Cancel") { - // Cas où le formulaire est annulé - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + formView.add(new Link<Void>("Cancel") { + // Cas où le formulaire est annulé + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - formView.setDefaultButton(addResultatButton); - add(formView); + formView.setDefaultButton(addResultatButton); + add(formView); } @@ -353,84 +353,84 @@ * @param formView le formulaire */ private void initPrincipalFields(Form<Void> formView) { - formView.add(new TextField<String>("TestBio.ref", new PropertyModel<String>(testBioModel, "ref"))); + formView.add(new TextField<String>("TestBio.ref", new PropertyModel<String>(testBioModel, "ref"))); - formView.add(new DropDownChoice<Personne>("TestBio.manipulateur", new PropertyModel<Personne>(testBioModel, - "manipulateur"), personnes, new PersonneRenderer()).setNullValid(false)); + formView.add(new DropDownChoice<Personne>("TestBio.manipulateur", new PropertyModel<Personne>(testBioModel, + "manipulateur"), personnes, new PersonneRenderer()).setNullValid(false)); - // Action : création d'une nouvelle personne - // ajaxSubmitLink permet de sauvegarder l'état du formulaire - formView.add(new AjaxSubmitLink("NewPersonne") { - @Override - protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } + // Action : création d'une nouvelle personne + // ajaxSubmitLink permet de sauvegarder l'état du formulaire + formView.add(new AjaxSubmitLink("NewPersonne") { + @Override + protected void onSubmit(AjaxRequestTarget arg0, Form<?> arg1) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } - // si erreur, le formulaire est également enregistré puis la redirection effectuée - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); - } - }); + // si erreur, le formulaire est également enregistré puis la redirection effectuée + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + setResponsePage(new ManagePersonnePage(new CallerPage((TemplatePage) getPage()), false)); + } + }); - formView.add(new AutoCompleteTextFieldString("TestBio.organismeTesteur", new PropertyModel<String>( - testBioModel, "organismeTesteur"), organismes, ComparisonMode.CONTAINS)); + formView.add(new AutoCompleteTextFieldString("TestBio.organismeTesteur", new PropertyModel<String>( + testBioModel, "organismeTesteur"), organismes, ComparisonMode.CONTAINS)); - formView.add(new DateTextField("TestBio.date", new PropertyModel<Date>(testBioModel, "date")) - .add(new DatePicker())); + formView.add(new DateTextField("TestBio.date", new PropertyModel<Date>(testBioModel, "date")) + .add(new DatePicker())); - concMasseDefautInput = new TextField<BigDecimal>("TestBio.concMasseDefaut", new PropertyModel<BigDecimal>( - testBioModel, "concMasseDefaut")); - concMasseDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - // maj du champ concMasse du résultat si résultat de type produit ou témoin - if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT - || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { - newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); - target.add(concMasseInput); - } - }; - }); - formView.add(concMasseDefautInput); + concMasseDefautInput = new TextField<BigDecimal>("TestBio.concMasseDefaut", new PropertyModel<BigDecimal>( + testBioModel, "concMasseDefaut")); + concMasseDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + // maj du champ concMasse du résultat si résultat de type produit ou témoin + if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT + || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { + newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); + target.add(concMasseInput); + } + }; + }); + formView.add(concMasseDefautInput); - uniteConcMasseDefautInput = new DropDownChoice<UniteConcMasse>("TestBio.uniteConcMasseDefaut", - new PropertyModel<UniteConcMasse>(testBioModel, "uniteConcMasseDefaut"), Arrays.asList(UniteConcMasse - .values()), new EnumChoiceRenderer<UniteConcMasse>(this)); - uniteConcMasseDefautInput.setNullValid(true); + uniteConcMasseDefautInput = new DropDownChoice<UniteConcMasse>("TestBio.uniteConcMasseDefaut", + new PropertyModel<UniteConcMasse>(testBioModel, "uniteConcMasseDefaut"), Arrays.asList(UniteConcMasse + .values()), new EnumChoiceRenderer<UniteConcMasse>(this)); + uniteConcMasseDefautInput.setNullValid(true); - uniteConcMasseDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - // maj du champ uniteConcMasse du résultat si résultat de type produit - if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT - || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { - newResultatModel.getObject().setUniteConcMasse(uniteConcMasseDefautInput.getModelObject()); - target.add(uniteConcMasseInput); - } - } - }); - formView.add(uniteConcMasseDefautInput); + uniteConcMasseDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + // maj du champ uniteConcMasse du résultat si résultat de type produit + if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT + || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { + newResultatModel.getObject().setUniteConcMasse(uniteConcMasseDefautInput.getModelObject()); + target.add(uniteConcMasseInput); + } + } + }); + formView.add(uniteConcMasseDefautInput); - final AbstractSingleSelectChoice<Stade> stadeDefautInput = new DropDownChoice<Stade>("TestBio.stadeDefaut", - new PropertyModel<Stade>(testBioModel, "stadeDefaut"), Arrays.asList(Stade.values()), - new EnumChoiceRenderer<Stade>(this)); - stadeDefautInput.setNullValid(true); + final AbstractSingleSelectChoice<Stade> stadeDefautInput = new DropDownChoice<Stade>("TestBio.stadeDefaut", + new PropertyModel<Stade>(testBioModel, "stadeDefaut"), Arrays.asList(Stade.values()), + new EnumChoiceRenderer<Stade>(this)); + stadeDefautInput.setNullValid(true); - stadeDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - // maj du champ stade du résultat si résultat de type produit - if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT - || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { - newResultatModel.getObject().setStade(stadeDefautInput.getModelObject()); - target.add(stadeInput); - } - } - }); - formView.add(stadeDefautInput); + stadeDefautInput.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + // maj du champ stade du résultat si résultat de type produit + if (newResultatModel.getObject().getTypeResultat() == TypeResultat.PRODUIT + || newResultatModel.getObject().getTypeResultat() == TypeResultat.TEMOIN) { + newResultatModel.getObject().setStade(stadeDefautInput.getModelObject()); + target.add(stadeInput); + } + } + }); + formView.add(stadeDefautInput); - formView.add(new TextArea<String>("TestBio.complement", new PropertyModel<String>(testBioModel, "complement"))); - // Créateur en lecture seule - formView.add(new TextField<String>("TestBio.createur", new PropertyModel<String>(testBioModel, "createur")) - .setEnabled(false)); + formView.add(new TextArea<String>("TestBio.complement", new PropertyModel<String>(testBioModel, "complement"))); + // Créateur en lecture seule + formView.add(new TextField<String>("TestBio.createur", new PropertyModel<String>(testBioModel, "createur")) + .setEnabled(false)); } /** @@ -439,57 +439,57 @@ */ private void initMethodeFields(final Form<Void> formView) { - final WebMarkupContainer methodeCont = new WebMarkupContainer("TestBio.methode"); - methodeCont.setOutputMarkupId(true); - formView.add(methodeCont); + final WebMarkupContainer methodeCont = new WebMarkupContainer("TestBio.methode"); + methodeCont.setOutputMarkupId(true); + formView.add(methodeCont); - // Champs pour la méthode - descriptionMethoContainer = new WebMarkupContainer("TestBio.descriptionMethodeCont") { - @Override - public boolean isVisible() { - // description cachée si pas de méthode sélectionnée - return testBioModel.getObject().getMethode() != null; - } - }; - descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax - descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); // pour accéder à l'élement html qd son état est - // non visible - methodeCont.add(descriptionMethoContainer); + // Champs pour la méthode + descriptionMethoContainer = new WebMarkupContainer("TestBio.descriptionMethodeCont") { + @Override + public boolean isVisible() { + // description cachée si pas de méthode sélectionnée + return testBioModel.getObject().getMethode() != null; + } + }; + descriptionMethoContainer.setOutputMarkupId(true); // pour l'update Ajax + descriptionMethoContainer.setOutputMarkupPlaceholderTag(true); // pour accéder à l'élement html qd son état est + // non visible + methodeCont.add(descriptionMethoContainer); - Label methodeCible = new Label("TestBio.cibleMethode", new PropertyModel<String>(testBioModel, "methode.cible")); - descriptionMethoContainer.add(methodeCible); + Label methodeCible = new Label("TestBio.cibleMethode", new PropertyModel<String>(testBioModel, "methode.cible")); + descriptionMethoContainer.add(methodeCible); - Label methodeDomaine = new Label("TestBio.domaineMethode", new PropertyModel<String>(testBioModel, - "methode.domaine")); - descriptionMethoContainer.add(methodeDomaine); + Label methodeDomaine = new Label("TestBio.domaineMethode", new PropertyModel<String>(testBioModel, + "methode.domaine")); + descriptionMethoContainer.add(methodeDomaine); - MultiLineLabel methodeDesc = new MultiLineLabel("TestBio.descriptionMethode", new PropertyModel<String>( - testBioModel, "methode.description")); - descriptionMethoContainer.add(methodeDesc); + MultiLineLabel methodeDesc = new MultiLineLabel("TestBio.descriptionMethode", new PropertyModel<String>( + testBioModel, "methode.description")); + descriptionMethoContainer.add(methodeDesc); - Label methodeValeurMesuree = new Label("TestBio.valeurMesureeMethode", new PropertyModel<String>(testBioModel, - "methode.valeurMesuree")); - descriptionMethoContainer.add(methodeValeurMesuree); + Label methodeValeurMesuree = new Label("TestBio.valeurMesureeMethode", new PropertyModel<String>(testBioModel, + "methode.valeurMesuree")); + descriptionMethoContainer.add(methodeValeurMesuree); - Label methodeCritereActivite = new Label("TestBio.critereActiviteMethode", new PropertyModel<String>( - testBioModel, "methode.critereActivite")); - descriptionMethoContainer.add(methodeCritereActivite); + Label methodeCritereActivite = new Label("TestBio.critereActiviteMethode", new PropertyModel<String>( + testBioModel, "methode.critereActivite")); + descriptionMethoContainer.add(methodeCritereActivite); - Label methodeUniteResultat = new Label("TestBio.uniteResultatMethode", new PropertyModel<String>(testBioModel, - "methode.uniteResultat")); - descriptionMethoContainer.add(methodeUniteResultat); + Label methodeUniteResultat = new Label("TestBio.uniteResultatMethode", new PropertyModel<String>(testBioModel, + "methode.uniteResultat")); + descriptionMethoContainer.add(methodeUniteResultat); - final DropDownChoice<MethodeTestBio> methodeChoice = new DropDownChoice<MethodeTestBio>("TestBio.nomMethode", - new PropertyModel<MethodeTestBio>(testBioModel, "methode"), methodes); - methodeChoice.setNullValid(false); - // mise à jour de la description de la méthode et des fractions lors de la sélection de la méthode - methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - // mise à jour de la description et des paramètres - target.add(methodeCont); - } - }); - methodeCont.add(methodeChoice); + final DropDownChoice<MethodeTestBio> methodeChoice = new DropDownChoice<MethodeTestBio>("TestBio.nomMethode", + new PropertyModel<MethodeTestBio>(testBioModel, "methode"), methodes); + methodeChoice.setNullValid(false); + // mise à jour de la description de la méthode et des fractions lors de la sélection de la méthode + methodeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + // mise à jour de la description et des paramètres + target.add(methodeCont); + } + }); + methodeCont.add(methodeChoice); } /** @@ -498,348 +498,350 @@ */ private void initResultatsFields(final Form<Void> formView) { - // Déclaration tableau des resultats - final MarkupContainer testsBioTable = new WebMarkupContainer("TestBio.resultats.Table"); - testsBioTable.setOutputMarkupId(true); + // Déclaration tableau des resultats + final MarkupContainer testsBioTable = new WebMarkupContainer("TestBio.resultats.Table"); + testsBioTable.setOutputMarkupId(true); - // Contenu tableaux resultats - testsBioTable.add(new ListView<ResultatTestBio>("TestBio.resultats.List", - new PropertyModel<List<ResultatTestBio>>(testBioModel, "sortedResultats")) { - @Override - protected void populateItem(ListItem<ResultatTestBio> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux resultats + testsBioTable.add(new ListView<ResultatTestBio>("TestBio.resultats.List", + new PropertyModel<List<ResultatTestBio>>(testBioModel, "sortedResultats")) { + @Override + protected void populateItem(ListItem<ResultatTestBio> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final IModel<ResultatTestBio> resultatModel = item.getModel(); - final ResultatTestBio resultat = item.getModelObject(); + final IModel<ResultatTestBio> resultatModel = item.getModel(); + final ResultatTestBio resultat = item.getModelObject(); - // Colonnes - item.add(new Label("TestBio.resultats.List.repere", new PropertyModel<String>(resultat, "repere"))); - item.add(new Label("TestBio.resultats.List.typeResultat", new DisplayEnumPropertyModel(resultat, - "typeResultat", (TemplatePage) this.getPage()))); - item.add(new Label("TestBio.resultats.List.produit", new PropertyModel<String>(resultat, "produit.ref"))); + // Colonnes + item.add(new Label("TestBio.resultats.List.repere", new PropertyModel<String>(resultat, "repere"))); + item.add(new Label("TestBio.resultats.List.typeResultat", new DisplayEnumPropertyModel(resultat, + "typeResultat", (TemplatePage) this.getPage()))); + item + .add(new Label("TestBio.resultats.List.produit", new PropertyModel<String>(resultat, + "produit.ref"))); - item.add(new Label("TestBio.resultats.List.produitTemoin", new PropertyModel<String>(resultat, - "produitTemoin"))); + item.add(new Label("TestBio.resultats.List.produitTemoin", new PropertyModel<String>(resultat, + "produitTemoin"))); - // concatenation de concMasse et de uniteConcMasse - item.add(new Label("TestBio.resultats.List.concMasse", new Model<Serializable>(resultat) { + // concatenation de concMasse et de uniteConcMasse + item.add(new Label("TestBio.resultats.List.concMasse", new Model<Serializable>(resultat) { - /** {@inheritDoc} */ - @Override - public String getObject() { - String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasse", - DecimalDisplFormat.SMALL, getLocale()).getObject(); - if (masse == null) { - masse = ""; - } + /** {@inheritDoc} */ + @Override + public String getObject() { + String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasse", + DecimalDisplFormat.SMALL, getLocale()).getObject(); + if (masse == null) { + masse = ""; + } - String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasse", - (TemplatePage) getPage()).getObject(); - if (unite == null) { - unite = ""; - } - return masse + " " + unite; - } - })); + String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasse", + (TemplatePage) getPage()).getObject(); + if (unite == null) { + unite = ""; + } + return masse + " " + unite; + } + })); - item.add(new Label("TestBio.resultats.List.stade", new DisplayEnumPropertyModel(resultat, "stade", - (TemplatePage) this.getPage()))); - item.add(new Label("TestBio.resultats.List.valeur", new DisplayDecimalPropertyModel(resultat, "valeur", - DecimalDisplFormat.SMALL, getSession().getLocale()))); - item.add(new Label("TestBio.resultats.List.actif", new DisplayBooleanPropertyModel(resultatModel, - "estActif", (TemplatePage) this.getPage())).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("TestBio.resultats.List.stade", new DisplayEnumPropertyModel(resultat, "stade", + (TemplatePage) this.getPage()))); + item.add(new Label("TestBio.resultats.List.valeur", new DisplayDecimalPropertyModel(resultat, "valeur", + DecimalDisplFormat.SMALL, getSession().getLocale()))); + item.add(new Label("TestBio.resultats.List.actif", new DisplayBooleanPropertyModel(resultatModel, + "estActif", (TemplatePage) this.getPage())).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("TestBio.resultats.List.erreur", new PropertyModel<String>(resultat, "erreur.nom"))); - // info-bulle comprenant la description de l'erreur - item.add(new SimpleTooltipPanel("TestBio.resultats.List.erreur.info", new PropertyModel<String>( - resultat, "erreur.description")) { - /** {@inheritDoc} */ - @Override - public boolean isVisible() { - return resultat.getErreur() != null; - } - }); + item.add(new Label("TestBio.resultats.List.erreur", new PropertyModel<String>(resultat, "erreur.nom"))); + // info-bulle comprenant la description de l'erreur + item.add(new SimpleTooltipPanel("TestBio.resultats.List.erreur.info", new PropertyModel<String>( + resultat, "erreur.description")) { + /** {@inheritDoc} */ + @Override + public boolean isVisible() { + return resultat.getErreur() != null; + } + }); - // Action : suppression d'un résultat de test - Button deleteButton = new AjaxFallbackButton("TestBio.resultats.List.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - testBioModel.getObject().getResultats().remove(resultat); + // Action : suppression d'un résultat de test + Button deleteButton = new AjaxFallbackButton("TestBio.resultats.List.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + testBioModel.getObject().getResultats().remove(resultat); - if (target != null) { - target.add(testsBioTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(testsBioTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteButton.setDefaultFormProcessing(false); - item.add(deleteButton); - } - }); + }; + deleteButton.setDefaultFormProcessing(false); + item.add(deleteButton); + } + }); - // champs d'input - testsBioTable.add(new TextField<String>("TestBio.resultats.repere", new PropertyModel<String>(newResultatModel, - "repere")) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - // champs requis uniquement qd le bouton d'ajout de résultat est activé - // de même pour les autres composants ci-dessous - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton; - } - }); + // champs d'input + testsBioTable.add(new TextField<String>("TestBio.resultats.repere", new PropertyModel<String>(newResultatModel, + "repere")) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + // champs requis uniquement qd le bouton d'ajout de résultat est activé + // de même pour les autres composants ci-dessous + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton; + } + }); - final DropDownChoice<TypeResultat> typeResultatChoice = new DropDownChoice<TypeResultat>( - "TestBio.resultats.typeResultat", new PropertyModel<TypeResultat>(newResultatModel, "typeResultat"), - Arrays.asList(TypeResultat.values()), new EnumChoiceRenderer<TypeResultat>(this)) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton; - } - }; - typeResultatChoice.setNullValid(false); - testsBioTable.add(typeResultatChoice); + final DropDownChoice<TypeResultat> typeResultatChoice = new DropDownChoice<TypeResultat>( + "TestBio.resultats.typeResultat", new PropertyModel<TypeResultat>(newResultatModel, "typeResultat"), + Arrays.asList(TypeResultat.values()), new EnumChoiceRenderer<TypeResultat>(this)) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton; + } + }; + typeResultatChoice.setNullValid(false); + testsBioTable.add(typeResultatChoice); - final DropDownChoice<Produit> produitChoice = new DropDownChoice<Produit>("TestBio.resultats.produit", - new PropertyModel<Produit>(newResultatModel, "produit"), produits) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton - && typeResultatChoice.getModelObject() == TypeResultat.PRODUIT; - } - }; - produitChoice.setOutputMarkupId(true); - produitChoice.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(produitChoice); + final DropDownChoice<Produit> produitChoice = new DropDownChoice<Produit>("TestBio.resultats.produit", + new PropertyModel<Produit>(newResultatModel, "produit"), produits) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton + && typeResultatChoice.getModelObject() == TypeResultat.PRODUIT; + } + }; + produitChoice.setOutputMarkupId(true); + produitChoice.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(produitChoice); - final AutoCompleteTextFieldString produitTemoinInput = new AutoCompleteTextFieldString( - "TestBio.resultats.produitTemoin", new PropertyModel<String>(newResultatModel, "produitTemoin"), - produitsTemoins, ComparisonMode.CONTAINS) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton - && typeResultatChoice.getModelObject() == TypeResultat.TEMOIN; - } - }; - produitTemoinInput.setOutputMarkupId(true); - produitTemoinInput.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(produitTemoinInput); + final AutoCompleteTextFieldString produitTemoinInput = new AutoCompleteTextFieldString( + "TestBio.resultats.produitTemoin", new PropertyModel<String>(newResultatModel, "produitTemoin"), + produitsTemoins, ComparisonMode.CONTAINS) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton + && typeResultatChoice.getModelObject() == TypeResultat.TEMOIN; + } + }; + produitTemoinInput.setOutputMarkupId(true); + produitTemoinInput.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(produitTemoinInput); - concMasseInput = new TextField<BigInteger>("TestBio.resultats.concMasse", new PropertyModel<BigInteger>( - newResultatModel, "concMasse")); - concMasseInput.setOutputMarkupId(true); - concMasseInput.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(concMasseInput); + concMasseInput = new TextField<BigInteger>("TestBio.resultats.concMasse", new PropertyModel<BigInteger>( + newResultatModel, "concMasse")); + concMasseInput.setOutputMarkupId(true); + concMasseInput.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(concMasseInput); - uniteConcMasseInput = new DropDownChoice<UniteConcMasse>("TestBio.resultats.uniteConcMasse", - new PropertyModel<UniteConcMasse>(newResultatModel, "uniteConcMasse"), Arrays.asList(UniteConcMasse - .values()), new EnumChoiceRenderer<UniteConcMasse>(this)); - uniteConcMasseInput.setOutputMarkupId(true); - uniteConcMasseInput.setOutputMarkupPlaceholderTag(true); - uniteConcMasseInput.setNullValid(true); + uniteConcMasseInput = new DropDownChoice<UniteConcMasse>("TestBio.resultats.uniteConcMasse", + new PropertyModel<UniteConcMasse>(newResultatModel, "uniteConcMasse"), Arrays.asList(UniteConcMasse + .values()), new EnumChoiceRenderer<UniteConcMasse>(this)); + uniteConcMasseInput.setOutputMarkupId(true); + uniteConcMasseInput.setOutputMarkupPlaceholderTag(true); + uniteConcMasseInput.setNullValid(true); - testsBioTable.add(uniteConcMasseInput); + testsBioTable.add(uniteConcMasseInput); - stadeInput = new DropDownChoice<Stade>("TestBio.resultats.stade", new PropertyModel<Stade>(newResultatModel, - "stade"), Arrays.asList(Stade.values()), new EnumChoiceRenderer<Stade>(this)) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton - && typeResultatChoice.getModelObject() == TypeResultat.PRODUIT; - } - }; - stadeInput.setOutputMarkupId(true); - stadeInput.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(stadeInput); + stadeInput = new DropDownChoice<Stade>("TestBio.resultats.stade", new PropertyModel<Stade>(newResultatModel, + "stade"), Arrays.asList(Stade.values()), new EnumChoiceRenderer<Stade>(this)) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton + && typeResultatChoice.getModelObject() == TypeResultat.PRODUIT; + } + }; + stadeInput.setOutputMarkupId(true); + stadeInput.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(stadeInput); - testsBioTable - .add(new CheckBox("TestBio.resultats.actif", new PropertyModel<Boolean>(newResultatModel, "actif"))); + testsBioTable + .add(new CheckBox("TestBio.resultats.actif", new PropertyModel<Boolean>(newResultatModel, "actif"))); - final DropDownChoice<ErreurTestBio> erreurChoice = new DropDownChoice<ErreurTestBio>( - "TestBio.resultats.erreur", new PropertyModel<ErreurTestBio>(newResultatModel, "erreur"), erreurs); - erreurChoice.setNullValid(true); - testsBioTable.add(erreurChoice); + final DropDownChoice<ErreurTestBio> erreurChoice = new DropDownChoice<ErreurTestBio>( + "TestBio.resultats.erreur", new PropertyModel<ErreurTestBio>(newResultatModel, "erreur"), erreurs); + erreurChoice.setNullValid(true); + testsBioTable.add(erreurChoice); - // info-bulle comprenant la description de l'erreur - final SimpleTooltipPanel infoBulle = new SimpleTooltipPanel("TestBio.resultats.erreur.info", - new PropertyModel<String>(newResultatModel, "erreur.description")); - infoBulle.setVisibilityAllowed(false); - // permet la mise en visibité ou non en Ajax - infoBulle.setOutputMarkupId(true); - infoBulle.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(infoBulle); + // info-bulle comprenant la description de l'erreur + final SimpleTooltipPanel infoBulle = new SimpleTooltipPanel("TestBio.resultats.erreur.info", + new PropertyModel<String>(newResultatModel, "erreur.description")); + infoBulle.setVisibilityAllowed(false); + // permet la mise en visibité ou non en Ajax + infoBulle.setOutputMarkupId(true); + infoBulle.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(infoBulle); - final TextField<BigDecimal> valeurInput = new TextField<BigDecimal>("TestBio.resultats.valeur", - new PropertyModel<BigDecimal>(newResultatModel, "valeur")) { - @Override - @SuppressWarnings("unchecked") - public boolean isRequired() { - Form<Void> form = (Form<Void>) findParent(Form.class); - return form.getRootForm().findSubmittingButton() == addResultatButton - && erreurChoice.getModelObject() == null; - } - }; - valeurInput.setOutputMarkupId(true); - valeurInput.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(valeurInput); + final TextField<BigDecimal> valeurInput = new TextField<BigDecimal>("TestBio.resultats.valeur", + new PropertyModel<BigDecimal>(newResultatModel, "valeur")) { + @Override + @SuppressWarnings("unchecked") + public boolean isRequired() { + Form<Void> form = (Form<Void>) findParent(Form.class); + return form.getRootForm().findSubmittingButton() == addResultatButton + && erreurChoice.getModelObject() == null; + } + }; + valeurInput.setOutputMarkupId(true); + valeurInput.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(valeurInput); - // comportement dynamique sur les inputs - typeResultatChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - if (typeResultatChoice.getModelObject() == TypeResultat.BLANC) { - activeInputsForBlancType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, - stadeInput, target); - } else if (typeResultatChoice.getModelObject() == TypeResultat.TEMOIN) { - activeInputsForTemoinType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, - stadeInput, target); - } else { - activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, - stadeInput, true, target); - } - } - }); + // comportement dynamique sur les inputs + typeResultatChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + if (typeResultatChoice.getModelObject() == TypeResultat.BLANC) { + activeInputsForBlancType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, + stadeInput, target); + } else if (typeResultatChoice.getModelObject() == TypeResultat.TEMOIN) { + activeInputsForTemoinType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, + stadeInput, target); + } else { + activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, + stadeInput, true, target); + } + } + }); - erreurChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { - protected void onUpdate(AjaxRequestTarget target) { - if (erreurChoice.getModelObject() != null) { - // si une erreur est sélectionnée, le champ valeur est désactivé et l'info-bulle affichée - valeurInput.setVisibilityAllowed(false); - newResultatModel.getObject().setValeur(null); - infoBulle.setVisibilityAllowed(true); - } else { - // si une erreur est sélectionnée, le champ valeur est désactivé et l'info-bulle désactivée - valeurInput.setVisibilityAllowed(true); - infoBulle.setVisibilityAllowed(false); - } - target.add(valeurInput, infoBulle); - } - }); + erreurChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { + protected void onUpdate(AjaxRequestTarget target) { + if (erreurChoice.getModelObject() != null) { + // si une erreur est sélectionnée, le champ valeur est désactivé et l'info-bulle affichée + valeurInput.setVisibilityAllowed(false); + newResultatModel.getObject().setValeur(null); + infoBulle.setVisibilityAllowed(true); + } else { + // si une erreur est sélectionnée, le champ valeur est désactivé et l'info-bulle désactivée + valeurInput.setVisibilityAllowed(true); + infoBulle.setVisibilityAllowed(false); + } + target.add(valeurInput, infoBulle); + } + }); - // Bouton AJAX pour ajouter un résultat de test - addResultatButton = new AjaxFallbackButton("TestBio.resultats.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - try { - // normalisation du résultat - newResultatModel.getObject() - .setRepere( - Normalizer.normalize(UniqueFieldNormalizer.class, newResultatModel.getObject() - .getRepere())); - // ajout du type testBio - newResultatModel.getObject().setTestBio(testBioModel.getObject()); + // Bouton AJAX pour ajouter un résultat de test + addResultatButton = new AjaxFallbackButton("TestBio.resultats.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + try { + // normalisation du résultat + newResultatModel.getObject() + .setRepere( + Normalizer.normalize(UniqueFieldNormalizer.class, newResultatModel.getObject() + .getRepere())); + // ajout du type testBio + newResultatModel.getObject().setTestBio(testBioModel.getObject()); - // ajout à la liste - ResultatTestBio resultatAdded = newResultatModel.getObject().clone(); - testBioModel.getObject().getResultats().add(resultatAdded); + // ajout à la liste + ResultatTestBio resultatAdded = newResultatModel.getObject().clone(); + testBioModel.getObject().getResultats().add(resultatAdded); - List<String> errors = validator.validate(newResultatModel.getObject(), getSession().getLocale()); + List<String> errors = validator.validate(newResultatModel.getObject(), getSession().getLocale()); - // si une saisie existe pour concMasse, on s'assure que les deux composantes sont bien renseignées - if ((newResultatModel.getObject().getConcMasse() != null && newResultatModel.getObject() - .getUniteConcMasse() == null) - || (newResultatModel.getObject().getConcMasse() == null && newResultatModel.getObject() - .getUniteConcMasse() != null)) { - errors.add(getString("TestBio.resultats.concMasse.KO")); - } + // si une saisie existe pour concMasse, on s'assure que les deux composantes sont bien renseignées + if ((newResultatModel.getObject().getConcMasse() != null && newResultatModel.getObject() + .getUniteConcMasse() == null) + || (newResultatModel.getObject().getConcMasse() == null && newResultatModel.getObject() + .getUniteConcMasse() != null)) { + errors.add(getString("TestBio.resultats.concMasse.KO")); + } - if (errors.isEmpty()) { - // réinit des champs de la ligne "ajout" - newResultatModel.getObject().setRepere(null); - newResultatModel.getObject().setTypeResultat(TypeResultat.PRODUIT); - activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, - uniteConcMasseInput, stadeInput, true, target); - newResultatModel.getObject().setProduit(null); + if (errors.isEmpty()) { + // réinit des champs de la ligne "ajout" + newResultatModel.getObject().setRepere(null); + newResultatModel.getObject().setTypeResultat(TypeResultat.PRODUIT); + activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, + uniteConcMasseInput, stadeInput, true, target); + newResultatModel.getObject().setProduit(null); - // si non vide, ajout du témoin produit à la liste des propositions - if (StringUtils.isNotEmpty(newResultatModel.getObject().getProduitTemoin())) { - produitTemoinInput.addChoice(newResultatModel.getObject().getProduitTemoin()); - } - newResultatModel.getObject().setProduitTemoin(null); + // si non vide, ajout du témoin produit à la liste des propositions + if (StringUtils.isNotEmpty(newResultatModel.getObject().getProduitTemoin())) { + produitTemoinInput.addChoice(newResultatModel.getObject().getProduitTemoin()); + } + newResultatModel.getObject().setProduitTemoin(null); - // concMasse et uniteConcMasse prennent les valeurs par défaut - newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); - newResultatModel.getObject().setUniteConcMasse(uniteConcMasseDefautInput.getModelObject()); - newResultatModel.getObject().setStade(stadeInput.getModelObject()); - newResultatModel.getObject().setValeur(null); - newResultatModel.getObject().setActif(null); - newResultatModel.getObject().setErreur(null); - // réactivation du champ valeur en cas d'ancienne sélection d'erreur - valeurInput.setVisibilityAllowed(true); - } else { - testBioModel.getObject().getResultats().remove(resultatAdded); - addValidationErrors(errors); - } - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + // concMasse et uniteConcMasse prennent les valeurs par défaut + newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); + newResultatModel.getObject().setUniteConcMasse(uniteConcMasseDefautInput.getModelObject()); + newResultatModel.getObject().setStade(stadeInput.getModelObject()); + newResultatModel.getObject().setValeur(null); + newResultatModel.getObject().setActif(null); + newResultatModel.getObject().setErreur(null); + // réactivation du champ valeur en cas d'ancienne sélection d'erreur + valeurInput.setVisibilityAllowed(true); + } else { + testBioModel.getObject().getResultats().remove(resultatAdded); + addValidationErrors(errors); + } + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } - if (target != null) { - target.add(testsBioTable); - refreshFeedbackPage(target); - } - } + if (target != null) { + target.add(testsBioTable); + refreshFeedbackPage(target); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - testsBioTable.add(addResultatButton); - formView.add(testsBioTable); + }; + testsBioTable.add(addResultatButton); + formView.add(testsBioTable); - // pre-initialisation of the value Produit for TypeProduit - newResultatModel.getObject().setTypeResultat(TypeResultat.PRODUIT); - activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, stadeInput, - false, null); + // pre-initialisation of the value Produit for TypeProduit + newResultatModel.getObject().setTypeResultat(TypeResultat.PRODUIT); + activeInputsForProduitType(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseInput, stadeInput, + false, null); } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité - // Personne ou Lot) - refreshModel(); + // On rafraichit le modèle lorsque la page est rechargée (par exemple après l'ajout d'une nouvelle entité + // Personne ou Lot) + refreshModel(); - super.onBeforeRender(); + super.onBeforeRender(); } /** * Redirection vers une autre page. Cas où le formulaire est validé */ private void redirect() { - if (multipleEntry) { - // Redirection de nouveau vers l'écran de saisie d'une nouvelle testBio - TestBio nextManip = new TestBio(); - nextManip.setManipulateur(testBioModel.getObject().getManipulateur()); - nextManip.setOrganismeTesteur(testBioModel.getObject().getOrganismeTesteur()); - nextManip.setMethode(testBioModel.getObject().getMethode()); - setResponsePage(new ManageTestBioPage(nextManip, callerPage)); - } else if (callerPage != null) { - // On passe l'id du testBio associée à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(TestBio.class.getSimpleName(), testBioModel.getObject()); - callerPage.responsePage(this); - } + if (multipleEntry) { + // Redirection de nouveau vers l'écran de saisie d'une nouvelle testBio + TestBio nextManip = new TestBio(); + nextManip.setManipulateur(testBioModel.getObject().getManipulateur()); + nextManip.setOrganismeTesteur(testBioModel.getObject().getOrganismeTesteur()); + nextManip.setMethode(testBioModel.getObject().getMethode()); + setResponsePage(new ManageTestBioPage(nextManip, callerPage)); + } else if (callerPage != null) { + // On passe l'id du testBio associée à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(TestBio.class.getSimpleName(), testBioModel.getObject()); + callerPage.responsePage(this); + } } /** @@ -847,22 +849,22 @@ */ private void refreshModel() { - // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. - String key = Personne.class.getSimpleName(); - if (getPageParameters().getNamedKeys().contains(key)) { - CollectionTools.setter(personnes, personneService.listPersonnes()); - try { - Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); - testBioModel.getObject().setManipulateur(createdPersonne); - } catch (StringValueConversionException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - getPageParameters().remove(key); - } + // Récupère (et supprime) les éventuels nouveaux objets créés dans les paramètres de la page. + String key = Personne.class.getSimpleName(); + if (getPageParameters().getNamedKeys().contains(key)) { + CollectionTools.setter(personnes, personneService.listPersonnes()); + try { + Personne createdPersonne = personneService.loadPersonne(getPageParameters().get(key).toInt()); + testBioModel.getObject().setManipulateur(createdPersonne); + } catch (StringValueConversionException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + getPageParameters().remove(key); + } } /** @@ -875,28 +877,28 @@ * @param target Cible de la requête ajax */ private void activeInputsForBlancType(final DropDownChoice<Produit> produitChoice, - final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, - final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, - AjaxRequestTarget target) { - // si blanc, aucune saisie pour produit, produit témoin, conc., unité conc., stade - produitChoice.setNullValid(true); - newResultatModel.getObject().setProduit(null); - produitChoice.setVisibilityAllowed(false); + final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, + final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, + AjaxRequestTarget target) { + // si blanc, aucune saisie pour produit, produit témoin, conc., unité conc., stade + produitChoice.setNullValid(true); + newResultatModel.getObject().setProduit(null); + produitChoice.setVisibilityAllowed(false); - newResultatModel.getObject().setProduitTemoin(null); - produitTemoinInput.setVisibilityAllowed(false); + newResultatModel.getObject().setProduitTemoin(null); + produitTemoinInput.setVisibilityAllowed(false); - newResultatModel.getObject().setConcMasse(null); - concMasseInput.setVisibilityAllowed(false); + newResultatModel.getObject().setConcMasse(null); + concMasseInput.setVisibilityAllowed(false); - newResultatModel.getObject().setUniteConcMasse(null); - uniteConcMasseChoice.setVisibilityAllowed(false); + newResultatModel.getObject().setUniteConcMasse(null); + uniteConcMasseChoice.setVisibilityAllowed(false); - stadeChoice.setNullValid(true); - newResultatModel.getObject().setStade(null); - stadeChoice.setVisibilityAllowed(false); + stadeChoice.setNullValid(true); + newResultatModel.getObject().setStade(null); + stadeChoice.setVisibilityAllowed(false); - target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); + target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); } /** @@ -909,30 +911,30 @@ * @param target Cible de la requête ajax */ private void activeInputsForTemoinType(final DropDownChoice<Produit> produitChoice, - final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, - final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, - AjaxRequestTarget target) { - // si témoin, aucune saisie pour produit et stade - produitChoice.setNullValid(true); - newResultatModel.getObject().setProduit(null); - produitChoice.setVisibilityAllowed(false); + final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, + final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, + AjaxRequestTarget target) { + // si témoin, aucune saisie pour produit et stade + produitChoice.setNullValid(true); + newResultatModel.getObject().setProduit(null); + produitChoice.setVisibilityAllowed(false); - stadeChoice.setNullValid(true); - newResultatModel.getObject().setStade(null); - stadeChoice.setVisibilityAllowed(false); + stadeChoice.setNullValid(true); + newResultatModel.getObject().setStade(null); + stadeChoice.setVisibilityAllowed(false); - // saisie pour le reste - produitTemoinInput.setVisibilityAllowed(true); + // saisie pour le reste + produitTemoinInput.setVisibilityAllowed(true); - // masse/conc. par défaut comme valeur - newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); - concMasseInput.setVisibilityAllowed(true); + // masse/conc. par défaut comme valeur + newResultatModel.getObject().setConcMasse(concMasseDefautInput.getModelObject()); + concMasseInput.setVisibilityAllowed(true); - // unité masse/conc. par défaut comme valeur - newResultatModel.getObject().setUniteConcMasse(testBioModel.getObject().getUniteConcMasseDefaut()); - uniteConcMasseChoice.setVisibilityAllowed(true); + // unité masse/conc. par défaut comme valeur + newResultatModel.getObject().setUniteConcMasse(testBioModel.getObject().getUniteConcMasseDefaut()); + uniteConcMasseChoice.setVisibilityAllowed(true); - target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); + target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); } /** @@ -946,46 +948,46 @@ * @param target Cible de la requête ajax, null si non appelé par une requête ajax */ private void activeInputsForProduitType(final DropDownChoice<Produit> produitChoice, - final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, - final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, - boolean isAjaxRequete, AjaxRequestTarget target) { - // cas où type est produit, produit témoin désactivé et produit, conc., unité conc., stade activés - newResultatModel.getObject().setProduitTemoin(null); - produitTemoinInput.setVisibilityAllowed(false); + final TextField<String> produitTemoinInput, final TextField<BigInteger> concMasseInput, + final DropDownChoice<UniteConcMasse> uniteConcMasseChoice, final DropDownChoice<Stade> stadeChoice, + boolean isAjaxRequete, AjaxRequestTarget target) { + // cas où type est produit, produit témoin désactivé et produit, conc., unité conc., stade activés + newResultatModel.getObject().setProduitTemoin(null); + produitTemoinInput.setVisibilityAllowed(false); - produitChoice.setNullValid(false); - produitChoice.setVisibilityAllowed(true); + produitChoice.setNullValid(false); + produitChoice.setVisibilityAllowed(true); - // masse/conc. par défaut comme valeur - newResultatModel.getObject().setConcMasse(testBioModel.getObject().getConcMasseDefaut()); - concMasseInput.setVisibilityAllowed(true); + // masse/conc. par défaut comme valeur + newResultatModel.getObject().setConcMasse(testBioModel.getObject().getConcMasseDefaut()); + concMasseInput.setVisibilityAllowed(true); - // unité masse/conc. par défaut comme valeur - newResultatModel.getObject().setUniteConcMasse(testBioModel.getObject().getUniteConcMasseDefaut()); - uniteConcMasseChoice.setVisibilityAllowed(true); + // unité masse/conc. par défaut comme valeur + newResultatModel.getObject().setUniteConcMasse(testBioModel.getObject().getUniteConcMasseDefaut()); + uniteConcMasseChoice.setVisibilityAllowed(true); - stadeChoice.setNullValid(false); - // stade par défaut comme valeur - newResultatModel.getObject().setStade(testBioModel.getObject().getStadeDefaut()); - stadeChoice.setVisibilityAllowed(true); + stadeChoice.setNullValid(false); + // stade par défaut comme valeur + newResultatModel.getObject().setStade(testBioModel.getObject().getStadeDefaut()); + stadeChoice.setVisibilityAllowed(true); - if (isAjaxRequete) { - target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); - } + if (isAjaxRequete) { + target.add(produitChoice, produitTemoinInput, concMasseInput, uniteConcMasseChoice, stadeChoice); + } } /** * Validate model */ private void validateModel() { - addValidationErrors(validator.validate(testBioModel.getObject(), getSession().getLocale())); + addValidationErrors(validator.validate(testBioModel.getObject(), getSession().getLocale())); - if (!CollectionTools.containsWithValue(testBioModel.getObject().getResultats(), "typeResultat", - AccessType.GETTER, TypeResultat.PRODUIT)) { - error(getString("TestBio.resultats.noProduit")); - } - if (!testBioService.isTestBioUnique(testBioModel.getObject())) { - error(getString("TestBio.notUnique")); - } + if (!CollectionTools.containsWithValue(testBioModel.getObject().getResultats(), "typeResultat", + AccessType.GETTER, TypeResultat.PRODUIT)) { + error(getString("TestBio.resultats.noProduit")); + } + if (!testBioService.isTestBioUnique(testBioModel.getObject())) { + error(getString("TestBio.notUnique")); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ReadTestBioPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ReadTestBioPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/testBio/ReadTestBioPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -104,61 +104,61 @@ * @param callerPage Page appelante */ public ReadTestBioPage(Integer idTestBio, CallerPage callerPage) { - super(ReadTestBioPage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + super(ReadTestBioPage.class); + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation du modèle - testBioModel = new GenericLoadableDetachableModel<TestBio>(TestBio.class, idTestBio); + // Initialisation du modèle + testBioModel = new GenericLoadableDetachableModel<TestBio>(TestBio.class, idTestBio); - final TestBio testBio = testBioModel.getObject(); + final TestBio testBio = testBioModel.getObject(); - initPrincipalFields(testBioModel, currentPage); - initTestMethodFields(idTestBio); - initResultsFields(idTestBio, currentPage); + initPrincipalFields(testBioModel, currentPage); + initTestMethodFields(idTestBio); + initResultsFields(idTestBio, currentPage); - // Ajout du formulaire pour les actions - Form<Void> formView = new Form<Void>("Form"); + // Ajout du formulaire pour les actions + Form<Void> formView = new Form<Void>("Form"); - // Action : mise à jour (redirection vers le formulaire) - Link<TestBio> updateLink = new Link<TestBio>(getResource() + ".TestBio.Update", new Model<TestBio>(testBio)) { - @Override - public void onClick() { - setResponsePage(new ManageTestBioPage(getModelObject().getIdTestBio(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(testBioService.updateOrdeleteTestBioEnabled(testBio, getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<TestBio> updateLink = new Link<TestBio>(getResource() + ".TestBio.Update", new Model<TestBio>(testBio)) { + @Override + public void onClick() { + setResponsePage(new ManageTestBioPage(getModelObject().getIdTestBio(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(testBioService.updateOrdeleteTestBioEnabled(testBio, getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : retour à la page précédente - formView.add(new Link<Void>(getResource() + ".TestBio.Back") { - @Override - public void onClick() { - redirect(); - } - }); + // Action : retour à la page précédente + formView.add(new Link<Void>(getResource() + ".TestBio.Back") { + @Override + public void onClick() { + redirect(); + } + }); - // Action : suppression de la testBio - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageTestBioPage.class, - new SubmittableButtonEvents() { + // Action : suppression de la testBio + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageTestBioPage.class, + new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - testBioService.deleteTestBio(testBio); - } + @Override + public void onProcess() throws DataConstraintException { + testBioService.deleteTestBio(testBio); + } - @Override - public void onSuccess() { - successNextPage(ManageTestBioPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(testBioService.updateOrdeleteTestBioEnabled(testBio, getSession() - .getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManageTestBioPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(testBioService.updateOrdeleteTestBioEnabled(testBio, getSession() + .getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); + add(formView); } /** @@ -168,55 +168,55 @@ */ private void initPrincipalFields(IModel<TestBio> testBioModel, final CallerPage currentPage) { - add(new Label("TestBio.ref", new PropertyModel<String>(testBioModel, "ref")) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TestBio.ref", new PropertyModel<String>(testBioModel, "ref")) + .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("TestBio.manipulateur", new PropertyModel<Personne>(testBioModel, - "manipulateur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new PropertyLabelLinkPanel<Personne>("TestBio.manipulateur", new PropertyModel<Personne>(testBioModel, + "manipulateur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); - add(new Label("TestBio.organismeTesteur", new PropertyModel<String>(testBioModel, "organismeTesteur")) - .add(new ReplaceEmptyLabelBehavior())); - add(new Label("TestBio.date", new DisplayShortDatePropertyModel(testBioModel, "date", getLocale())) - .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TestBio.organismeTesteur", new PropertyModel<String>(testBioModel, "organismeTesteur")) + .add(new ReplaceEmptyLabelBehavior())); + add(new Label("TestBio.date", new DisplayShortDatePropertyModel(testBioModel, "date", getLocale())) + .add(new ReplaceEmptyLabelBehavior())); - // concatenation de concMasse par défaut et de uniteConcMasse par défaut - add(new Label("TestBio.concMasseDefaut", new Model<Serializable>(testBioModel) { - /** {@inheritDoc} */ - @Override - public String getObject() { - String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasseDefaut", - DecimalDisplFormat.SMALL, getLocale()).getObject(); + // concatenation de concMasse par défaut et de uniteConcMasse par défaut + add(new Label("TestBio.concMasseDefaut", new Model<Serializable>(testBioModel) { + /** {@inheritDoc} */ + @Override + public String getObject() { + String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasseDefaut", + DecimalDisplFormat.SMALL, getLocale()).getObject(); - String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasseDefaut", - (TemplatePage) getPage()).getObject(); + String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasseDefaut", + (TemplatePage) getPage()).getObject(); - if (masse == null && unite == null) { - return ReplaceEmptyLabelBehavior.NULL_PROPERTY; - } else if (masse == null) { - return ReplaceEmptyLabelBehavior.NULL_PROPERTY + unite; - } else if (unite == null) { - return masse + ReplaceEmptyLabelBehavior.NULL_PROPERTY; - } - return masse + " " + unite; - } - })); + if (masse == null && unite == null) { + return ReplaceEmptyLabelBehavior.NULL_PROPERTY; + } else if (masse == null) { + return ReplaceEmptyLabelBehavior.NULL_PROPERTY + unite; + } else if (unite == null) { + return masse + ReplaceEmptyLabelBehavior.NULL_PROPERTY; + } + return masse + " " + unite; + } + })); - add(new Label("TestBio.stadeDefaut", new DisplayEnumPropertyModel(testBioModel, "stadeDefaut", this)) - .add(new ReplaceEmptyLabelBehavior())); - add(new MultiLineLabel("TestBio.complement", new PropertyModel<String>(testBioModel, "complement")) - .add(new ReplaceEmptyLabelBehavior())); - add(new PropertyLabelLinkPanel<Personne>("TestBio.createur", new PropertyModel<Personne>(testBioModel, - "createur"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); - } - }); + add(new Label("TestBio.stadeDefaut", new DisplayEnumPropertyModel(testBioModel, "stadeDefaut", this)) + .add(new ReplaceEmptyLabelBehavior())); + add(new MultiLineLabel("TestBio.complement", new PropertyModel<String>(testBioModel, "complement")) + .add(new ReplaceEmptyLabelBehavior())); + add(new PropertyLabelLinkPanel<Personne>("TestBio.createur", new PropertyModel<Personne>(testBioModel, + "createur"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadPersonnePage(getModelObject().getIdPersonne(), currentPage)); + } + }); } /** @@ -224,41 +224,41 @@ * @param idTestBio itb */ private void initTestMethodFields(Integer idTestBio) { - WebMarkupContainer methodeCont = new WebMarkupContainer("TestBio.methode") { - @Override - public boolean isVisible() { - // description cachée si pas de méthode sélectionnée - return testBioModel.getObject().getMethode() != null; - } - }; - methodeCont.setOutputMarkupId(true); - add(methodeCont); + WebMarkupContainer methodeCont = new WebMarkupContainer("TestBio.methode") { + @Override + public boolean isVisible() { + // description cachée si pas de méthode sélectionnée + return testBioModel.getObject().getMethode() != null; + } + }; + methodeCont.setOutputMarkupId(true); + add(methodeCont); - Label methodeCible = new Label("TestBio.cibleMethode", new PropertyModel<String>(testBioModel, "methode.cible")); - methodeCont.add(methodeCible); + Label methodeCible = new Label("TestBio.cibleMethode", new PropertyModel<String>(testBioModel, "methode.cible")); + methodeCont.add(methodeCible); - Label methodeDomaine = new Label("TestBio.domaineMethode", new PropertyModel<String>(testBioModel, - "methode.domaine")); - methodeCont.add(methodeDomaine); + Label methodeDomaine = new Label("TestBio.domaineMethode", new PropertyModel<String>(testBioModel, + "methode.domaine")); + methodeCont.add(methodeDomaine); - MultiLineLabel methodeDesc = new MultiLineLabel("TestBio.descriptionMethode", new PropertyModel<String>( - testBioModel, "methode.description")); - methodeCont.add(methodeDesc); + MultiLineLabel methodeDesc = new MultiLineLabel("TestBio.descriptionMethode", new PropertyModel<String>( + testBioModel, "methode.description")); + methodeCont.add(methodeDesc); - Label methodeValeurMesuree = new Label("TestBio.valeurMesureeMethode", new PropertyModel<String>(testBioModel, - "methode.valeurMesuree")); - methodeCont.add(methodeValeurMesuree); + Label methodeValeurMesuree = new Label("TestBio.valeurMesureeMethode", new PropertyModel<String>(testBioModel, + "methode.valeurMesuree")); + methodeCont.add(methodeValeurMesuree); - Label methodeCritereActivite = new Label("TestBio.critereActiviteMethode", new PropertyModel<String>( - testBioModel, "methode.critereActivite")); - methodeCont.add(methodeCritereActivite); + Label methodeCritereActivite = new Label("TestBio.critereActiviteMethode", new PropertyModel<String>( + testBioModel, "methode.critereActivite")); + methodeCont.add(methodeCritereActivite); - Label methodeUniteResultat = new Label("TestBio.uniteResultatMethode", new PropertyModel<String>(testBioModel, - "methode.uniteResultat")); - methodeCont.add(methodeUniteResultat); + Label methodeUniteResultat = new Label("TestBio.uniteResultatMethode", new PropertyModel<String>(testBioModel, + "methode.uniteResultat")); + methodeCont.add(methodeUniteResultat); - Label nomMethode = new Label("TestBio.nomMethode", new PropertyModel<String>(testBioModel, "methode.nom")); - methodeCont.add(nomMethode); + Label nomMethode = new Label("TestBio.nomMethode", new PropertyModel<String>(testBioModel, "methode.nom")); + methodeCont.add(nomMethode); } @@ -268,119 +268,119 @@ * @param currentPage currentPage */ private void initResultsFields(Integer idTestBio, final CallerPage currentPage) { - // Déclaration tableau des resultats - // Pas de possibilité d'avoir le tableau vide car toujours au moins un résultat de type produit - final MarkupContainer testsBioTable = new WebMarkupContainer("TestBio.resultats.Table"); - testsBioTable.setOutputMarkupId(true); - add(testsBioTable); + // Déclaration tableau des resultats + // Pas de possibilité d'avoir le tableau vide car toujours au moins un résultat de type produit + final MarkupContainer testsBioTable = new WebMarkupContainer("TestBio.resultats.Table"); + testsBioTable.setOutputMarkupId(true); + add(testsBioTable); - final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( - "TestBio.resultats.resultsNotAccessibles"); - resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); - testsBioTable.add(resultNotAccessibleCont); + final WebMarkupContainer resultNotAccessibleCont = new WebMarkupContainer( + "TestBio.resultats.resultsNotAccessibles"); + resultNotAccessibleCont.setOutputMarkupPlaceholderTag(true); + testsBioTable.add(resultNotAccessibleCont); - // Model de liste des résultats - final LoadableDetachableModel<List<ResultatTestBio>> listResultsModel = new LoadableDetachableModel<List<ResultatTestBio>>() { - @Override - protected List<ResultatTestBio> load() { - boolean isOneResultNotAccessible = false; + // Model de liste des résultats + final LoadableDetachableModel<List<ResultatTestBio>> listResultsModel = new LoadableDetachableModel<List<ResultatTestBio>>() { + @Override + protected List<ResultatTestBio> load() { + boolean isOneResultNotAccessible = false; - List<ResultatTestBio> listResults = new ArrayList<ResultatTestBio>(); + List<ResultatTestBio> listResults = new ArrayList<ResultatTestBio>(); - for (ResultatTestBio res : testBioModel.getObject().getSortedResultats()) { - // les résultats de type blanc ou témoin sont tjr accessibles - if (res.getTypeResultat() != TypeResultat.PRODUIT - || testBioService.isResultatTestBioAccessibleByUser(res, ((AuthSession) getPage() - .getSession()).getUtilisateur())) { - listResults.add(res); - } else { - isOneResultNotAccessible = true; - } - } - // si un des résultats non accessible, on rend visible le message d'avertissement - resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); - return listResults; - } - }; + for (ResultatTestBio res : testBioModel.getObject().getSortedResultats()) { + // les résultats de type blanc ou témoin sont tjr accessibles + if (res.getTypeResultat() != TypeResultat.PRODUIT + || testBioService.isResultatTestBioAccessibleByUser(res, ((AuthSession) getPage() + .getSession()).getUtilisateur())) { + listResults.add(res); + } else { + isOneResultNotAccessible = true; + } + } + // si un des résultats non accessible, on rend visible le message d'avertissement + resultNotAccessibleCont.setVisibilityAllowed(isOneResultNotAccessible); + return listResults; + } + }; - // Contenu tableaux resultats - testsBioTable.add(new ListView<ResultatTestBio>("TestBio.resultats.List", listResultsModel) { - @Override - protected void populateItem(ListItem<ResultatTestBio> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Contenu tableaux resultats + testsBioTable.add(new ListView<ResultatTestBio>("TestBio.resultats.List", listResultsModel) { + @Override + protected void populateItem(ListItem<ResultatTestBio> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final IModel<ResultatTestBio> resultatModel = item.getModel(); - final ResultatTestBio resultat = resultatModel.getObject(); - // Colonnes - item.add(new Label("TestBio.resultats.List.repere", new PropertyModel<String>(resultat, "repere"))); - item.add(new Label("TestBio.resultats.List.typeResultat", new DisplayEnumPropertyModel(resultat, - "typeResultat", (TemplatePage) this.getPage()))); + final IModel<ResultatTestBio> resultatModel = item.getModel(); + final ResultatTestBio resultat = resultatModel.getObject(); + // Colonnes + item.add(new Label("TestBio.resultats.List.repere", new PropertyModel<String>(resultat, "repere"))); + item.add(new Label("TestBio.resultats.List.typeResultat", new DisplayEnumPropertyModel(resultat, + "typeResultat", (TemplatePage) this.getPage()))); - item.add(new PropertyLabelLinkProduitPanel("TestBio.resultats.List.produit", - new PropertyModel<Produit>(resultat, "produit"), (TemplatePage) getPage()) { - @Override - public void onClickIfExtrait(Extrait extrait) { - setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); - } + item.add(new PropertyLabelLinkProduitPanel("TestBio.resultats.List.produit", + new PropertyModel<Produit>(resultat, "produit"), (TemplatePage) getPage()) { + @Override + public void onClickIfExtrait(Extrait extrait) { + setResponsePage(new ReadExtractionPage(extrait.getExtraction().getIdExtraction(), currentPage)); + } - @Override - public void onClickIfFraction(Fraction fraction) { - setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), - currentPage)); - } - }); + @Override + public void onClickIfFraction(Fraction fraction) { + setResponsePage(new ReadPurificationPage(fraction.getPurification().getIdPurification(), + currentPage)); + } + }); - item.add(new Label("TestBio.resultats.List.produitTemoin", new PropertyModel<String>(resultat, - "produitTemoin"))); - // concaténation de concMasse et uniteMasse - item.add(new Label("TestBio.resultats.List.concMasse", new Model<Serializable>(resultat) { + item.add(new Label("TestBio.resultats.List.produitTemoin", new PropertyModel<String>(resultat, + "produitTemoin"))); + // concaténation de concMasse et uniteMasse + item.add(new Label("TestBio.resultats.List.concMasse", new Model<Serializable>(resultat) { - /** {@inheritDoc} */ - @Override - public String getObject() { - String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasse", - DecimalDisplFormat.SMALL, getLocale()).getObject(); + /** {@inheritDoc} */ + @Override + public String getObject() { + String masse = (String) new DisplayDecimalPropertyModel(super.getObject(), "concMasse", + DecimalDisplFormat.SMALL, getLocale()).getObject(); - String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasse", - (TemplatePage) getPage()).getObject(); + String unite = (String) new DisplayEnumPropertyModel(super.getObject(), "uniteConcMasse", + (TemplatePage) getPage()).getObject(); - if (masse == null && unite == null) { - return ReplaceEmptyLabelBehavior.NULL_PROPERTY; - } else if (masse == null) { - return ReplaceEmptyLabelBehavior.NULL_PROPERTY + unite; - } else if (unite == null) { - return masse + ReplaceEmptyLabelBehavior.NULL_PROPERTY; - } - return masse + " " + unite; - } - })); + if (masse == null && unite == null) { + return ReplaceEmptyLabelBehavior.NULL_PROPERTY; + } else if (masse == null) { + return ReplaceEmptyLabelBehavior.NULL_PROPERTY + unite; + } else if (unite == null) { + return masse + ReplaceEmptyLabelBehavior.NULL_PROPERTY; + } + return masse + " " + unite; + } + })); - item.add(new Label("TestBio.resultats.List.stade", new DisplayEnumPropertyModel(resultat, "stade", - (TemplatePage) this.getPage()))); - item.add(new Label("TestBio.resultats.List.valeur", new DisplayDecimalPropertyModel(resultat, "valeur", - DecimalDisplFormat.SMALL, getSession().getLocale()))); - item.add(new Label("TestBio.resultats.List.actif", new DisplayBooleanPropertyModel(resultatModel, - "estActif", (TemplatePage) this.getPage())).add(new ReplaceEmptyLabelBehavior())); - item.add(new Label("TestBio.resultats.List.erreur", new PropertyModel<String>(resultat, "erreur.nom"))); - // info-bulle comprenant la description de l'erreur - item.add(new SimpleTooltipPanel("TestBio.resultats.List.erreur.info", new PropertyModel<String>( - resultat, "erreur.description")) { - /** {@inheritDoc} */ - @Override - public boolean isVisible() { - return resultat.getErreur() != null; - } - }); - } - }); + item.add(new Label("TestBio.resultats.List.stade", new DisplayEnumPropertyModel(resultat, "stade", + (TemplatePage) this.getPage()))); + item.add(new Label("TestBio.resultats.List.valeur", new DisplayDecimalPropertyModel(resultat, "valeur", + DecimalDisplFormat.SMALL, getSession().getLocale()))); + item.add(new Label("TestBio.resultats.List.actif", new DisplayBooleanPropertyModel(resultatModel, + "estActif", (TemplatePage) this.getPage())).add(new ReplaceEmptyLabelBehavior())); + item.add(new Label("TestBio.resultats.List.erreur", new PropertyModel<String>(resultat, "erreur.nom"))); + // info-bulle comprenant la description de l'erreur + item.add(new SimpleTooltipPanel("TestBio.resultats.List.erreur.info", new PropertyModel<String>( + resultat, "erreur.description")) { + /** {@inheritDoc} */ + @Override + public boolean isVisible() { + return resultat.getErreur() != null; + } + }); + } + }); } /** * Redirection vers une autre page */ private void redirect() { - callerPage.responsePage(this); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ManageUtilisateurPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ManageUtilisateurPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ManageUtilisateurPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -82,7 +82,7 @@ * @author Mickael Tricot * @author Adrien Cheype */ -@AuthRoles({ AuthRole.ADMIN }) +@AuthRoles( { AuthRole.ADMIN }) public final class ManageUtilisateurPage extends TemplatePage { /** Action : delete */ @@ -142,296 +142,296 @@ * @param callerPage Page appelante (pour redirection) */ public ManageUtilisateurPage(Integer idPersonne, final CallerPage callerPage) { - super(ManageUtilisateurPage.class); + super(ManageUtilisateurPage.class); - // Initialisation des modèles - try { - utilisateurModel = new Model<Utilisateur>(personneService.loadUtilisateur(idPersonne)); - } catch (DataNotFoundException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - manageUtilisateurModel = new Model<ManageUtilisateurModel>(new ManageUtilisateurModel()); + // Initialisation des modèles + try { + utilisateurModel = new Model<Utilisateur>(personneService.loadUtilisateur(idPersonne)); + } catch (DataNotFoundException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + manageUtilisateurModel = new Model<ManageUtilisateurModel>(new ManageUtilisateurModel()); - manageUtilisateurModel.getObject().setCampagnesDroits(utilisateurModel.getObject().getCampagnesDroits()); - manageUtilisateurModel.getObject().getCampagnes() - .addAll(utilisateurModel.getObject().getCampagnesDroits().keySet()); - manageUtilisateurModel.getObject().setLotsDroits(utilisateurModel.getObject().getLotsDroits()); - manageUtilisateurModel.getObject().getLots().addAll(utilisateurModel.getObject().getLotsDroits().keySet()); + manageUtilisateurModel.getObject().setCampagnesDroits(utilisateurModel.getObject().getCampagnesDroits()); + manageUtilisateurModel.getObject().getCampagnes().addAll( + utilisateurModel.getObject().getCampagnesDroits().keySet()); + manageUtilisateurModel.getObject().setLotsDroits(utilisateurModel.getObject().getLotsDroits()); + manageUtilisateurModel.getObject().getLots().addAll(utilisateurModel.getObject().getLotsDroits().keySet()); - campagnePersonneDroitsModel = new Model<CampagnePersonneDroits>(new CampagnePersonneDroits()); - campagnePersonneDroitsModel.getObject().getId().setPk2(utilisateurModel.getObject()); - campagnePersonneDroitsModel.getObject().getDroits().setDroitExtrait(Boolean.TRUE); - campagnePersonneDroitsModel.getObject().getDroits().setDroitPuri(Boolean.TRUE); - campagnePersonneDroitsModel.getObject().getDroits().setDroitRecolte(Boolean.TRUE); - campagnePersonneDroitsModel.getObject().getDroits().setDroitTestBio(Boolean.TRUE); - lotsPersonneDroitsModel = new Model<LotPersonneDroits>(new LotPersonneDroits()); - lotsPersonneDroitsModel.getObject().getId().setPk2(utilisateurModel.getObject()); - lotsPersonneDroitsModel.getObject().getDroits().setDroitExtrait(Boolean.TRUE); - lotsPersonneDroitsModel.getObject().getDroits().setDroitPuri(Boolean.TRUE); - lotsPersonneDroitsModel.getObject().getDroits().setDroitRecolte(Boolean.TRUE); - lotsPersonneDroitsModel.getObject().getDroits().setDroitTestBio(Boolean.TRUE); + campagnePersonneDroitsModel = new Model<CampagnePersonneDroits>(new CampagnePersonneDroits()); + campagnePersonneDroitsModel.getObject().getId().setPk2(utilisateurModel.getObject()); + campagnePersonneDroitsModel.getObject().getDroits().setDroitExtrait(Boolean.TRUE); + campagnePersonneDroitsModel.getObject().getDroits().setDroitPuri(Boolean.TRUE); + campagnePersonneDroitsModel.getObject().getDroits().setDroitRecolte(Boolean.TRUE); + campagnePersonneDroitsModel.getObject().getDroits().setDroitTestBio(Boolean.TRUE); + lotsPersonneDroitsModel = new Model<LotPersonneDroits>(new LotPersonneDroits()); + lotsPersonneDroitsModel.getObject().getId().setPk2(utilisateurModel.getObject()); + lotsPersonneDroitsModel.getObject().getDroits().setDroitExtrait(Boolean.TRUE); + lotsPersonneDroitsModel.getObject().getDroits().setDroitPuri(Boolean.TRUE); + lotsPersonneDroitsModel.getObject().getDroits().setDroitRecolte(Boolean.TRUE); + lotsPersonneDroitsModel.getObject().getDroits().setDroitTestBio(Boolean.TRUE); - // Initialisation des listes - campagnes = Collections.unmodifiableList(campagneService.listCampagnes(getSession().getUtilisateur())); + // Initialisation des listes + campagnes = Collections.unmodifiableList(campagneService.listCampagnes(getSession().getUtilisateur())); - final Form<Void> formView = new Form<Void>("Form"); + final Form<Void> formView = new Form<Void>("Form"); - final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", utilisateurModel); - formView.add(personnePanel); + final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", utilisateurModel); + formView.add(personnePanel); - formView.add(new RadioChoice<TypeDroit>("Utilisateur.typeDroit", new PropertyModel<TypeDroit>(utilisateurModel, - "typeDroit"), Arrays.asList(TypeDroit.values()), new EnumChoiceRenderer<TypeDroit>(this))); + formView.add(new RadioChoice<TypeDroit>("Utilisateur.typeDroit", new PropertyModel<TypeDroit>(utilisateurModel, + "typeDroit"), Arrays.asList(TypeDroit.values()), new EnumChoiceRenderer<TypeDroit>(this))); - // Gestion des campagnes et lots autorisés - final MarkupContainer campagnesContainer = new WebMarkupContainer(getResource() - + ".Authorizations.Campagnes.Table"); - campagnesContainer.setOutputMarkupId(true); + // Gestion des campagnes et lots autorisés + final MarkupContainer campagnesContainer = new WebMarkupContainer(getResource() + + ".Authorizations.Campagnes.Table"); + campagnesContainer.setOutputMarkupId(true); - // Liste des campagnes autorisées - campagnesContainer.add(new ListView<Campagne>(getResource() + ".Authorizations.Campagnes.List", - manageUtilisateurModel.getObject().getCampagnes()) { - @Override - protected void populateItem(final ListItem<Campagne> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des campagnes autorisées + campagnesContainer.add(new ListView<Campagne>(getResource() + ".Authorizations.Campagnes.List", + manageUtilisateurModel.getObject().getCampagnes()) { + @Override + protected void populateItem(final ListItem<Campagne> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final Campagne campagne = item.getModelObject(); - item.add(new Label(getResource() + ".Authorizations.Campagnes.Campagne.nom", campagne.getNom())); - // Bouton de suppression des droits sur une campagne - AjaxFallbackButton deleteAuthorization = new AjaxFallbackButton( - "ManageUtilisateurPage.Authorizations.Campagnes.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - manageUtilisateurModel.getObject().getCampagnesDroits().remove(campagne); - // Mise à jour des listes - updateAvailableCampagnes(); - if (target != null) { - target.add(campagnesContainer); - } - } + final Campagne campagne = item.getModelObject(); + item.add(new Label(getResource() + ".Authorizations.Campagnes.Campagne.nom", campagne.getNom())); + // Bouton de suppression des droits sur une campagne + AjaxFallbackButton deleteAuthorization = new AjaxFallbackButton( + "ManageUtilisateurPage.Authorizations.Campagnes.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + manageUtilisateurModel.getObject().getCampagnesDroits().remove(campagne); + // Mise à jour des listes + updateAvailableCampagnes(); + if (target != null) { + target.add(campagnesContainer); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteAuthorization.setDefaultFormProcessing(false); - item.add(deleteAuthorization); - } - }); + }; + deleteAuthorization.setDefaultFormProcessing(false); + item.add(deleteAuthorization); + } + }); - // Liste des lots autorisés - campagnesContainer.add(new ListView<Lot>(getResource() + ".Authorizations.Lots.List", manageUtilisateurModel - .getObject().getLots()) { - @Override - protected void populateItem(ListItem<Lot> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des lots autorisés + campagnesContainer.add(new ListView<Lot>(getResource() + ".Authorizations.Lots.List", manageUtilisateurModel + .getObject().getLots()) { + @Override + protected void populateItem(ListItem<Lot> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - final Lot lot = item.getModelObject(); - item.add(new Label(getResource() + ".Authorizations.Lots.Campagne.nom", lot.getCampagne().getNom())); - item.add(new Label(getResource() + ".Authorizations.Lots.Lot.ref", lot.getRef())); - // Bouton de suppression des droits sur un lot - AjaxFallbackButton deleteAuthorization = new AjaxFallbackButton( - "ManageUtilisateurPage.Authorizations.Lots.Delete", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - // Suppression - manageUtilisateurModel.getObject().getLotsDroits().remove(lot); - // Mise à jour des listes - updateAvailableCampagnes(); - if (target != null) { - target.add(campagnesContainer); - } - } + final Lot lot = item.getModelObject(); + item.add(new Label(getResource() + ".Authorizations.Lots.Campagne.nom", lot.getCampagne().getNom())); + item.add(new Label(getResource() + ".Authorizations.Lots.Lot.ref", lot.getRef())); + // Bouton de suppression des droits sur un lot + AjaxFallbackButton deleteAuthorization = new AjaxFallbackButton( + "ManageUtilisateurPage.Authorizations.Lots.Delete", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + // Suppression + manageUtilisateurModel.getObject().getLotsDroits().remove(lot); + // Mise à jour des listes + updateAvailableCampagnes(); + if (target != null) { + target.add(campagnesContainer); + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - // never called - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + // never called + } - }; - deleteAuthorization.setDefaultFormProcessing(false); - item.add(deleteAuthorization); - } - }); + }; + deleteAuthorization.setDefaultFormProcessing(false); + item.add(deleteAuthorization); + } + }); - // Liste des campagnes disponibles (pour ajouter les droits) - availableCampagnes = new DropDownChoice<Campagne>(getResource() + ".Authorizations.Campagnes.Campagne", - new PropertyModel<Campagne>(campagnePersonneDroitsModel, "id.pk1"), new ArrayList<Campagne>()); - availableCampagnes.add(new AjaxFormComponentUpdatingBehavior("onchange") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - // Mise à jour des listes lorsqu'une campagne a été sélectionnée - updateAvailableCampagnes(); - target.add(availableLots); - } - }); - campagnesContainer.add(availableCampagnes); + // Liste des campagnes disponibles (pour ajouter les droits) + availableCampagnes = new DropDownChoice<Campagne>(getResource() + ".Authorizations.Campagnes.Campagne", + new PropertyModel<Campagne>(campagnePersonneDroitsModel, "id.pk1"), new ArrayList<Campagne>()); + availableCampagnes.add(new AjaxFormComponentUpdatingBehavior("onchange") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + // Mise à jour des listes lorsqu'une campagne a été sélectionnée + updateAvailableCampagnes(); + target.add(availableLots); + } + }); + campagnesContainer.add(availableCampagnes); - // Liste des lots disponibles (pour ajouter les droits) - availableLots = new DropDownChoice<Lot>(getResource() + ".Authorizations.Campagnes.Lot", - new PropertyModel<Lot>(lotsPersonneDroitsModel, "id.pk1"), new ArrayList<Lot>()); - availableLots.setOutputMarkupId(true); - campagnesContainer.add(availableLots); + // Liste des lots disponibles (pour ajouter les droits) + availableLots = new DropDownChoice<Lot>(getResource() + ".Authorizations.Campagnes.Lot", + new PropertyModel<Lot>(lotsPersonneDroitsModel, "id.pk1"), new ArrayList<Lot>()); + availableLots.setOutputMarkupId(true); + campagnesContainer.add(availableLots); - // Ajout de droits sur une campagne ou un lot - addAuthorization = new AjaxFallbackButton(getResource() + ".Authorizations.Campagnes.Add", formView) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - if (campagnePersonneDroitsModel.getObject().getId().getPk1() != null) { - if (lotsPersonneDroitsModel.getObject().getId().getPk1() == null) { - // Ajout de droits sur une campagne - CampagnePersonneDroits droits; - try { - droits = campagnePersonneDroitsModel.getObject().clone(); - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - // Recharge la campagne pour éviter une LazyLoadingException - campagneService.refreshCampagne(droits.getId().getPk1()); - manageUtilisateurModel.getObject().getCampagnesDroits().put(droits.getId().getPk1(), droits); + // Ajout de droits sur une campagne ou un lot + addAuthorization = new AjaxFallbackButton(getResource() + ".Authorizations.Campagnes.Add", formView) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + if (campagnePersonneDroitsModel.getObject().getId().getPk1() != null) { + if (lotsPersonneDroitsModel.getObject().getId().getPk1() == null) { + // Ajout de droits sur une campagne + CampagnePersonneDroits droits; + try { + droits = campagnePersonneDroitsModel.getObject().clone(); + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + // Recharge la campagne pour éviter une LazyLoadingException + campagneService.refreshCampagne(droits.getId().getPk1()); + manageUtilisateurModel.getObject().getCampagnesDroits().put(droits.getId().getPk1(), droits); - // puisque droits sur Campagne-Tous, suppression des Campagne-Lot de cette campagne - // Se base sur le réf de lot plutôt que l'objet pour être indépendant du contexte de persistance - // d'où provient l'entité - CollectionTools.removeAllWithValue(manageUtilisateurModel.getObject().getLotsDroits().keySet(), - "ref", AccessType.GETTER, CollectionTools.valuesFromList(droits.getId().getPk1() - .getLots(), "ref", AccessType.GETTER)); + // puisque droits sur Campagne-Tous, suppression des Campagne-Lot de cette campagne + // Se base sur le réf de lot plutôt que l'objet pour être indépendant du contexte de persistance + // d'où provient l'entité + CollectionTools.removeAllWithValue(manageUtilisateurModel.getObject().getLotsDroits().keySet(), + "ref", AccessType.GETTER, CollectionTools.valuesFromList(droits.getId().getPk1() + .getLots(), "ref", AccessType.GETTER)); - } else { - // Ajout de droits sur un lot - LotPersonneDroits droits; - try { - droits = lotsPersonneDroitsModel.getObject().clone(); - } catch (CloneNotSupportedException e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - manageUtilisateurModel.getObject().getLotsDroits().put(droits.getId().getPk1(), droits); - } - // Mise à jour des listes - updateAvailableCampagnes(); - if (target != null) { - target.add(campagnesContainer); - } - } - } + } else { + // Ajout de droits sur un lot + LotPersonneDroits droits; + try { + droits = lotsPersonneDroitsModel.getObject().clone(); + } catch (CloneNotSupportedException e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + manageUtilisateurModel.getObject().getLotsDroits().put(droits.getId().getPk1(), droits); + } + // Mise à jour des listes + updateAvailableCampagnes(); + if (target != null) { + target.add(campagnesContainer); + } + } + } - @Override - protected void onError(AjaxRequestTarget target, Form<?> form) { - refreshFeedbackPage(target); - } + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + refreshFeedbackPage(target); + } - }; - campagnesContainer.add(addAuthorization); + }; + campagnesContainer.add(addAuthorization); - updateAvailableCampagnes(); - formView.add(campagnesContainer); + updateAvailableCampagnes(); + formView.add(campagnesContainer); - // Action : mise à jour de l'utilisateur - Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.updateUtilisateur(utilisateurModel.getObject(), true); - } + // Action : mise à jour de l'utilisateur + Button updateButton = new SubmittableButton(ACTION_UPDATE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.updateUtilisateur(utilisateurModel.getObject(), true); + } - @Override - public void onSuccess() { - successNextPage(ACTION_UPDATE); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_UPDATE); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - utilisateurModel.getObject() - .setCampagnesDroits(manageUtilisateurModel.getObject().getCampagnesDroits()); - utilisateurModel.getObject().setLotsDroits(manageUtilisateurModel.getObject().getLotsDroits()); - personnePanel.validate(); - validator.validate(utilisateurModel.getObject(), getSession().getLocale(), "typeDroit"); - } - }); - updateButton.setVisibilityAllowed(utilisateurEstValide()); - formView.add(updateButton); + @Override + public void onValidate() { + utilisateurModel.getObject() + .setCampagnesDroits(manageUtilisateurModel.getObject().getCampagnesDroits()); + utilisateurModel.getObject().setLotsDroits(manageUtilisateurModel.getObject().getLotsDroits()); + personnePanel.validate(); + validator.validate(utilisateurModel.getObject(), getSession().getLocale(), "typeDroit"); + } + }); + updateButton.setVisibilityAllowed(utilisateurEstValide()); + formView.add(updateButton); - // Action validation de l'utilisateur - Button validButton = new SubmittableButton(ACTION_VALID, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.validAndUpdateUtilisateur(utilisateurModel.getObject()); - } + // Action validation de l'utilisateur + Button validButton = new SubmittableButton(ACTION_VALID, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.validAndUpdateUtilisateur(utilisateurModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_VALID); - callerPage.responsePage((TemplatePage) getPage()); - } + @Override + public void onSuccess() { + successNextPage(ACTION_VALID); + callerPage.responsePage((TemplatePage) getPage()); + } - @Override - public void onValidate() { - utilisateurModel.getObject() - .setCampagnesDroits(manageUtilisateurModel.getObject().getCampagnesDroits()); - utilisateurModel.getObject().setLotsDroits(manageUtilisateurModel.getObject().getLotsDroits()); - personnePanel.validate(); - validator.validate(utilisateurModel.getObject(), getSession().getLocale(), "typeDroit"); - } - }); - validButton.setVisibilityAllowed(!utilisateurEstValide()); - formView.add(validButton); + @Override + public void onValidate() { + utilisateurModel.getObject() + .setCampagnesDroits(manageUtilisateurModel.getObject().getCampagnesDroits()); + utilisateurModel.getObject().setLotsDroits(manageUtilisateurModel.getObject().getLotsDroits()); + personnePanel.validate(); + validator.validate(utilisateurModel.getObject(), getSession().getLocale(), "typeDroit"); + } + }); + validButton.setVisibilityAllowed(!utilisateurEstValide()); + formView.add(validButton); - // Action : suppression de l'utilisateur - Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException, EmailException { - personneService.deleteUtilisateur(utilisateurModel.getObject()); - } + // Action : suppression de l'utilisateur + Button deleteButton = new SubmittableButton(ACTION_DELETE, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException, EmailException { + personneService.deleteUtilisateur(utilisateurModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_DELETE); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - // impossible de supprimer son propre utilisateur - deleteButton.setVisibilityAllowed(utilisateurEstValide() - && getSession().getUtilisateur().getIdPersonne() != utilisateurModel.getObject().getIdPersonne()); - deleteButton.setDefaultFormProcessing(false); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); + @Override + public void onSuccess() { + successNextPage(ACTION_DELETE); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + // impossible de supprimer son propre utilisateur + deleteButton.setVisibilityAllowed(utilisateurEstValide() + && getSession().getUtilisateur().getIdPersonne() != utilisateurModel.getObject().getIdPersonne()); + deleteButton.setDefaultFormProcessing(false); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); - // Action : rejet de l'utilisateur - Button rejectButton = new SubmittableButton(ACTION_REJECT, new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.rejectUtilisateur(utilisateurModel.getObject()); - } + // Action : rejet de l'utilisateur + Button rejectButton = new SubmittableButton(ACTION_REJECT, new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.rejectUtilisateur(utilisateurModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ACTION_REJECT); - callerPage.responsePage((TemplatePage) getPage()); - } - }); - rejectButton.setVisibilityAllowed(!utilisateurEstValide()); - rejectButton.setDefaultFormProcessing(false); - rejectButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(rejectButton); + @Override + public void onSuccess() { + successNextPage(ACTION_REJECT); + callerPage.responsePage((TemplatePage) getPage()); + } + }); + rejectButton.setVisibilityAllowed(!utilisateurEstValide()); + rejectButton.setDefaultFormProcessing(false); + rejectButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(rejectButton); - // Action : annulation - formView.add(new Link<Void>("Cancel") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }); + // Action : annulation + formView.add(new Link<Void>("Cancel") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }); - add(formView); + add(formView); } /** @@ -439,49 +439,49 @@ */ @SuppressWarnings("unchecked") private void updateAvailableCampagnes() { - CollectionTools.setter(manageUtilisateurModel.getObject().getCampagnes(), manageUtilisateurModel.getObject() - .getCampagnesDroits().keySet()); - // tri pour affichage - Collections.sort(manageUtilisateurModel.getObject().getCampagnes(), BeanTools.createPropertyComparator("nom")); + CollectionTools.setter(manageUtilisateurModel.getObject().getCampagnes(), manageUtilisateurModel.getObject() + .getCampagnesDroits().keySet()); + // tri pour affichage + Collections.sort(manageUtilisateurModel.getObject().getCampagnes(), BeanTools.createPropertyComparator("nom")); - CollectionTools.setter(manageUtilisateurModel.getObject().getLots(), manageUtilisateurModel.getObject() - .getLotsDroits().keySet()); - // tri pour affichage - ComparatorChain campagneComp = new ComparatorChain(BeanTools.createPropertyComparator("campagne.nom")); - campagneComp.addComparator(BeanTools.createPropertyComparator("ref")); - Collections.sort(manageUtilisateurModel.getObject().getLots(), campagneComp); + CollectionTools.setter(manageUtilisateurModel.getObject().getLots(), manageUtilisateurModel.getObject() + .getLotsDroits().keySet()); + // tri pour affichage + ComparatorChain campagneComp = new ComparatorChain(BeanTools.createPropertyComparator("campagne.nom")); + campagneComp.addComparator(BeanTools.createPropertyComparator("ref")); + Collections.sort(manageUtilisateurModel.getObject().getLots(), campagneComp); - // Campagnes - List<Campagne> campagnesList = new ArrayList<Campagne>(campagnes); - // Supprime les campagnes dont l'utilisateur a déjà les droits - // Se base sur le nom de campagne plutôt que l'objet pour être indépendant du contexte de persistance d'où - // provient l'entité - CollectionTools.removeAllWithValue(campagnesList, "nom", AccessType.GETTER, CollectionTools.valuesFromList( - manageUtilisateurModel.getObject().getCampagnes(), "nom", AccessType.GETTER)); - // campagnesList.removeAll(manageUtilisateurModel.getObject().getCampagnes()); - availableCampagnes.setChoices(campagnesList); - campagnePersonneDroitsModel.getObject().getId() - .setPk1(campagnesList.isEmpty() ? null : availableCampagnes.getModelObject()); - availableCampagnes.setEnabled(!campagnesList.isEmpty()); + // Campagnes + List<Campagne> campagnesList = new ArrayList<Campagne>(campagnes); + // Supprime les campagnes dont l'utilisateur a déjà les droits + // Se base sur le nom de campagne plutôt que l'objet pour être indépendant du contexte de persistance d'où + // provient l'entité + CollectionTools.removeAllWithValue(campagnesList, "nom", AccessType.GETTER, CollectionTools.valuesFromList( + manageUtilisateurModel.getObject().getCampagnes(), "nom", AccessType.GETTER)); + // campagnesList.removeAll(manageUtilisateurModel.getObject().getCampagnes()); + availableCampagnes.setChoices(campagnesList); + campagnePersonneDroitsModel.getObject().getId().setPk1( + campagnesList.isEmpty() ? null : availableCampagnes.getModelObject()); + availableCampagnes.setEnabled(!campagnesList.isEmpty()); - // Lots - List<Lot> lotsList = new ArrayList<Lot>(); - availableLots.setEnabled(campagnePersonneDroitsModel.getObject().getId().getPk1() != null); - if (availableLots.isEnabled()) { - // Evite une LazyLoadingException car la campagne n'est plus dans la session - campagneService.refreshCampagne(campagnePersonneDroitsModel.getObject().getId().getPk1()); - lotsList.addAll(campagnePersonneDroitsModel.getObject().getId().getPk1().getLots()); - // Supprime les lots pour lequels l'utilisateur a déjà les droits - // Se base sur le réf de lot plutôt que l'objet pour être indépendant du contexte de persistance d'où - // provient l'entité - CollectionTools.removeAllWithValue(lotsList, "ref", AccessType.GETTER, CollectionTools.valuesFromList( - manageUtilisateurModel.getObject().getLots(), "ref", AccessType.GETTER)); + // Lots + List<Lot> lotsList = new ArrayList<Lot>(); + availableLots.setEnabled(campagnePersonneDroitsModel.getObject().getId().getPk1() != null); + if (availableLots.isEnabled()) { + // Evite une LazyLoadingException car la campagne n'est plus dans la session + campagneService.refreshCampagne(campagnePersonneDroitsModel.getObject().getId().getPk1()); + lotsList.addAll(campagnePersonneDroitsModel.getObject().getId().getPk1().getLots()); + // Supprime les lots pour lequels l'utilisateur a déjà les droits + // Se base sur le réf de lot plutôt que l'objet pour être indépendant du contexte de persistance d'où + // provient l'entité + CollectionTools.removeAllWithValue(lotsList, "ref", AccessType.GETTER, CollectionTools.valuesFromList( + manageUtilisateurModel.getObject().getLots(), "ref", AccessType.GETTER)); - availableLots.setChoices(lotsList); - } - lotsPersonneDroitsModel.getObject().getId().setPk1(null); + availableLots.setChoices(lotsList); + } + lotsPersonneDroitsModel.getObject().getId().setPk1(null); - addAuthorization.setEnabled(!campagnesList.isEmpty()); + addAuthorization.setEnabled(!campagnesList.isEmpty()); } /** @@ -489,6 +489,6 @@ * @return Validité */ private boolean utilisateurEstValide() { - return utilisateurModel.getObject().isValide(); + return utilisateurModel.getObject().isValide(); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ReadUtilisateurPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ReadUtilisateurPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ReadUtilisateurPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -73,86 +73,86 @@ * @param callerPage Page appelante */ public ReadUtilisateurPage(Integer idUtilisateur, CallerPage callerPage) { - super(ReadUtilisateurPage.class); + super(ReadUtilisateurPage.class); - final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); - this.callerPage = callerPage; + final CallerPage currentPage = new CallerPage((TemplatePage) getPage()); + this.callerPage = callerPage; - // Initialisation du modèle - utilisateurModel = new GenericLoadableDetachableModel<Utilisateur>(Utilisateur.class, idUtilisateur); + // Initialisation du modèle + utilisateurModel = new GenericLoadableDetachableModel<Utilisateur>(Utilisateur.class, idUtilisateur); - // Ajout du panel ReadPersonnePanel - add(new ReadPersonnePanel("ReadPersonnePanel", utilisateurModel)); + // Ajout du panel ReadPersonnePanel + add(new ReadPersonnePanel("ReadPersonnePanel", utilisateurModel)); - add(new Label("Utilisateur.typeDroits", new DisplayEnumPropertyModel(utilisateurModel, "typeDroit", this))); + add(new Label("Utilisateur.typeDroits", new DisplayEnumPropertyModel(utilisateurModel, "typeDroit", this))); - // Ajout du formulaire pour les actions - final Form<Utilisateur> formView = new Form<Utilisateur>("Form", utilisateurModel); + // Ajout du formulaire pour les actions + final Form<Utilisateur> formView = new Form<Utilisateur>("Form", utilisateurModel); - // Fieldset pour les droits de l'utilisateur (affiché uniquement si l'utilisateur est administrateur ou s'il - // affiche son propre profil) - MarkupContainer autorizationsFieldset = new WebMarkupContainer("ReadUtilisateurPage.AutorizationsFieldset") { - /** {@inheritDoc} */ - @Override - public boolean isVisible() { - Utilisateur currentUser = ReadUtilisateurPage.this.getSession().getUtilisateur(); - return currentUser.getTypeDroit() == TypeDroit.ADMINISTRATEUR - || currentUser.getIdPersonne().equals(utilisateurModel.getObject().getIdPersonne()); - } - }; + // Fieldset pour les droits de l'utilisateur (affiché uniquement si l'utilisateur est administrateur ou s'il + // affiche son propre profil) + MarkupContainer autorizationsFieldset = new WebMarkupContainer("ReadUtilisateurPage.AutorizationsFieldset") { + /** {@inheritDoc} */ + @Override + public boolean isVisible() { + Utilisateur currentUser = ReadUtilisateurPage.this.getSession().getUtilisateur(); + return currentUser.getTypeDroit() == TypeDroit.ADMINISTRATEUR + || currentUser.getIdPersonne().equals(utilisateurModel.getObject().getIdPersonne()); + } + }; - autorizationsFieldset.add(new ReadDroitsUtilisateurPanel("ReadDroitsUtilisateurPanel", utilisateurModel)); - add(autorizationsFieldset); + autorizationsFieldset.add(new ReadDroitsUtilisateurPanel("ReadDroitsUtilisateurPanel", utilisateurModel)); + add(autorizationsFieldset); - // Action : mise à jour (redirection vers le formulaire) - Link<Utilisateur> updateLink = new Link<Utilisateur>(getResource() + ".Personne.Update", utilisateurModel) { - @Override - public void onClick() { - setResponsePage(new ManageUtilisateurPage(getModelObject().getIdPersonne(), currentPage)); - } - }; - updateLink.setVisibilityAllowed(getSession().getUtilisateur().getIdPersonne() != utilisateurModel.getObject() - .getIdPersonne() - && personneService.updateOrDeletePersonneEnabled(utilisateurModel.getObject(), getSession() - .getUtilisateur())); - formView.add(updateLink); + // Action : mise à jour (redirection vers le formulaire) + Link<Utilisateur> updateLink = new Link<Utilisateur>(getResource() + ".Personne.Update", utilisateurModel) { + @Override + public void onClick() { + setResponsePage(new ManageUtilisateurPage(getModelObject().getIdPersonne(), currentPage)); + } + }; + updateLink.setVisibilityAllowed(getSession().getUtilisateur().getIdPersonne() != utilisateurModel.getObject() + .getIdPersonne() + && personneService.updateOrDeletePersonneEnabled(utilisateurModel.getObject(), getSession() + .getUtilisateur())); + formView.add(updateLink); - // Action : retour à la page précédente - formView.add(new Link<Void>(getResource() + ".Personne.Back") { - @Override - public void onClick() { - redirect(); - } - }); + // Action : retour à la page précédente + formView.add(new Link<Void>(getResource() + ".Personne.Back") { + @Override + public void onClick() { + redirect(); + } + }); - // Action : suppression de la personne - Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageUtilisateurPage.class, - new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataConstraintException { - personneService.deletePersonne(utilisateurModel.getObject()); - } + // Action : suppression de la personne + Button deleteButton = new SubmittableButton(ACTION_DELETE, ManageUtilisateurPage.class, + new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataConstraintException { + personneService.deletePersonne(utilisateurModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage(ManageUtilisateurPage.class, ACTION_DELETE); - redirect(); - } - }); - deleteButton.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(utilisateurModel.getObject(), - getSession().getUtilisateur())); - deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); - formView.add(deleteButton); - add(formView); + @Override + public void onSuccess() { + successNextPage(ManageUtilisateurPage.class, ACTION_DELETE); + redirect(); + } + }); + deleteButton.setVisibilityAllowed(personneService.updateOrDeletePersonneEnabled(utilisateurModel.getObject(), + getSession().getUtilisateur())); + deleteButton.add(new JSConfirmationBehavior(getString("Confirm"))); + formView.add(deleteButton); + add(formView); } /** * Redirection vers une autre page */ private void redirect() { - // On passe la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre de - // l'exploiter si besoin - callerPage.addPageParameter(Personne.class.getSimpleName(), utilisateurModel.getObject()); - callerPage.responsePage(this); + // On passe la personne associée à cette page, en paramètre de la prochaine page, pour lui permettre de + // l'exploiter si besoin + callerPage.addPageParameter(Personne.class.getSimpleName(), utilisateurModel.getObject()); + callerPage.responsePage(this); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/RegisterPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/RegisterPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/RegisterPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -63,83 +63,84 @@ private PersonneService personneService; /** Validateur modèle */ - @SpringBean(name = "webModelValidator") private ModelValidator validator; + @SpringBean(name = "webModelValidator") + private ModelValidator validator; /** * Constructeur */ public RegisterPage() { - super(RegisterPage.class); + super(RegisterPage.class); - // Initialisation des modèles (registerModel, CaptchaModel, Utilisateur) - final IModel<RegisterModel> registerModel = new Model<RegisterModel>(new RegisterModel()); - final IModel<CaptchaModel> captchaModel = new Model<CaptchaModel>(new CaptchaModel()); - captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); - final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); + // Initialisation des modèles (registerModel, CaptchaModel, Utilisateur) + final IModel<RegisterModel> registerModel = new Model<RegisterModel>(new RegisterModel()); + final IModel<CaptchaModel> captchaModel = new Model<CaptchaModel>(new CaptchaModel()); + captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); + final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); - // Formulaire - final Form<Void> formView = new Form<Void>("Form"); - final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", utilisateurModel); - formView.add(personnePanel); + // Formulaire + final Form<Void> formView = new Form<Void>("Form"); + final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", utilisateurModel); + formView.add(personnePanel); - // Champs n'apparaissant pas dans le "ManagePersonnePanel" - formView.add(new PasswordTextField("RegisterModel.password", new PropertyModel<String>(registerModel, - "password")).setRequired(false)); - final Component passwordConfirmationView = new PasswordTextField("RegisterModel.passwordConfirmation", - new PropertyModel<String>(registerModel, "passwordConfirmation")).setRequired(false); - formView.add(passwordConfirmationView); - formView.add(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel.getObject() - .getCaptchaTextGenerated()))); - final Component captchaTextView = new TextField<String>("CaptchaModel.captchaText", new PropertyModel<String>( - captchaModel, "captchaText")); - formView.add(captchaTextView); + // Champs n'apparaissant pas dans le "ManagePersonnePanel" + formView.add(new PasswordTextField("RegisterModel.password", new PropertyModel<String>(registerModel, + "password")).setRequired(false)); + final Component passwordConfirmationView = new PasswordTextField("RegisterModel.passwordConfirmation", + new PropertyModel<String>(registerModel, "passwordConfirmation")).setRequired(false); + formView.add(passwordConfirmationView); + formView.add(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel.getObject() + .getCaptchaTextGenerated()))); + final Component captchaTextView = new TextField<String>("CaptchaModel.captchaText", new PropertyModel<String>( + captchaModel, "captchaText")); + formView.add(captchaTextView); - // Action : enregistrement de l'utilisateur - formView.add(new SubmittableButton("Register", new SubmittableButtonEvents() { - @Override - public void onError() { - // Remise à zéro de certains champs - registerModel.getObject().setPassword(null); - registerModel.getObject().setPasswordConfirmation(null); - captchaModel.getObject().setCaptchaText(null); - captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); - formView.replace(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel - .getObject().getCaptchaTextGenerated()))); - } + // Action : enregistrement de l'utilisateur + formView.add(new SubmittableButton("Register", new SubmittableButtonEvents() { + @Override + public void onError() { + // Remise à zéro de certains champs + registerModel.getObject().setPassword(null); + registerModel.getObject().setPasswordConfirmation(null); + captchaModel.getObject().setCaptchaText(null); + captchaModel.getObject().setCaptchaTextGenerated(CaptchaTools.random()); + formView.replace(new NonCachingImage("CaptchaModel.captchaImage", new CaptchaImageResource(captchaModel + .getObject().getCaptchaTextGenerated()))); + } - @Override - public void onProcess() throws DataConstraintException { - // Cryptage du mot de passe - utilisateurModel.getObject().setPasswordHash( - personneService.hashPassword(registerModel.getObject().getPassword())); - // Mise à jour de l'utilisateur - personneService.createUtilisateur(utilisateurModel.getObject()); - } + @Override + public void onProcess() throws DataConstraintException { + // Cryptage du mot de passe + utilisateurModel.getObject().setPasswordHash( + personneService.hashPassword(registerModel.getObject().getPassword())); + // Mise à jour de l'utilisateur + personneService.createUtilisateur(utilisateurModel.getObject()); + } - @Override - public void onSuccess() { - successNextPage("Register"); - setResponsePage(HomePage.class); - } + @Override + public void onSuccess() { + successNextPage("Register"); + setResponsePage(HomePage.class); + } - @Override - public void onValidate() { - personnePanel.validate(); - List<String> passwordErrors = validator.validate(registerModel.getObject(), getSession().getLocale(), - "password"); - if (passwordErrors.isEmpty()) { - if (!registerModel.getObject().validate()) { - errorCurrentPage(passwordConfirmationView); - } - } else { - addValidationErrors(passwordErrors); - } - if (!captchaModel.getObject().validate()) { - errorCurrentPage(captchaTextView); - } - } - })); + @Override + public void onValidate() { + personnePanel.validate(); + List<String> passwordErrors = validator.validate(registerModel.getObject(), getSession().getLocale(), + "password"); + if (passwordErrors.isEmpty()) { + if (!registerModel.getObject().validate()) { + errorCurrentPage(passwordConfirmationView); + } + } else { + addValidationErrors(passwordErrors); + } + if (!captchaModel.getObject().validate()) { + errorCurrentPage(captchaTextView); + } + } + })); - add(formView); + add(formView); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ResetPasswordPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ResetPasswordPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/ResetPasswordPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,41 +53,42 @@ private PersonneService personneService; /** Validateur modèle */ - @SpringBean(name = "webModelValidator") private ModelValidator validator; + @SpringBean(name = "webModelValidator") + private ModelValidator validator; /** * Constructeur */ public ResetPasswordPage() { - super(ResetPasswordPage.class); - // Modèle - final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); - // Formulaire - Form<Utilisateur> formView = new Form<Utilisateur>("Form", utilisateurModel); - formView - .add(new TextField<String>("Personne.courriel", new PropertyModel<String>(utilisateurModel, "courriel"))); + super(ResetPasswordPage.class); + // Modèle + final IModel<Utilisateur> utilisateurModel = new Model<Utilisateur>(new Utilisateur()); + // Formulaire + Form<Utilisateur> formView = new Form<Utilisateur>("Form", utilisateurModel); + formView + .add(new TextField<String>("Personne.courriel", new PropertyModel<String>(utilisateurModel, "courriel"))); - // Action : regénération du mot de passe - formView.add(new SubmittableButton("Reset", new SubmittableButtonEvents() { - @Override - public void onProcess() throws DataNotFoundException, EmailException { - personneService.resetPasswordUtilisateur(utilisateurModel.getObject().getCourriel()); - } + // Action : regénération du mot de passe + formView.add(new SubmittableButton("Reset", new SubmittableButtonEvents() { + @Override + public void onProcess() throws DataNotFoundException, EmailException { + personneService.resetPasswordUtilisateur(utilisateurModel.getObject().getCourriel()); + } - @Override - public void onSuccess() { - successNextPage("Reset"); + @Override + public void onSuccess() { + successNextPage("Reset"); - setResponsePage(getApplication().getHomePage()); - } + setResponsePage(getApplication().getHomePage()); + } - @Override - public void onValidate() { - addValidationErrors(validator.validate(utilisateurModel.getObject(), getSession().getLocale(), - "courriel")); - } - })); + @Override + public void onValidate() { + addValidationErrors(validator.validate(utilisateurModel.getObject(), getSession().getLocale(), + "courriel")); + } + })); - add(formView); + add(formView); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/UpdateUtilisateurPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/UpdateUtilisateurPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/UpdateUtilisateurPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -75,7 +75,7 @@ * Constructeur */ public UpdateUtilisateurPage() { - this(null); + this(null); } /** @@ -83,137 +83,137 @@ * @param callerPage Page appelante (pour redirection) */ public UpdateUtilisateurPage(final CallerPage callerPage) { - super(UpdateUtilisateurPage.class); + super(UpdateUtilisateurPage.class); - // Initialisation du modèle (pour le profil) - final IModel<Utilisateur> utilisateurProfileModel = new Model<Utilisateur>(getSession().getUtilisateur()); + // Initialisation du modèle (pour le profil) + final IModel<Utilisateur> utilisateurProfileModel = new Model<Utilisateur>(getSession().getUtilisateur()); - // Initialisation du modèle supplémentaire - final IModel<UpdateUtilisateurModel> utilisateurPasswordModel = new Model<UpdateUtilisateurModel>( - new UpdateUtilisateurModel()); + // Initialisation du modèle supplémentaire + final IModel<UpdateUtilisateurModel> utilisateurPasswordModel = new Model<UpdateUtilisateurModel>( + new UpdateUtilisateurModel()); - // Formulaire de mise à jour du profil - final Form<Utilisateur> formProfileView = new Form<Utilisateur>("FormProfile", utilisateurProfileModel); + // Formulaire de mise à jour du profil + final Form<Utilisateur> formProfileView = new Form<Utilisateur>("FormProfile", utilisateurProfileModel); - final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", - utilisateurProfileModel); - formProfileView.add(personnePanel); + final ManagePersonnePanel personnePanel = new ManagePersonnePanel("ManagePersonnePanel", + utilisateurProfileModel); + formProfileView.add(personnePanel); - // Action : mise à jour du profil - formProfileView.add(new SubmittableButton(ACTION_UPDATE_PROFILE, new SubmittableButtonEvents() { - @Override - public void onError() { - utilisateurPasswordModel.getObject().setPassword(null); - } + // Action : mise à jour du profil + formProfileView.add(new SubmittableButton(ACTION_UPDATE_PROFILE, new SubmittableButtonEvents() { + @Override + public void onError() { + utilisateurPasswordModel.getObject().setPassword(null); + } - @Override - public void onProcess() throws DataConstraintException { - personneService.updateUtilisateur(utilisateurProfileModel.getObject(), false); - getSession().update(utilisateurProfileModel.getObject()); - } + @Override + public void onProcess() throws DataConstraintException { + personneService.updateUtilisateur(utilisateurProfileModel.getObject(), false); + getSession().update(utilisateurProfileModel.getObject()); + } - @Override - public void onSuccess() { - if (callerPage == null) { - successCurrentPage(ACTION_UPDATE_PROFILE); - } else { - successNextPage(ACTION_UPDATE_PROFILE); - callerPage.responsePage((TemplatePage) getPage()); - } - } + @Override + public void onSuccess() { + if (callerPage == null) { + successCurrentPage(ACTION_UPDATE_PROFILE); + } else { + successNextPage(ACTION_UPDATE_PROFILE); + callerPage.responsePage((TemplatePage) getPage()); + } + } - @Override - public void onValidate() { - personnePanel.validate(); - } - })); + @Override + public void onValidate() { + personnePanel.validate(); + } + })); - // Action : annulation - Link<Void> cancelProfileLink = new Link<Void>("CancelProfile") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }; - cancelProfileLink.setVisibilityAllowed(callerPage != null); - formProfileView.add(cancelProfileLink); - add(formProfileView); + // Action : annulation + Link<Void> cancelProfileLink = new Link<Void>("CancelProfile") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }; + cancelProfileLink.setVisibilityAllowed(callerPage != null); + formProfileView.add(cancelProfileLink); + add(formProfileView); - // Formulaire de mise à jour du mot de passe - final Form<UpdateUtilisateurModel> formPasswordView = new Form<UpdateUtilisateurModel>("FormPassword", - utilisateurPasswordModel); + // Formulaire de mise à jour du mot de passe + final Form<UpdateUtilisateurModel> formPasswordView = new Form<UpdateUtilisateurModel>("FormPassword", + utilisateurPasswordModel); - final Component currentPasswordView = new PasswordTextField("UpdateUtilisateurModel.currentPassword", - new PropertyModel<String>(utilisateurPasswordModel, "currentPassword")).setRequired(false); - formPasswordView.add(currentPasswordView); - formPasswordView.add(new PasswordTextField("UpdateUtilisateurModel.newPassword", new PropertyModel<String>( - utilisateurPasswordModel, "newPassword")).setRequired(false)); - final Component newPasswordConfirmationView = new PasswordTextField( - "UpdateUtilisateurModel.newPasswordConfirmation", new PropertyModel<String>(utilisateurPasswordModel, - "newPasswordConfirmation")).setRequired(false); - formPasswordView.add(newPasswordConfirmationView); + final Component currentPasswordView = new PasswordTextField("UpdateUtilisateurModel.currentPassword", + new PropertyModel<String>(utilisateurPasswordModel, "currentPassword")).setRequired(false); + formPasswordView.add(currentPasswordView); + formPasswordView.add(new PasswordTextField("UpdateUtilisateurModel.newPassword", new PropertyModel<String>( + utilisateurPasswordModel, "newPassword")).setRequired(false)); + final Component newPasswordConfirmationView = new PasswordTextField( + "UpdateUtilisateurModel.newPasswordConfirmation", new PropertyModel<String>(utilisateurPasswordModel, + "newPasswordConfirmation")).setRequired(false); + formPasswordView.add(newPasswordConfirmationView); - // Action : mise à jour du mot de passe - formPasswordView.add(new SubmittableButton(ACTION_UPDATE_PASSWORD, new SubmittableButtonEvents() { - @Override - public void onError() { - utilisateurPasswordModel.getObject().setCurrentPassword(null); - utilisateurPasswordModel.getObject().setNewPassword(null); - utilisateurPasswordModel.getObject().setNewPasswordConfirmation(null); - } + // Action : mise à jour du mot de passe + formPasswordView.add(new SubmittableButton(ACTION_UPDATE_PASSWORD, new SubmittableButtonEvents() { + @Override + public void onError() { + utilisateurPasswordModel.getObject().setCurrentPassword(null); + utilisateurPasswordModel.getObject().setNewPassword(null); + utilisateurPasswordModel.getObject().setNewPasswordConfirmation(null); + } - @Override - public void onProcess() throws DataConstraintException { - utilisateurProfileModel.getObject().setPasswordHash( - personneService.hashPassword(utilisateurPasswordModel.getObject().getNewPassword())); - personneService.updateUtilisateur(utilisateurProfileModel.getObject(), false); - getSession().update(utilisateurProfileModel.getObject()); - } + @Override + public void onProcess() throws DataConstraintException { + utilisateurProfileModel.getObject().setPasswordHash( + personneService.hashPassword(utilisateurPasswordModel.getObject().getNewPassword())); + personneService.updateUtilisateur(utilisateurProfileModel.getObject(), false); + getSession().update(utilisateurProfileModel.getObject()); + } - @Override - public void onSuccess() { - if (callerPage == null) { - successCurrentPage(ACTION_UPDATE_PASSWORD); - } else { - successNextPage(ACTION_UPDATE_PASSWORD); - callerPage.responsePage((TemplatePage) getPage()); - } - } + @Override + public void onSuccess() { + if (callerPage == null) { + successCurrentPage(ACTION_UPDATE_PASSWORD); + } else { + successNextPage(ACTION_UPDATE_PASSWORD); + callerPage.responsePage((TemplatePage) getPage()); + } + } - @Override - public void onValidate() { - // Erreurs mot de passe courant - List<String> passwordErrors = validator.validate(utilisateurPasswordModel.getObject(), getSession() - .getLocale(), "currentPassword"); - addValidationErrors(passwordErrors); - if (passwordErrors.isEmpty() - && !utilisateurProfileModel.getObject().getPasswordHash() - .equals( - personneService.hashPassword(utilisateurPasswordModel.getObject() - .getCurrentPassword()))) { - errorCurrentPage(currentPasswordView); - } - // Erreurs nouveau mot de passe - passwordErrors = validator.validate(utilisateurPasswordModel.getObject(), getSession().getLocale(), - "newPassword"); - addValidationErrors(passwordErrors); - if (passwordErrors.isEmpty() && !utilisateurPasswordModel.getObject().validate()) { - errorCurrentPage(newPasswordConfirmationView); - } - } + @Override + public void onValidate() { + // Erreurs mot de passe courant + List<String> passwordErrors = validator.validate(utilisateurPasswordModel.getObject(), getSession() + .getLocale(), "currentPassword"); + addValidationErrors(passwordErrors); + if (passwordErrors.isEmpty() + && !utilisateurProfileModel.getObject().getPasswordHash() + .equals( + personneService.hashPassword(utilisateurPasswordModel.getObject() + .getCurrentPassword()))) { + errorCurrentPage(currentPasswordView); + } + // Erreurs nouveau mot de passe + passwordErrors = validator.validate(utilisateurPasswordModel.getObject(), getSession().getLocale(), + "newPassword"); + addValidationErrors(passwordErrors); + if (passwordErrors.isEmpty() && !utilisateurPasswordModel.getObject().validate()) { + errorCurrentPage(newPasswordConfirmationView); + } + } - })); + })); - // Action : annulation - Link<Void> cancelPasswordLink = new Link<Void>("CancelPassword") { - @Override - public void onClick() { - callerPage.responsePage((TemplatePage) getPage()); - } - }; - cancelPasswordLink.setVisibilityAllowed(callerPage != null); - formPasswordView.add(cancelPasswordLink); + // Action : annulation + Link<Void> cancelPasswordLink = new Link<Void>("CancelPassword") { + @Override + public void onClick() { + callerPage.responsePage((TemplatePage) getPage()); + } + }; + cancelPasswordLink.setVisibilityAllowed(callerPage != null); + formPasswordView.add(cancelPasswordLink); - add(formPasswordView); + add(formPasswordView); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/panels/ReadDroitsUtilisateurPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/panels/ReadDroitsUtilisateurPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/domain/utilisateur/panels/ReadDroitsUtilisateurPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -62,95 +62,95 @@ * @param utilisateurModel Modèle de l'utilisateur concerné */ public ReadDroitsUtilisateurPanel(String id, final IModel<? extends Utilisateur> utilisateurModel) { - super(id, utilisateurModel); + super(id, utilisateurModel); - // Gestion des campagnes et lots autorisés - final MarkupContainer autorisationsContainer = new WebMarkupContainer("Authorizations.Table") { - @Override - public boolean isVisible() { - return utilisateurModel.getObject().getCampagnesDroits().size() != 0 - || utilisateurModel.getObject().getLotsDroits().size() != 0; - } - }; - autorisationsContainer.setOutputMarkupId(true); + // Gestion des campagnes et lots autorisés + final MarkupContainer autorisationsContainer = new WebMarkupContainer("Authorizations.Table") { + @Override + public boolean isVisible() { + return utilisateurModel.getObject().getCampagnesDroits().size() != 0 + || utilisateurModel.getObject().getLotsDroits().size() != 0; + } + }; + autorisationsContainer.setOutputMarkupId(true); - final LoadableDetachableModel<List<CampagnePersonneDroits>> campagnesModel = new LoadableDetachableModel<List<CampagnePersonneDroits>>() { - @Override - protected List<CampagnePersonneDroits> load() { - List<CampagnePersonneDroits> listCampagnesDroits = new ArrayList<CampagnePersonneDroits>( - utilisateurModel.getObject().getCampagnesDroits().values()); + final LoadableDetachableModel<List<CampagnePersonneDroits>> campagnesModel = new LoadableDetachableModel<List<CampagnePersonneDroits>>() { + @Override + protected List<CampagnePersonneDroits> load() { + List<CampagnePersonneDroits> listCampagnesDroits = new ArrayList<CampagnePersonneDroits>( + utilisateurModel.getObject().getCampagnesDroits().values()); - // tri pour affichage - Collections.sort(listCampagnesDroits, new CampagnePersonneDroitsComp()); - return listCampagnesDroits; - } - }; + // tri pour affichage + Collections.sort(listCampagnesDroits, new CampagnePersonneDroitsComp()); + return listCampagnesDroits; + } + }; - // Liste des campagnes autorisées - autorisationsContainer - .add(new ListView<CampagnePersonneDroits>("Authorizations.Campagnes.List", campagnesModel) { - @Override - protected void populateItem(final ListItem<CampagnePersonneDroits> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des campagnes autorisées + autorisationsContainer + .add(new ListView<CampagnePersonneDroits>("Authorizations.Campagnes.List", campagnesModel) { + @Override + protected void populateItem(final ListItem<CampagnePersonneDroits> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - item.add(new PropertyLabelLinkPanel<Campagne>("Authorizations.Campagnes.Campagne.nom", - new PropertyModel<Campagne>(item.getModel(), "id.pk1"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), new CallerPage( - (TemplatePage) getPage()))); - } - }); - } - }); + item.add(new PropertyLabelLinkPanel<Campagne>("Authorizations.Campagnes.Campagne.nom", + new PropertyModel<Campagne>(item.getModel(), "id.pk1"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), new CallerPage( + (TemplatePage) getPage()))); + } + }); + } + }); - // Liste des lots autorisés - final LoadableDetachableModel<List<LotPersonneDroits>> lotsModel = new LoadableDetachableModel<List<LotPersonneDroits>>() { - protected List<LotPersonneDroits> load() { - List<LotPersonneDroits> listLotsDroits = new ArrayList<LotPersonneDroits>(utilisateurModel.getObject() - .getLotsDroits().values()); - // tri pour affichage - Collections.sort(listLotsDroits, new LotPersonneDroitsComp()); - return listLotsDroits; - } - }; - autorisationsContainer.add(new ListView<LotPersonneDroits>("Authorizations.Lots.List", lotsModel) { - @Override - protected void populateItem(ListItem<LotPersonneDroits> item) { - if (item.getIndex() % 2 == 1) { - item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); - } + // Liste des lots autorisés + final LoadableDetachableModel<List<LotPersonneDroits>> lotsModel = new LoadableDetachableModel<List<LotPersonneDroits>>() { + protected List<LotPersonneDroits> load() { + List<LotPersonneDroits> listLotsDroits = new ArrayList<LotPersonneDroits>(utilisateurModel.getObject() + .getLotsDroits().values()); + // tri pour affichage + Collections.sort(listLotsDroits, new LotPersonneDroitsComp()); + return listLotsDroits; + } + }; + autorisationsContainer.add(new ListView<LotPersonneDroits>("Authorizations.Lots.List", lotsModel) { + @Override + protected void populateItem(ListItem<LotPersonneDroits> item) { + if (item.getIndex() % 2 == 1) { + item.add(new AttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd")); + } - item.add(new PropertyLabelLinkPanel<Campagne>("Authorizations.Lots.Campagne.nom", - new PropertyModel<Campagne>(item.getModel(), "id.pk1.campagne"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), new CallerPage( - (TemplatePage) getPage()))); - } - }); + item.add(new PropertyLabelLinkPanel<Campagne>("Authorizations.Lots.Campagne.nom", + new PropertyModel<Campagne>(item.getModel(), "id.pk1.campagne"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadCampagnePage(getModelObject().getIdCampagne(), new CallerPage( + (TemplatePage) getPage()))); + } + }); - item.add(new PropertyLabelLinkPanel<Lot>("Authorizations.Lots.Lot.ref", new PropertyModel<Lot>(item - .getModel(), "id.pk1"), getString("Read")) { - @Override - public void onClick() { - setResponsePage(new ReadLotPage(getModelObject().getIdLot(), new CallerPage( - (TemplatePage) getPage()))); - } - }); - } - }); - add(autorisationsContainer); + item.add(new PropertyLabelLinkPanel<Lot>("Authorizations.Lots.Lot.ref", new PropertyModel<Lot>(item + .getModel(), "id.pk1"), getString("Read")) { + @Override + public void onClick() { + setResponsePage(new ReadLotPage(getModelObject().getIdLot(), new CallerPage( + (TemplatePage) getPage()))); + } + }); + } + }); + add(autorisationsContainer); - // Selon la non existence d'elements dans la table on affiche le span pour remplacer - MarkupContainer emptyCampagnesContainer = new WebMarkupContainer("Authorizations.emptyTable") { - @Override - public boolean isVisible() { - return !autorisationsContainer.isVisible(); - } - }; - add(emptyCampagnesContainer); + // Selon la non existence d'elements dans la table on affiche le span pour remplacer + MarkupContainer emptyCampagnesContainer = new WebMarkupContainer("Authorizations.emptyTable") { + @Override + public boolean isVisible() { + return !autorisationsContainer.isVisible(); + } + }; + add(emptyCampagnesContainer); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/errors/ErrorPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/errors/ErrorPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/errors/ErrorPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,19 +39,19 @@ * Constructor */ public ErrorPage() { - super(ErrorPage.class); - String errorMsgKey = String.format(PATTERN_ERROR_MSG, getResource(), getClass().getSimpleName()); - try { - errorMsgKey = getString(errorMsgKey); - } catch (MissingResourceException e) { - // - } - error(errorMsgKey); + super(ErrorPage.class); + String errorMsgKey = String.format(PATTERN_ERROR_MSG, getResource(), getClass().getSimpleName()); + try { + errorMsgKey = getString(errorMsgKey); + } catch (MissingResourceException e) { + // + } + error(errorMsgKey); } /** {@inheritDoc} */ @Override public final boolean isErrorPage() { - return true; + return true; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/CaptchaModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/CaptchaModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/CaptchaModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,7 +45,7 @@ * @return TRUE if it is valid */ public boolean validate() { - return !StringUtils.isEmpty(captchaText) && captchaTextGenerated.equals(captchaText); + return !StringUtils.isEmpty(captchaText) && captchaTextGenerated.equals(captchaText); } /** @@ -53,7 +53,7 @@ * @return captchaText */ public String getCaptchaText() { - return captchaText; + return captchaText; } /** @@ -61,7 +61,7 @@ * @param captchaText captchaText */ public void setCaptchaText(String captchaText) { - this.captchaText = captchaText; + this.captchaText = captchaText; } /** @@ -69,7 +69,7 @@ * @return captchaTextGenerated */ public String getCaptchaTextGenerated() { - return captchaTextGenerated; + return captchaTextGenerated; } /** @@ -77,7 +77,7 @@ * @param captchaTextGenerated captchaTextGenerated */ public void setCaptchaTextGenerated(String captchaTextGenerated) { - this.captchaTextGenerated = captchaTextGenerated; + this.captchaTextGenerated = captchaTextGenerated; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ContactModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ContactModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ContactModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,7 +51,7 @@ * @return mail */ public String getMail() { - return mail; + return mail; } /** @@ -59,7 +59,7 @@ * @param mail mail */ public void setMail(String mail) { - this.mail = mail; + this.mail = mail; } /** @@ -67,7 +67,7 @@ * @return message */ public String getMessage() { - return message; + return message; } /** @@ -75,7 +75,7 @@ * @param message message */ public void setMessage(String message) { - this.message = message; + this.message = message; } /** @@ -83,7 +83,7 @@ * @return subject */ public String getSubject() { - return subject; + return subject; } /** @@ -91,6 +91,6 @@ * @param subject subject */ public void setSubject(String subject) { - this.subject = subject; + this.subject = subject; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/LoginModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/LoginModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/LoginModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -47,7 +47,7 @@ * @return password */ public String getPassword() { - return password; + return password; } /** @@ -55,7 +55,7 @@ * @param password password */ public void setPassword(String password) { - this.password = password; + this.password = password; } /** @@ -63,7 +63,7 @@ * @return rememberMe */ public Boolean getRememberMe() { - return rememberMe; + return rememberMe; } /** @@ -71,7 +71,7 @@ * @param rememberMe rememberMe */ public void setRememberMe(Boolean rememberMe) { - this.rememberMe = rememberMe; + this.rememberMe = rememberMe; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageCampagneModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageCampagneModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageCampagneModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -43,7 +43,7 @@ * @return complement */ public String getComplement() { - return complement; + return complement; } /** @@ -51,7 +51,7 @@ * @param complement complement */ public void setComplement(String complement) { - this.complement = complement; + this.complement = complement; } /** @@ -59,7 +59,7 @@ * @return selectedPersonne */ public Personne getSelectedPersonne() { - return selectedPersonne; + return selectedPersonne; } /** @@ -67,7 +67,7 @@ * @param selectedPersonne selectedPersonne */ public void setSelectedPersonne(Personne selectedPersonne) { - this.selectedPersonne = selectedPersonne; + this.selectedPersonne = selectedPersonne; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageStationModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageStationModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageStationModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -71,7 +71,7 @@ * @return latitudeDegrees */ public Integer getLatitudeDegrees() { - return latitudeDegrees; + return latitudeDegrees; } /** @@ -79,7 +79,7 @@ * @param latitudeDegrees latitudeDegrees */ public void setLatitudeDegrees(Integer latitudeDegrees) { - this.latitudeDegrees = latitudeDegrees; + this.latitudeDegrees = latitudeDegrees; } /** @@ -87,7 +87,7 @@ * @return latitudeMinutes */ public BigDecimal getLatitudeMinutes() { - return latitudeMinutes; + return latitudeMinutes; } /** @@ -95,7 +95,7 @@ * @param latitudeMinutes latitudeMinutes */ public void setLatitudeMinutes(BigDecimal latitudeMinutes) { - this.latitudeMinutes = latitudeMinutes; + this.latitudeMinutes = latitudeMinutes; } /** @@ -103,7 +103,7 @@ * @return latitudeOrientation */ public Character getLatitudeOrientation() { - return latitudeOrientation; + return latitudeOrientation; } /** @@ -111,7 +111,7 @@ * @param latitudeOrientation latitudeOrientation */ public void setLatitudeOrientation(Character latitudeOrientation) { - this.latitudeOrientation = latitudeOrientation; + this.latitudeOrientation = latitudeOrientation; } /** @@ -119,7 +119,7 @@ * @return longitudeDegrees */ public Integer getLongitudeDegrees() { - return longitudeDegrees; + return longitudeDegrees; } /** @@ -127,7 +127,7 @@ * @param longitudeDegrees longitudeDegrees */ public void setLongitudeDegrees(Integer longitudeDegrees) { - this.longitudeDegrees = longitudeDegrees; + this.longitudeDegrees = longitudeDegrees; } /** @@ -135,7 +135,7 @@ * @return longitudeMinutes */ public BigDecimal getLongitudeMinutes() { - return longitudeMinutes; + return longitudeMinutes; } /** @@ -143,7 +143,7 @@ * @param longitudeMinutes longitudeMinutes */ public void setLongitudeMinutes(BigDecimal longitudeMinutes) { - this.longitudeMinutes = longitudeMinutes; + this.longitudeMinutes = longitudeMinutes; } /** @@ -151,7 +151,7 @@ * @return longitudeOrientation */ public Character getLongitudeOrientation() { - return longitudeOrientation; + return longitudeOrientation; } /** @@ -159,7 +159,7 @@ * @param longitudeOrientation longitudeOrientation */ public void setLongitudeOrientation(Character longitudeOrientation) { - this.longitudeOrientation = longitudeOrientation; + this.longitudeOrientation = longitudeOrientation; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageUtilisateurModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageUtilisateurModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/ManageUtilisateurModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -55,7 +55,7 @@ * @return campagnesDroits */ public Map<Campagne, CampagnePersonneDroits> getCampagnesDroits() { - return campagnesDroits; + return campagnesDroits; } /** @@ -63,7 +63,7 @@ * @param campagnesDroits campagnesDroits */ public void setCampagnesDroits(Map<Campagne, CampagnePersonneDroits> campagnesDroits) { - this.campagnesDroits = campagnesDroits; + this.campagnesDroits = campagnesDroits; } /** @@ -71,7 +71,7 @@ * @return lotsDroits */ public Map<Lot, LotPersonneDroits> getLotsDroits() { - return lotsDroits; + return lotsDroits; } /** @@ -79,7 +79,7 @@ * @param lotsDroits lotsDroits */ public void setLotsDroits(Map<Lot, LotPersonneDroits> lotsDroits) { - this.lotsDroits = lotsDroits; + this.lotsDroits = lotsDroits; } /** @@ -87,7 +87,7 @@ * @return campagnes */ public List<Campagne> getCampagnes() { - return campagnes; + return campagnes; } /** @@ -95,7 +95,7 @@ * @return lots */ public List<Lot> getLots() { - return lots; + return lots; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/RegisterModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/RegisterModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/RegisterModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,7 +48,7 @@ * @return TRUE if it is valid */ public boolean validate() { - return password.equals(passwordConfirmation); + return password.equals(passwordConfirmation); } /** @@ -56,7 +56,7 @@ * @return password */ public String getPassword() { - return password; + return password; } /** @@ -64,7 +64,7 @@ * @param password password */ public void setPassword(String password) { - this.password = password; + this.password = password; } /** @@ -72,7 +72,7 @@ * @return passwordConfirmation */ public String getPasswordConfirmation() { - return passwordConfirmation; + return passwordConfirmation; } /** @@ -80,7 +80,7 @@ * @param passwordConfirmation passwordConfirmation */ public void setPasswordConfirmation(String passwordConfirmation) { - this.passwordConfirmation = passwordConfirmation; + this.passwordConfirmation = passwordConfirmation; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/UpdateUtilisateurModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/UpdateUtilisateurModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/model/UpdateUtilisateurModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,7 +58,7 @@ * @return TRUE if it is valid */ public boolean validate() { - return newPassword.equals(newPasswordConfirmation); + return newPassword.equals(newPasswordConfirmation); } /** @@ -66,7 +66,7 @@ * @return currentPassword */ public String getCurrentPassword() { - return currentPassword; + return currentPassword; } /** @@ -74,7 +74,7 @@ * @param currentPassword currentPassword */ public void setCurrentPassword(String currentPassword) { - this.currentPassword = currentPassword; + this.currentPassword = currentPassword; } /** @@ -82,7 +82,7 @@ * @return newPassword */ public String getNewPassword() { - return newPassword; + return newPassword; } /** @@ -90,7 +90,7 @@ * @param newPassword newPassword */ public void setNewPassword(String newPassword) { - this.newPassword = newPassword; + this.newPassword = newPassword; } /** @@ -98,7 +98,7 @@ * @return newPasswordConfirmation */ public String getNewPasswordConfirmation() { - return newPasswordConfirmation; + return newPasswordConfirmation; } /** @@ -106,7 +106,7 @@ * @param newPasswordConfirmation newPasswordConfirmation */ public void setNewPasswordConfirmation(String newPasswordConfirmation) { - this.newPasswordConfirmation = newPasswordConfirmation; + this.newPasswordConfirmation = newPasswordConfirmation; } /** @@ -114,7 +114,7 @@ * @return password */ public String getPassword() { - return password; + return password; } /** @@ -122,7 +122,7 @@ * @param password password */ public void setPassword(String password) { - this.password = password; + this.password = password; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/PersonneRenderer.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/PersonneRenderer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/PersonneRenderer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,6 +35,6 @@ /** {@inheritDoc} */ @Override public Object getDisplayValue(final Personne personne) { - return personne.getNom() + " " + personne.getPrenom(); + return personne.getNom() + " " + personne.getPrenom(); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/ProduitRenderer.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/ProduitRenderer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/pages/renderers/ProduitRenderer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -35,6 +35,6 @@ /** {@inheritDoc} */ @Override public Object getDisplayValue(final Produit produit) { - return produit.getRef(); + return produit.getRef(); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/CallerPage.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/CallerPage.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/CallerPage.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,9 +45,9 @@ * @param page Page class */ public CallerPage(Class<? extends TemplatePage> page) { - AssertTools.assertNotNull(page); - classPage = page; - instancePage = null; + AssertTools.assertNotNull(page); + classPage = page; + instancePage = null; } /** @@ -55,9 +55,9 @@ * @param page Page instance */ public CallerPage(TemplatePage page) { - AssertTools.assertNotNull(page); - classPage = null; - instancePage = page; + AssertTools.assertNotNull(page); + classPage = null; + instancePage = page; } /** @@ -66,9 +66,9 @@ * @param value Value */ public void addPageParameter(String key, Object value) { - if (instancePage != null) { - instancePage.getPageParameters().add(key, value); - } + if (instancePage != null) { + instancePage.getPageParameters().add(key, value); + } } /** @@ -76,10 +76,10 @@ * @param currentPage Current page */ public void responsePage(TemplatePage currentPage) { - if (classPage != null) { - currentPage.setResponsePage(classPage); - } else { - currentPage.setResponsePage(instancePage); - } + if (classPage != null) { + currentPage.setResponsePage(classPage); + } else { + currentPage.setResponsePage(instancePage); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/JSConfirmationBehavior.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/JSConfirmationBehavior.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/JSConfirmationBehavior.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,16 +51,16 @@ * @param message Confirmation message */ public JSConfirmationBehavior(String message) { - AssertTools.assertNotEmpty(message); - jsScript = String.format(JS_SCRIPT_TEMPLATE, message); + AssertTools.assertNotEmpty(message); + jsScript = String.format(JS_SCRIPT_TEMPLATE, message); } /** {@inheritDoc} */ @Override public void onComponentTag(Component component, ComponentTag tag) { - if (component instanceof Button || component instanceof Link<?>) { - tag.getAttributes().remove(JS_EVENT); - tag.getAttributes().put(JS_EVENT, jsScript); - } + if (component instanceof Button || component instanceof Link<?>) { + tag.getAttributes().remove(JS_EVENT); + tag.getAttributes().put(JS_EVENT, jsScript); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeEditorBehavior.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeEditorBehavior.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeEditorBehavior.java 2013-02-18 07:27:17 UTC (rev 119) @@ -49,51 +49,51 @@ * @param replaceModel replace model */ public MoleculeEditorBehavior(IModel<?> replaceModel) { - super("formula", replaceModel); + super("formula", replaceModel); } /** {@inheritDoc} */ @Override protected String newValue(String currentValue, String replacementValue) { - // on ajoute toujours un premier caractere pour oblige l'existance de - // l'attribut car sinon si formula est vide l'attribut n'est pas ajoute - String result = "."; - if (replacementValue != null) { - result += replacementValue; - } - return result; + // on ajoute toujours un premier caractere pour oblige l'existance de + // l'attribut car sinon si formula est vide l'attribut n'est pas ajoute + String result = "."; + if (replacementValue != null) { + result += replacementValue; + } + return result; } /** {@inheritDoc} */ @Override public void renderHead(Component component, IHeaderResponse response) { - response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/ChemDoodleWeb.css")); - response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/jquery-ui-1.9.2.custom.css")); - response.render(JavaScriptHeaderItem.forUrl("js/jquery-1.9.1.min.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-libs.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/jquery-ui-1.9.2.custom.min.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-sketcher.js")); - response.render(JavaScriptHeaderItem.forUrl("js/moleditor.js")); + response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/ChemDoodleWeb.css")); + response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/jquery-ui-1.9.2.custom.css")); + response.render(JavaScriptHeaderItem.forUrl("js/jquery-1.9.1.min.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-libs.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/jquery-ui-1.9.2.custom.min.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-sketcher.js")); + response.render(JavaScriptHeaderItem.forUrl("js/moleditor.js")); } /** {@inheritDoc} */ @Override public void beforeRender(Component component) { - // il faut que l'element HTML est forcement un identifiant pour pouvoir - // travailler avec - component.setOutputMarkupId(true); + // il faut que l'element HTML est forcement un identifiant pour pouvoir + // travailler avec + component.setOutputMarkupId(true); } /** {@inheritDoc} */ @Override public void afterRender(Component component) { - Response response = component.getResponse(); - final String id = component.getMarkupId(); + Response response = component.getResponse(); + final String id = component.getMarkupId(); - response.write(JavaScriptUtils.SCRIPT_OPEN_TAG); + response.write(JavaScriptUtils.SCRIPT_OPEN_TAG); - response.write("addEditorMolecule('"+id+"');"); - response.write(JavaScriptUtils.SCRIPT_CLOSE_TAG); + response.write("addEditorMolecule('" + id + "');"); + response.write(JavaScriptUtils.SCRIPT_CLOSE_TAG); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeViewBehavior.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeViewBehavior.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/MoleculeViewBehavior.java 2013-02-18 07:27:17 UTC (rev 119) @@ -55,9 +55,9 @@ * @param replaceModel replace model */ public MoleculeViewBehavior(IModel<?> replaceModel) { - this(replaceModel, 100, 100); + this(replaceModel, 100, 100); } - + /** * Constructor. * @@ -66,51 +66,51 @@ * @param height canvas height */ public MoleculeViewBehavior(IModel<?> replaceModel, int width, int height) { - super("formula", replaceModel); - this.width = width; - this.height = height; + super("formula", replaceModel); + this.width = width; + this.height = height; } /** {@inheritDoc} */ @Override protected String newValue(String currentValue, String replacementValue) { - // on ajoute toujours un premier caractere pour oblige l'existance de - // l'attribut car sinon si formula est vide le l'attribut n'est pas ajoute - String result = "."; - if (replacementValue != null) { - result += replacementValue; - } - return result; + // on ajoute toujours un premier caractere pour oblige l'existance de + // l'attribut car sinon si formula est vide le l'attribut n'est pas ajoute + String result = "."; + if (replacementValue != null) { + result += replacementValue; + } + return result; } /** {@inheritDoc} */ @Override public void renderHead(Component component, IHeaderResponse response) { - response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/ChemDoodleWeb.css")); - response.render(JavaScriptHeaderItem.forUrl("js/jquery-1.9.1.min.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-libs.js")); - response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb.js")); - response.render(JavaScriptHeaderItem.forUrl("js/molviewer.js")); + response.render(CssHeaderItem.forUrl("ChemDoodleWeb/css/ChemDoodleWeb.css")); + response.render(JavaScriptHeaderItem.forUrl("js/jquery-1.9.1.min.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb-libs.js")); + response.render(JavaScriptHeaderItem.forUrl("ChemDoodleWeb/js/ChemDoodleWeb.js")); + response.render(JavaScriptHeaderItem.forUrl("js/molviewer.js")); } /** {@inheritDoc} */ @Override public void beforeRender(Component component) { - // il faut que l'element HTML est forcement un identifiant pour pouvoir - // travailler avec - component.setOutputMarkupId(true); + // il faut que l'element HTML est forcement un identifiant pour pouvoir + // travailler avec + component.setOutputMarkupId(true); } /** {@inheritDoc} */ @Override public void afterRender(Component component) { - Response response = component.getResponse(); - String id = component.getMarkupId(); + Response response = component.getResponse(); + String id = component.getMarkupId(); - response.write(JavaScriptUtils.SCRIPT_OPEN_TAG); + response.write(JavaScriptUtils.SCRIPT_OPEN_TAG); - response.write("addViewerMolecule('"+id+"', " + width + "," + height + ");"); - response.write(JavaScriptUtils.SCRIPT_CLOSE_TAG); + response.write("addViewerMolecule('" + id + "', " + width + "," + height + ");"); + response.write(JavaScriptUtils.SCRIPT_CLOSE_TAG); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/ReplaceEmptyLabelBehavior.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/ReplaceEmptyLabelBehavior.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/behaviors/ReplaceEmptyLabelBehavior.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,10 +37,10 @@ /** {@inheritDoc} */ @Override public void beforeRender(Component component) { - super.bind(component); - if (component.getDefaultModelObject() == null) { - component.getResponse().write(NULL_PROPERTY); - } + super.bind(component); + if (component.getDefaultModelObject() == null) { + component.getResponse().write(NULL_PROPERTY); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/AjaxButtonPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/AjaxButtonPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/AjaxButtonPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,9 +53,9 @@ * @param altMessage Alternative message displayed when image can't be rendered */ public AjaxButtonPropertyColumn(Model<String> buttonLabel, Form<?> form) { - this(new Model<String>(), buttonLabel, form); + this(new Model<String>(), buttonLabel, form); } - + /** * Constructor * @param displayModel header display model @@ -64,16 +64,16 @@ * @param altMessage Alternative message displayed when image can't be rendered */ public AjaxButtonPropertyColumn(IModel<String> displayModel, Model<String> buttonLabel, Form<?> form) { - super(displayModel); - this.buttonLabel = buttonLabel; - this.form = form; + super(displayModel); + this.buttonLabel = buttonLabel; + this.form = form; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { - ButtonPanel panel = new ButtonPanel(item, componentId, model); - item.add(panel); + ButtonPanel panel = new ButtonPanel(item, componentId, model); + item.add(panel); } /** @@ -89,23 +89,23 @@ */ public class ButtonPanel extends Panel { - /** - * Constructor - * @param item Item - * @param componentId Component id - * @param model Model - */ - public ButtonPanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { - super(componentId); + /** + * Constructor + * @param item Item + * @param componentId Component id + * @param model Model + */ + public ButtonPanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { + super(componentId); - AjaxButton button = new AjaxButton("button", buttonLabel, form) { - @Override - protected void onSubmit(AjaxRequestTarget target, Form<?> form) { - AjaxButtonPropertyColumn.this.onSubmit(target, form, model); - } - }; + AjaxButton button = new AjaxButton("button", buttonLabel, form) { + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + AjaxButtonPropertyColumn.this.onSubmit(target, form, model); + } + }; - add(button); - } + add(button); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/BooleanPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/BooleanPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/BooleanPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,22 +54,22 @@ * @param page Page used to get True, False message */ public BooleanPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - TemplatePage page) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.page = page; + TemplatePage page) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.page = page; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, getDataModel(rowModel))); + cellItem.add(new Label(componentId, getDataModel(rowModel))); } /** {@inheritDoc} */ @Override public IModel<Object> getDataModel(final IModel<T> rowModel) { - IModel<Object> textModel = new DisplayBooleanPropertyModel(rowModel.getObject(), propertyExpression, page); - return textModel; + IModel<Object> textModel = new DisplayBooleanPropertyModel(rowModel.getObject(), propertyExpression, page); + return textModel; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/DecimalPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/DecimalPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/DecimalPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -60,24 +60,23 @@ * @param locale Locale used to format decimal */ public DecimalPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - DecimalDisplFormat format, Locale locale) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.format = format; - this.locale = locale; + DecimalDisplFormat format, Locale locale) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.format = format; + this.locale = locale; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, getDataModel(rowModel))); + cellItem.add(new Label(componentId, getDataModel(rowModel))); } /** {@inheritDoc} */ @Override public IModel<Object> getDataModel(IModel<T> rowModel) { - return new DisplayDecimalPropertyModel(rowModel.getObject(), propertyExpression, - format, locale); + return new DisplayDecimalPropertyModel(rowModel.getObject(), propertyExpression, format, locale); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/EnumPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/EnumPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/EnumPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,22 +53,21 @@ * @param propertyExpression Wicket property expression * @param page Page used to get enum messages */ - public EnumPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - TemplatePage page) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.page = page; + public EnumPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, TemplatePage page) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.page = page; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, getDataModel(rowModel))); + cellItem.add(new Label(componentId, getDataModel(rowModel))); } /** {@inheritDoc} */ @Override public IModel<Object> getDataModel(IModel<T> rowModel) { - return new DisplayEnumPropertyModel(rowModel.getObject(), propertyExpression, page); + return new DisplayEnumPropertyModel(rowModel.getObject(), propertyExpression, page); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -58,9 +58,9 @@ * @param popupSettings Popup setting */ public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - PopupSettings popupSettings) { - this(displayModel, sortProperty, propertyExpression); - this.popupSettings = popupSettings; + PopupSettings popupSettings) { + this(displayModel, sortProperty, propertyExpression); + this.popupSettings = popupSettings; } /** @@ -70,10 +70,9 @@ * @param propertyExpression Property expression * @param linkTitle Title displayed for the link */ - public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - String linkTitle) { - this(displayModel, sortProperty, propertyExpression); - this.linkTitle = linkTitle; + public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, String linkTitle) { + this(displayModel, sortProperty, propertyExpression); + this.linkTitle = linkTitle; } /** @@ -84,11 +83,11 @@ * @param linkTitle Title displayed for the link * @param popupSettings Popup setting */ - public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - String linkTitle, PopupSettings popupSettings) { - this(displayModel, sortProperty, propertyExpression); - this.linkTitle = linkTitle; - this.popupSettings = popupSettings; + public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, String linkTitle, + PopupSettings popupSettings) { + this(displayModel, sortProperty, propertyExpression); + this.linkTitle = linkTitle; + this.popupSettings = popupSettings; } /** @@ -97,8 +96,8 @@ * @param labelModel Label model */ public LinkPropertyColumn(IModel<String> displayModel, IModel<String> labelModel) { - super(displayModel, null); - this.labelModel = labelModel; + super(displayModel, null); + this.labelModel = labelModel; } /** @@ -108,7 +107,7 @@ * @param propertyExpression Property expression */ public LinkPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression) { - super(displayModel, sortProperty, propertyExpression); + super(displayModel, sortProperty, propertyExpression); } /** @@ -117,13 +116,13 @@ * @param propertyExpression Property expression */ public LinkPropertyColumn(IModel<String> displayModel, String propertyExpression) { - super(displayModel, propertyExpression); + super(displayModel, propertyExpression); } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { - item.add(new LinkPanel(item, componentId, model)); + item.add(new LinkPanel(item, componentId, model)); } /** @@ -139,36 +138,36 @@ */ public class LinkPanel extends Panel { - /** - * Constructor - * @param item Item - * @param componentId Component id - * @param model Model - */ - public LinkPanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { - super(componentId); + /** + * Constructor + * @param item Item + * @param componentId Component id + * @param model Model + */ + public LinkPanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { + super(componentId); - Link<T> link = new Link<T>("link") { + Link<T> link = new Link<T>("link") { - @Override - public void onClick() { - LinkPropertyColumn.this.onClick(item, componentId, model); - } - }; - link.setPopupSettings(popupSettings); - if (linkTitle != null) { - link.add(new AttributeModifier("title", new Model<String>(linkTitle))); - } + @Override + public void onClick() { + LinkPropertyColumn.this.onClick(item, componentId, model); + } + }; + link.setPopupSettings(popupSettings); + if (linkTitle != null) { + link.add(new AttributeModifier("title", new Model<String>(linkTitle))); + } - add(link); + add(link); - IModel<?> tmpLabelModel = labelModel; + IModel<?> tmpLabelModel = labelModel; - if (labelModel == null) { - tmpLabelModel = getDataModel(model); - } + if (labelModel == null) { + tmpLabelModel = getDataModel(model); + } - link.add(new Label("label", tmpLabelModel)); - } + link.add(new Label("label", tmpLabelModel)); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkableImagePropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkableImagePropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/LinkableImagePropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,9 +56,9 @@ * @param altMessage Alternative message displayed when image can't be rendered */ public LinkableImagePropertyColumn(String imageSrc, String linkTitle, String altMessage) { - this(new Model<String>(), imageSrc, linkTitle, altMessage); + this(new Model<String>(), imageSrc, linkTitle, altMessage); } - + /** * Constructor * @param displayModel header display model @@ -67,18 +67,18 @@ * @param altMessage Alternative message displayed when image can't be rendered */ public LinkableImagePropertyColumn(IModel<String> displayModel, String imageSrc, String linkTitle, String altMessage) { - super(displayModel); - this.imageSrc = imageSrc; - this.linkTitle = linkTitle; - this.altMessage = altMessage; + super(displayModel); + this.imageSrc = imageSrc; + this.linkTitle = linkTitle; + this.altMessage = altMessage; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> item, String componentId, IModel<T> model) { - LinkableImagePanel panel = new LinkableImagePanel(item, componentId, model); - panel.setVisibilityAllowed(isVisibleAllowed(model)); - item.add(panel); + LinkableImagePanel panel = new LinkableImagePanel(item, componentId, model); + panel.setVisibilityAllowed(isVisibleAllowed(model)); + item.add(panel); } /** @@ -87,7 +87,7 @@ * @return true if panel is visible */ protected boolean isVisibleAllowed(IModel<T> model) { - return true; + return true; } /** @@ -103,32 +103,32 @@ */ public class LinkableImagePanel extends Panel { - /** - * Constructor - * @param item Item - * @param componentId Component id - * @param model Model - */ - public LinkableImagePanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { - super(componentId); + /** + * Constructor + * @param item Item + * @param componentId Component id + * @param model Model + */ + public LinkableImagePanel(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> model) { + super(componentId); - Link<T> link = new Link<T>("link") { + Link<T> link = new Link<T>("link") { - @Override - public void onClick() { - LinkableImagePropertyColumn.this.onClick(item, componentId, model); - } - }; - if (linkTitle != null) { - link.add(new AttributeModifier("title", new Model<String>(linkTitle))); - } - ContextImage image = new ContextImage("image", new Model<String>(imageSrc)); - if (altMessage != null) { - image.add(new AttributeModifier("alt", new Model<String>(altMessage))); - } - link.add(image); + @Override + public void onClick() { + LinkableImagePropertyColumn.this.onClick(item, componentId, model); + } + }; + if (linkTitle != null) { + link.add(new AttributeModifier("title", new Model<String>(linkTitle))); + } + ContextImage image = new ContextImage("image", new Model<String>(imageSrc)); + if (altMessage != null) { + image.add(new AttributeModifier("alt", new Model<String>(altMessage))); + } + link.add(image); - add(link); - } + add(link); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/MapValuePropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/MapValuePropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/MapValuePropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,22 +56,21 @@ * @param map Applying map */ public MapValuePropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - Map<U, String> map) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.map = map; + Map<U, String> map) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.map = map; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, getDataModel(rowModel))); + cellItem.add(new Label(componentId, getDataModel(rowModel))); } /** {@inheritDoc} */ @Override public IModel<Object> getDataModel(IModel<T> rowModel) { - return new DisplayMapValuePropertyModel<U>(rowModel.getObject(), - propertyExpression, map); + return new DisplayMapValuePropertyModel<U>(rowModel.getObject(), propertyExpression, map); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/PercentPropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/PercentPropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/PercentPropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -53,18 +53,17 @@ * @param propertyExpression Wicket property expression * @param locale Locale used to format decimal */ - public PercentPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - Locale locale) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.locale = locale; + public PercentPropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, Locale locale) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.locale = locale; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, new DisplayPercentPropertyModel(rowModel.getObject(), propertyExpression, - locale))); + cellItem.add(new Label(componentId, new DisplayPercentPropertyModel(rowModel.getObject(), propertyExpression, + locale))); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/ShortDatePropertyColumn.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/ShortDatePropertyColumn.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/columns/ShortDatePropertyColumn.java 2013-02-18 07:27:17 UTC (rev 119) @@ -54,23 +54,21 @@ * @param propertyExpression Wicket property expression * @param locale Locale used to format decimal */ - public ShortDatePropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, - Locale locale) { - super(displayModel, sortProperty); - this.propertyExpression = propertyExpression; - this.locale = locale; + public ShortDatePropertyColumn(IModel<String> displayModel, S sortProperty, String propertyExpression, Locale locale) { + super(displayModel, sortProperty); + this.propertyExpression = propertyExpression; + this.locale = locale; } /** {@inheritDoc} */ @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { - cellItem.add(new Label(componentId, getDataModel(rowModel))); + cellItem.add(new Label(componentId, getDataModel(rowModel))); } /** {@inheritDoc} */ @Override public IModel<Object> getDataModel(IModel<T> rowModel) { - return new DisplayShortDatePropertyModel(rowModel.getObject(), propertyExpression, - locale); + return new DisplayShortDatePropertyModel(rowModel.getObject(), propertyExpression, locale); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/BigDecimalConverterImpl.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/BigDecimalConverterImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/BigDecimalConverterImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,30 +52,30 @@ /** {@inheritDoc} */ @Override public BigDecimal convertToObject(String value, Locale locale) { - if (value == null || value.trim().equals("")) { - return null; - } + if (value == null || value.trim().equals("")) { + return null; + } - if (locale == null) { - locale = Locale.getDefault(); - } + if (locale == null) { + locale = Locale.getDefault(); + } - try { - return NumberTools.parseBigDecimal(value, locale, DataContext.DECIMAL_SCALE, DataContext.DECIMAL_PRECISION - - DataContext.DECIMAL_SCALE); - } catch (RuntimeException e) { - throw new ConversionException(e); - } + try { + return NumberTools.parseBigDecimal(value, locale, DataContext.DECIMAL_SCALE, DataContext.DECIMAL_PRECISION + - DataContext.DECIMAL_SCALE); + } catch (RuntimeException e) { + throw new ConversionException(e); + } } /** {@inheritDoc} */ public String convertToString(final BigDecimal value, Locale locale) { - try { - return NumberTools.bigDecimalToString(value, locale, DECIMAL_MIN_FRACTION_DIGIT, DataContext.DECIMAL_SCALE, - DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); - } catch (RuntimeException e) { - throw new ConversionException(e); - } + try { + return NumberTools.bigDecimalToString(value, locale, DECIMAL_MIN_FRACTION_DIGIT, DataContext.DECIMAL_SCALE, + DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); + } catch (RuntimeException e) { + throw new ConversionException(e); + } } /** @@ -83,6 +83,6 @@ */ @Override protected Class<BigDecimal> getTargetType() { - return BigDecimal.class; + return BigDecimal.class; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/DoubleConverterImpl.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/DoubleConverterImpl.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/converters/DoubleConverterImpl.java 2013-02-18 07:27:17 UTC (rev 119) @@ -48,30 +48,30 @@ /** {@inheritDoc} */ @Override public Double convertToObject(String value, Locale locale) { - if (value == null || value.trim().equals("")) { - return null; - } + if (value == null || value.trim().equals("")) { + return null; + } - if (locale == null) { - locale = Locale.getDefault(); - } + if (locale == null) { + locale = Locale.getDefault(); + } - try { - return NumberTools.parseDouble(value, locale, WebContext.DOUBLE_MAX_FRACTION_DIGIT); - } catch (Exception e) { - throw new ConversionException(e); - } + try { + return NumberTools.parseDouble(value, locale, WebContext.DOUBLE_MAX_FRACTION_DIGIT); + } catch (Exception e) { + throw new ConversionException(e); + } } /** {@inheritDoc} */ @Override public String convertToString(final Double value, Locale locale) { - try { - return NumberTools.doubleToString(value, locale, DECIMAL_MIN_FRACTION_DIGIT, - WebContext.DOUBLE_MAX_FRACTION_DIGIT); - } catch (Exception e) { - throw new ConversionException(e); - } + try { + return NumberTools.doubleToString(value, locale, DECIMAL_MIN_FRACTION_DIGIT, + WebContext.DOUBLE_MAX_FRACTION_DIGIT); + } catch (Exception e) { + throw new ConversionException(e); + } } /** @@ -79,7 +79,7 @@ */ @Override protected Class<Double> getTargetType() { - return Double.class; + return Double.class; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/data/TableExportToolbar.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/data/TableExportToolbar.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/data/TableExportToolbar.java 2013-02-18 07:27:17 UTC (rev 119) @@ -40,25 +40,25 @@ public class TableExportToolbar extends ExportToolbar { public TableExportToolbar(DataTable<?, ?> table, String fileName, Locale locale) { - super(table); + super(table); - // set message model - setMessageModel(new Model<String>(getString("ExportTo"))); + // set message model + setMessageModel(new Model<String>(getString("ExportTo"))); - // file name model - DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH_mm-"); - String headerFilename = dateFormat.format(new Date()); - setFileNameModel(new Model<String>(headerFilename + fileName)); + // file name model + DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH_mm-"); + String headerFilename = dateFormat.format(new Date()); + setFileNameModel(new Model<String>(headerFilename + fileName)); - CSVDataExporter csvDataExporter = new CSVDataExporter(); - // configuration du separateur suivant la locale - // fr : ; - // en : , - if (Locale.FRENCH.equals(locale)) { - csvDataExporter.setDelimiter(';'); - } else { - csvDataExporter.setDelimiter(','); - } - addDataExporter(csvDataExporter); + CSVDataExporter csvDataExporter = new CSVDataExporter(); + // configuration du separateur suivant la locale + // fr : ; + // en : , + if (Locale.FRENCH.equals(locale)) { + csvDataExporter.setDelimiter(';'); + } else { + csvDataExporter.setDelimiter(','); + } + addDataExporter(csvDataExporter); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/AutoCompleteTextFieldString.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/AutoCompleteTextFieldString.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/AutoCompleteTextFieldString.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,14 +51,14 @@ * Comparison mode */ public enum ComparisonMode { - /** choice.contains(input) */ - CONTAINS, - /** choice.endsWith(input) */ - ENDS_WITH, - /** choice.equals(input) */ - EQUALS, - /** choice.startsWith(input) */ - STARTS_WITH; + /** choice.contains(input) */ + CONTAINS, + /** choice.endsWith(input) */ + ENDS_WITH, + /** choice.equals(input) */ + EQUALS, + /** choice.startsWith(input) */ + STARTS_WITH; } /** @@ -67,7 +67,7 @@ * @return Purged string (trim, lower case, no accent) */ private static String purgeString(String string) { - return new StringTransformer(string).trimToNull().replaceAccents().toLowerCase().toString(); + return new StringTransformer(string).trimToNull().replaceAccents().toLowerCase().toString(); } /** Choices (pairs of purge choice & choice) */ @@ -90,7 +90,7 @@ * @param mode Comparison mode */ public AutoCompleteTextFieldString(String id, IModel<String> model, List<String> choices, ComparisonMode mode) { - this(id, model, choices, mode, 0, Integer.MAX_VALUE); + this(id, model, choices, mode, 0, Integer.MAX_VALUE); } /** @@ -104,42 +104,42 @@ */ @SuppressWarnings("unchecked") public AutoCompleteTextFieldString(String id, IModel<String> model, List<String> choices, ComparisonMode mode, - int minLength, int maxChoices) { - super(id, model, StringAutoCompleteRenderer.INSTANCE); - AssertTools.assertNotNull(choices); - AssertTools.assertNotNull(mode); - AssertTools.assertNotNegative(minLength); - AssertTools.assertPositive(maxChoices); - this.choices = new ArrayList<Pair<String, String>>(); - for (String choice : choices) { - String purgeChoice = purgeString(choice); - if (purgeChoice != null && purgeChoice.length() >= minLength) { - this.choices.add(new Pair<String, String>(purgeChoice, choice)); - } - } - this.mode = mode; - this.minLength = minLength; - this.maxChoices = maxChoices; + int minLength, int maxChoices) { + super(id, model, StringAutoCompleteRenderer.INSTANCE); + AssertTools.assertNotNull(choices); + AssertTools.assertNotNull(mode); + AssertTools.assertNotNegative(minLength); + AssertTools.assertPositive(maxChoices); + this.choices = new ArrayList<Pair<String, String>>(); + for (String choice : choices) { + String purgeChoice = purgeString(choice); + if (purgeChoice != null && purgeChoice.length() >= minLength) { + this.choices.add(new Pair<String, String>(purgeChoice, choice)); + } + } + this.mode = mode; + this.minLength = minLength; + this.maxChoices = maxChoices; } /** {@inheritDoc} */ @Override protected Iterator<String> getChoices(String input) { - TreeSet<String> choicesList = new TreeSet<String>(); - String purgeInput = purgeString(input); - if (StringTools.length(purgeInput) >= minLength) { - Iterator<Pair<String, String>> i = choices.iterator(); - while (i.hasNext() && choicesList.size() < maxChoices) { - Pair<String, String> choice = i.next(); - if (mode == ComparisonMode.STARTS_WITH && choice.getKey().startsWith(purgeInput) - || mode == ComparisonMode.CONTAINS && choice.getKey().contains(purgeInput) - || mode == ComparisonMode.ENDS_WITH && choice.getKey().endsWith(purgeInput) - || mode == ComparisonMode.EQUALS && choice.getKey().equals(purgeInput)) { - choicesList.add(choice.getValue()); - } - } - } - return choicesList.iterator(); + TreeSet<String> choicesList = new TreeSet<String>(); + String purgeInput = purgeString(input); + if (StringTools.length(purgeInput) >= minLength) { + Iterator<Pair<String, String>> i = choices.iterator(); + while (i.hasNext() && choicesList.size() < maxChoices) { + Pair<String, String> choice = i.next(); + if (mode == ComparisonMode.STARTS_WITH && choice.getKey().startsWith(purgeInput) + || mode == ComparisonMode.CONTAINS && choice.getKey().contains(purgeInput) + || mode == ComparisonMode.ENDS_WITH && choice.getKey().endsWith(purgeInput) + || mode == ComparisonMode.EQUALS && choice.getKey().equals(purgeInput)) { + choicesList.add(choice.getValue()); + } + } + } + return choicesList.iterator(); } /** @@ -147,10 +147,10 @@ * @param choice The choice to add */ public void addChoice(String choice) { - String purgeChoice = purgeString(choice); - if (purgeChoice != null && purgeChoice.length() >= minLength) { - this.choices.add(new Pair<String, String>(purgeChoice, choice)); - } + String purgeChoice = purgeString(choice); + if (purgeChoice != null && purgeChoice.length() >= minLength) { + this.choices.add(new Pair<String, String>(purgeChoice, choice)); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButton.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButton.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButton.java 2013-02-18 07:27:17 UTC (rev 119) @@ -52,10 +52,10 @@ * @param specificMsgPage Page wich provide error messages */ public SubmittableButton(String id, Class<? extends TemplatePage> specificMsgPage, - SubmittableButtonEvents submittable) { - super(id); - this.submittable = submittable; - this.specificMsgPage = specificMsgPage; + SubmittableButtonEvents submittable) { + super(id); + this.submittable = submittable; + this.specificMsgPage = specificMsgPage; } /** @@ -65,8 +65,8 @@ * @param submittable Submittable */ public SubmittableButton(String id, IModel<String> model, SubmittableButtonEvents submittable) { - super(id, model); - this.submittable = submittable; + super(id, model); + this.submittable = submittable; } /** @@ -75,35 +75,35 @@ * @param submittable Submittable */ public SubmittableButton(String id, SubmittableButtonEvents submittable) { - super(id); - this.submittable = submittable; + super(id); + this.submittable = submittable; } /** {@inheritDoc} */ @Override public void onSubmit() { - submittable.onValidate(); + submittable.onValidate(); - if (!getPage().hasErrorMessage()) { - try { - submittable.onProcess(); - } catch (UnexpectedException e) { - throw e; - } catch (RuntimeException e) { - LOG.error(e.getMessage(), e); - throw e; - } catch (Exception e) { - if (specificMsgPage == null) { - ((TemplatePage) getPage()).errorCurrentPage(getId(), e); - } else { - ((TemplatePage) getPage()).errorCurrentPage(specificMsgPage, getId(), e); - } - } - } - if (getPage().hasErrorMessage()) { - submittable.onError(); - } else { - submittable.onSuccess(); - } + if (!getPage().hasErrorMessage()) { + try { + submittable.onProcess(); + } catch (UnexpectedException e) { + throw e; + } catch (RuntimeException e) { + LOG.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + if (specificMsgPage == null) { + ((TemplatePage) getPage()).errorCurrentPage(getId(), e); + } else { + ((TemplatePage) getPage()).errorCurrentPage(specificMsgPage, getId(), e); + } + } + } + if (getPage().hasErrorMessage()) { + submittable.onError(); + } else { + submittable.onSuccess(); + } } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButtonEvents.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButtonEvents.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/forms/SubmittableButtonEvents.java 2013-02-18 07:27:17 UTC (rev 119) @@ -36,7 +36,7 @@ * (3) Action to perform on process error. For example, reset some form fields. */ public void onError() { - // Nothing to do (by default) + // Nothing to do (by default) } /** @@ -54,6 +54,6 @@ * (1) Action to perform on validate. For example, validate the form model. */ public void onValidate() { - // Nothing to do (by default) + // Nothing to do (by default) } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayBooleanPropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayBooleanPropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayBooleanPropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -37,6 +37,7 @@ /** true string */ private static final String TRUE_KEY = "Boolean.true"; + /** false string */ private static final String FALSE_KEY = "Boolean.false"; @@ -47,14 +48,14 @@ * @param page p */ public DisplayBooleanPropertyModel(Object modelObject, String expression, TemplatePage page) { - super(modelObject, expression); - this.page = page; + super(modelObject, expression); + this.page = page; } /** {@inheritDoc} */ @Override public String getObject() { - return booleanValueMessage((Boolean) super.getObject()); + return booleanValueMessage((Boolean) super.getObject()); } /** @@ -63,13 +64,13 @@ * @return The associated message, null if the Boolean is null */ private final String booleanValueMessage(Boolean boolValue) { - if (boolValue == null) { - return null; - } - if (boolValue) { - return page.getString(TRUE_KEY); - } else { - return page.getString(FALSE_KEY); - } + if (boolValue == null) { + return null; + } + if (boolValue) { + return page.getString(TRUE_KEY); + } else { + return page.getString(FALSE_KEY); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayDecimalPropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayDecimalPropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayDecimalPropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -38,10 +38,10 @@ /** Format to display decimal */ public enum DecimalDisplFormat { - /** Small format, use the NB_DECIMAL_SMALL_FORMAT defined in the class **/ - SMALL, - /** Large format, use the max number of decimal configured in the application **/ - LARGE + /** Small format, use the NB_DECIMAL_SMALL_FORMAT defined in the class **/ + SMALL, + /** Large format, use the max number of decimal configured in the application **/ + LARGE } /** Number of decimal displayed for small number **/ @@ -61,15 +61,15 @@ * @param locale locale */ public DisplayDecimalPropertyModel(Object modelObject, String expression, DecimalDisplFormat format, Locale locale) { - super(modelObject, expression); - this.format = format; - this.locale = locale; + super(modelObject, expression); + this.format = format; + this.locale = locale; } /** {@inheritDoc} */ @Override public Object getObject() { - return formatDecimalValue((Number) super.getObject()); + return formatDecimalValue((Number) super.getObject()); } /** @@ -77,19 +77,19 @@ * @return the format */ private final NumberFormat getDecimalFormat() { - int numberOfDec = format == DecimalDisplFormat.SMALL ? NB_DECIMAL_SMALL : DataContext.DECIMAL_SCALE; + int numberOfDec = format == DecimalDisplFormat.SMALL ? NB_DECIMAL_SMALL : DataContext.DECIMAL_SCALE; - NumberFormat fmt = NumberFormat.getNumberInstance(locale); + NumberFormat fmt = NumberFormat.getNumberInstance(locale); - fmt.setMaximumIntegerDigits(DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); + fmt.setMaximumIntegerDigits(DataContext.DECIMAL_PRECISION - DataContext.DECIMAL_SCALE); - fmt.setMaximumFractionDigits(numberOfDec); - // affichage obligatoire des chiffres après la virgule - fmt.setMinimumFractionDigits(numberOfDec); + fmt.setMaximumFractionDigits(numberOfDec); + // affichage obligatoire des chiffres après la virgule + fmt.setMinimumFractionDigits(numberOfDec); - fmt.setRoundingMode(RoundingMode.HALF_UP); + fmt.setRoundingMode(RoundingMode.HALF_UP); - return fmt; + return fmt; } /** @@ -98,10 +98,10 @@ * @return The string who represent the decimal value, null if the decimal value is null */ private final String formatDecimalValue(Number decimalValue) { - if (decimalValue == null) { - return null; - } - return getDecimalFormat().format(decimalValue); + if (decimalValue == null) { + return null; + } + return getDecimalFormat().format(decimalValue); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayEnumPropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayEnumPropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayEnumPropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,9 +45,9 @@ * @param page p */ public DisplayEnumPropertyModel(Object modelObject, String expression, TemplatePage page) { - super(modelObject, expression); - this.pattern = TemplatePage.PATTERN_ENUM_VALUE_LABEL; - this.page = page; + super(modelObject, expression); + this.pattern = TemplatePage.PATTERN_ENUM_VALUE_LABEL; + this.page = page; } /** @@ -56,7 +56,7 @@ */ @Override public String getObject() { - return enumValueMessage(super.getObject()); + return enumValueMessage(super.getObject()); } /** @@ -66,10 +66,10 @@ * @return Enum value message */ private final <E extends Enum<?>> String enumValueMessage(Object enumValue) { - if (enumValue == null) { - return null; - } - String enumValueMessage = String.format(pattern, enumValue.getClass().getSimpleName(), enumValue.toString()); - return page.getString(enumValueMessage); + if (enumValue == null) { + return null; + } + String enumValueMessage = String.format(pattern, enumValue.getClass().getSimpleName(), enumValue.toString()); + return page.getString(enumValueMessage); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayMapValuePropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayMapValuePropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayMapValuePropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,14 +44,14 @@ * @param map Applying map */ public DisplayMapValuePropertyModel(Object modelObject, String expression, Map<T, String> map) { - super(modelObject, expression); - this.map = map; + super(modelObject, expression); + this.map = map; } /** {@inheritDoc} */ @Override public String getObject() { - return map.get(super.getObject()); + return map.get(super.getObject()); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayPercentPropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayPercentPropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayPercentPropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -46,14 +46,14 @@ * @param locale locale */ public DisplayPercentPropertyModel(Object modelObject, String expression, Locale locale) { - super(modelObject, expression); - this.locale = locale; + super(modelObject, expression); + this.locale = locale; } /** {@inheritDoc} */ @Override public String getObject() { - return formatPercentValue((Number) super.getObject()); + return formatPercentValue((Number) super.getObject()); } /** @@ -62,10 +62,10 @@ * @return The string who represent the purcent, null if the purcent value is null */ private final String formatPercentValue(Number percentValue) { - if (percentValue == null) { - return null; - } - return this.getPercentFormat().format(percentValue); + if (percentValue == null) { + return null; + } + return this.getPercentFormat().format(percentValue); } /** @@ -73,10 +73,10 @@ * @return the format */ private final NumberFormat getPercentFormat() { - // pourcents with two digits after the point - NumberFormat percentFormat = NumberFormat.getPercentInstance(locale); - percentFormat.setMaximumFractionDigits(WebContext.PERCENT_PRECISION); - return percentFormat; + // pourcents with two digits after the point + NumberFormat percentFormat = NumberFormat.getPercentInstance(locale); + percentFormat.setMaximumFractionDigits(WebContext.PERCENT_PRECISION); + return percentFormat; } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayShortDatePropertyModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayShortDatePropertyModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/DisplayShortDatePropertyModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -44,14 +44,14 @@ * @param locale l */ public DisplayShortDatePropertyModel(Object modelObject, String expression, Locale locale) { - super(modelObject, expression); - this.locale = locale; + super(modelObject, expression); + this.locale = locale; } /** {@inheritDoc} */ @Override public String getObject() { - return formatShortDateValue((Date) super.getObject()); + return formatShortDateValue((Date) super.getObject()); } /** @@ -60,10 +60,10 @@ * @return The string who represent the date, null if the date is null */ private final String formatShortDateValue(Date dateValue) { - if (dateValue == null) { - return null; - } - return getShortDateFormat().format(dateValue); + if (dateValue == null) { + return null; + } + return getShortDateFormat().format(dateValue); } /** @@ -71,7 +71,7 @@ * @return the format */ private final DateFormat getShortDateFormat() { - return DateFormat.getDateInstance(DateFormat.SHORT, locale); + return DateFormat.getDateInstance(DateFormat.SHORT, locale); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/GenericLoadableDetachableModel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/GenericLoadableDetachableModel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/GenericLoadableDetachableModel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -63,11 +63,11 @@ * @param modelID Model ID */ public GenericLoadableDetachableModel(Class<M> modelClass, Serializable modelID) { - AssertTools.assertNotNull(modelClass); - AssertTools.assertNotNull(modelID); - this.modelClass = modelClass; - this.modelID = modelID; - WebApplicationImpl.injectSpringBeans(this); + AssertTools.assertNotNull(modelClass); + AssertTools.assertNotNull(modelID); + this.modelClass = modelClass; + this.modelID = modelID; + WebApplicationImpl.injectSpringBeans(this); } /** @@ -76,20 +76,20 @@ */ @SuppressWarnings("unchecked") public GenericLoadableDetachableModel(M model) { - this((Class<M>) model.getClass(), model.getIdValue()); - setObject(model); + this((Class<M>) model.getClass(), model.getIdValue()); + setObject(model); } /** {@inheritDoc} */ @Override protected M load() { - try { - // LOG.debug("chargement LOAD, " + modelClass + "- id : " + modelID); - return dao.read(modelClass, modelID); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } + try { + // LOG.debug("chargement LOAD, " + modelClass + "- id : " + modelID); + return dao.read(modelClass, modelID); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/LoadableDetachableSortableListDataProvider.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/LoadableDetachableSortableListDataProvider.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/LoadableDetachableSortableListDataProvider.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,7 +51,8 @@ * @param <T> Model object type * @param <S> the type of the sort property */ -public final class LoadableDetachableSortableListDataProvider<M extends AbstractModel> extends SortableDataProvider<M, String> { +public final class LoadableDetachableSortableListDataProvider<M extends AbstractModel> extends + SortableDataProvider<M, String> { /** Logger */ private static final Logger LOG = LoggerFactory.getLogger(LoadableDetachableSortableListDataProvider.class); @@ -78,64 +79,64 @@ */ @SuppressWarnings("unchecked") public LoadableDetachableSortableListDataProvider(List<M> list, Locale locale) { - AssertTools.assertNotNull(list); - AssertTools.assertIn(locale, DataContext.LOCALES); - this.list = list; - this.locale = locale; - comparator = new NullComparator(true); + AssertTools.assertNotNull(list); + AssertTools.assertIn(locale, DataContext.LOCALES); + this.list = list; + this.locale = locale; + comparator = new NullComparator(true); } /** {@inheritDoc} */ @Override public Iterator<? extends M> iterator(long first, long count) { - if (getSort() != null && !StringUtils.isEmpty(getSort().getProperty())) { - Collections.sort(list, new Comparator<M>() { - @Override - public int compare(M o1, M o2) { - try { - Comparable<? extends Object> c1; - Object c2; - c1 = GenericsTools.cast(BeanTools.getValueFromPath(o1, AccessType.GETTER, getSort() - .getProperty())); + if (getSort() != null && !StringUtils.isEmpty(getSort().getProperty())) { + Collections.sort(list, new Comparator<M>() { + @Override + public int compare(M o1, M o2) { + try { + Comparable<? extends Object> c1; + Object c2; + c1 = GenericsTools.cast(BeanTools.getValueFromPath(o1, AccessType.GETTER, getSort() + .getProperty())); - c2 = GenericsTools.cast(BeanTools.getValueFromPath(o2, AccessType.GETTER, getSort() - .getProperty())); + c2 = GenericsTools.cast(BeanTools.getValueFromPath(o2, AccessType.GETTER, getSort() + .getProperty())); - // Exceptions - // Countries are sorted by country name, not by country code - if (getSort().getProperty().endsWith(CODE_PAYS_PROPERTY)) { - if (c1 != null) { - c1 = WebContext.COUNTRIES.get(locale).get(c1); - } - if (c2 != null) { - c2 = WebContext.COUNTRIES.get(locale).get(c2); - } - } + // Exceptions + // Countries are sorted by country name, not by country code + if (getSort().getProperty().endsWith(CODE_PAYS_PROPERTY)) { + if (c1 != null) { + c1 = WebContext.COUNTRIES.get(locale).get(c1); + } + if (c2 != null) { + c2 = WebContext.COUNTRIES.get(locale).get(c2); + } + } - return (getSort().isAscending() ? 1 : -1) * comparator.compare(c1, c2); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - } - }); - } + return (getSort().isAscending() ? 1 : -1) * comparator.compare(c1, c2); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + } + }); + } - return list.subList((int)first, (int)Math.min(first + count, size())).iterator(); + return list.subList((int) first, (int) Math.min(first + count, size())).iterator(); } /** {@inheritDoc} */ @Override public GenericLoadableDetachableModel<M> model(M object) { - // return new Model<M>(object); - return new GenericLoadableDetachableModel<M>(object); + // return new Model<M>(object); + return new GenericLoadableDetachableModel<M>(object); } /** {@inheritDoc} */ @Override public long size() { - return list.size(); + return list.size(); } /** @@ -143,7 +144,7 @@ * @return list */ public List<M> getList() { - return list; + return list; } /** @@ -151,7 +152,7 @@ * @param list list */ public void setList(List<M> list) { - this.list = list; + this.list = list; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/SimpleSortableListDataProvider.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/SimpleSortableListDataProvider.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/models/SimpleSortableListDataProvider.java 2013-02-18 07:27:17 UTC (rev 119) @@ -78,70 +78,74 @@ */ @SuppressWarnings("unchecked") public SimpleSortableListDataProvider(List<M> list, Locale locale) { - AssertTools.assertNotNull(list); - AssertTools.assertIn(locale, DataContext.LOCALES); - this.list = list; - this.locale = locale; - comparator = new NullComparator(true); + AssertTools.assertNotNull(list); + AssertTools.assertIn(locale, DataContext.LOCALES); + this.list = list; + this.locale = locale; + comparator = new NullComparator(true); } /** {@inheritDoc} */ @Override public Iterator<M> iterator(long first, long count) { - if (getSort() != null && !StringUtils.isEmpty(getSort().getProperty())) { - Collections.sort(list, new Comparator<M>() { - @Override - public int compare(M o1, M o2) { - try { - Comparable<? extends Object> c1; - Object c2; - c1 = GenericsTools.cast(BeanTools.getValueFromPath(o1, AccessType.GETTER, getSort() - .getProperty())); + if (getSort() != null && !StringUtils.isEmpty(getSort().getProperty())) { + Collections.sort(list, new Comparator<M>() { + @Override + public int compare(M o1, M o2) { + try { + Comparable<? extends Object> c1; + Object c2; + c1 = GenericsTools.cast(BeanTools.getValueFromPath(o1, AccessType.GETTER, getSort() + .getProperty())); - c2 = GenericsTools.cast(BeanTools.getValueFromPath(o2, AccessType.GETTER, getSort() - .getProperty())); + c2 = GenericsTools.cast(BeanTools.getValueFromPath(o2, AccessType.GETTER, getSort() + .getProperty())); - // Exceptions - // Countries are sorted by country name, not by country code - if (getSort().getProperty().endsWith(CODE_PAYS_PROPERTY)) { - if (c1 != null) { - c1 = WebContext.COUNTRIES.get(locale).get(c1); - } - if (c2 != null) { - c2 = WebContext.COUNTRIES.get(locale).get(c2); - } - } + // Exceptions + // Countries are sorted by country name, not by country code + if (getSort().getProperty().endsWith(CODE_PAYS_PROPERTY)) { + if (c1 != null) { + c1 = WebContext.COUNTRIES.get(locale).get(c1); + } + if (c2 != null) { + c2 = WebContext.COUNTRIES.get(locale).get(c2); + } + } - return (getSort().isAscending() ? 1 : -1) * comparator.compare(c1, c2); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new UnexpectedException(e); - } - } - }); - } + return (getSort().isAscending() ? 1 : -1) * comparator.compare(c1, c2); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + throw new UnexpectedException(e); + } + } + }); + } - return list.subList((int)first, (int)Math.min(first + count, size())).iterator(); + return list.subList((int) first, (int) Math.min(first + count, size())).iterator(); } /** {@inheritDoc} */ @Override public IModel<M> model(final M object) { - // return new Model<M>(object); - return new IModel<M>(){ - public M getObject() { - return object; - } - public void setObject(M t) {} - public void detach() {} - }; + // return new Model<M>(object); + return new IModel<M>() { + public M getObject() { + return object; + } + + public void setObject(M t) { + } + + public void detach() { + } + }; } /** {@inheritDoc} */ @Override public long size() { - return list.size(); + return list.size(); } /** @@ -149,7 +153,7 @@ * @return list */ public List<M> getList() { - return list; + return list; } /** @@ -157,7 +161,7 @@ * @param list list */ public void setList(List<M> list) { - this.list = list; + this.list = list; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/CollapsiblePanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/CollapsiblePanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/CollapsiblePanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -56,37 +56,37 @@ * @param defaultOpen Is the default state open */ public CollapsiblePanel(String id, IModel<String> titleModel, boolean defaultOpen) { - super(id); - this.visible = defaultOpen; - innerPanel = getInnerPanel("innerPanel"); - innerPanel.setVisible(visible); - innerPanel.setOutputMarkupId(true); - innerPanel.setOutputMarkupPlaceholderTag(true); - add(innerPanel); + super(id); + this.visible = defaultOpen; + innerPanel = getInnerPanel("innerPanel"); + innerPanel.setVisible(visible); + innerPanel.setOutputMarkupId(true); + innerPanel.setOutputMarkupPlaceholderTag(true); + add(innerPanel); - final Image showHideImage = new Image("showHideIcon") { - private static final long serialVersionUID = 8638737301579767296L; + final Image showHideImage = new Image("showHideIcon") { + private static final long serialVersionUID = 8638737301579767296L; - @Override - public ResourceReference getImageResourceReference() { - return visible ? open : closed; - } - }; - showHideImage.setOutputMarkupId(true); - IndicatingAjaxLink<Void> showHideLink = new IndicatingAjaxLink<Void>("showHideLink") { - private static final long serialVersionUID = -1929927616508773911L; + @Override + public ResourceReference getImageResourceReference() { + return visible ? open : closed; + } + }; + showHideImage.setOutputMarkupId(true); + IndicatingAjaxLink<Void> showHideLink = new IndicatingAjaxLink<Void>("showHideLink") { + private static final long serialVersionUID = -1929927616508773911L; - @Override - public void onClick(AjaxRequestTarget target) { - visible = !visible; - innerPanel.setVisible(visible); - target.add(innerPanel); - target.add(showHideImage); - } - }; - showHideLink.add(showHideImage); - add(new Label("titlePanel", titleModel)); - add(showHideLink); + @Override + public void onClick(AjaxRequestTarget target) { + visible = !visible; + innerPanel.setVisible(visible); + target.add(innerPanel); + target.add(showHideImage); + } + }; + showHideLink.add(showHideImage); + add(new Label("titlePanel", titleModel)); + add(showHideLink); } /** Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -45,17 +45,17 @@ * @param linkModel model used to generate the link */ public PropertyLabelLinkPanel(String id, IModel<T> linkModel) { - super(id, linkModel); - link = new Link<T>("link") { + super(id, linkModel); + link = new Link<T>("link") { - @Override - public void onClick() { - PropertyLabelLinkPanel.this.onClick(); - } - }; - add(link); + @Override + public void onClick() { + PropertyLabelLinkPanel.this.onClick(); + } + }; + add(link); - link.add(new Label("label", linkModel)); + link.add(new Label("label", linkModel)); } /** @@ -65,11 +65,11 @@ * @param linkTitle title displayed for the link */ public PropertyLabelLinkPanel(String id, IModel<T> linkModel, String linkTitle) { - this(id, linkModel); + this(id, linkModel); - if (linkTitle != null) { - link.add(new AttributeModifier("title", new Model<String>(linkTitle))); - } + if (linkTitle != null) { + link.add(new AttributeModifier("title", new Model<String>(linkTitle))); + } } /** @@ -78,7 +78,7 @@ */ @SuppressWarnings("unchecked") public IModel<T> getModel() { - return (IModel<T>) getDefaultModel(); + return (IModel<T>) getDefaultModel(); } /** @@ -87,7 +87,7 @@ */ @SuppressWarnings("unchecked") public T getModelObject() { - return (T) getDefaultModelObject(); + return (T) getDefaultModelObject(); } /** Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkProduitPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkProduitPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/PropertyLabelLinkProduitPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -51,24 +51,24 @@ * @param produitModel model used to generate the link */ public PropertyLabelLinkProduitPanel(String id, final IModel<Produit> produitModel) { - super(id, produitModel); - link = new Link<Produit>("link") { + super(id, produitModel); + link = new Link<Produit>("link") { - @Override - public void onClick() { - if (produitModel.getObject().isExtrait()) { - Extrait extrait = (Extrait) produitModel.getObject(); - onClickIfExtrait(extrait); - } else { - // le produit est une fraction - Fraction fraction = (Fraction) produitModel.getObject(); - onClickIfFraction(fraction); - } - } - }; - add(link); + @Override + public void onClick() { + if (produitModel.getObject().isExtrait()) { + Extrait extrait = (Extrait) produitModel.getObject(); + onClickIfExtrait(extrait); + } else { + // le produit est une fraction + Fraction fraction = (Fraction) produitModel.getObject(); + onClickIfFraction(fraction); + } + } + }; + add(link); - link.add(new Label("label", produitModel)); + link.add(new Label("label", produitModel)); } /** @@ -78,17 +78,17 @@ * @param page page used to get messages */ public PropertyLabelLinkProduitPanel(String id, IModel<Produit> produitModel, TemplatePage page) { - this(id, produitModel); - if (produitModel.getObject() != null) { - String linkTitle; - // title différent suivant si le produit provient d'une extraction ou d'une purification - if (produitModel.getObject().isExtrait()) { - linkTitle = page.getString("ReadExtraction"); - } else { - linkTitle = page.getString("ReadPurification"); - } - link.add(new AttributeModifier("title", new Model<String>(linkTitle))); - } + this(id, produitModel); + if (produitModel.getObject() != null) { + String linkTitle; + // title différent suivant si le produit provient d'une extraction ou d'une purification + if (produitModel.getObject().isExtrait()) { + linkTitle = page.getString("ReadExtraction"); + } else { + linkTitle = page.getString("ReadPurification"); + } + link.add(new AttributeModifier("title", new Model<String>(linkTitle))); + } } /** @@ -97,7 +97,7 @@ */ @SuppressWarnings("unchecked") public final IModel<Produit> getModel() { - return (IModel<Produit>) getDefaultModel(); + return (IModel<Produit>) getDefaultModel(); } /** @@ -105,7 +105,7 @@ * @return model object */ public final Produit getModelObject() { - return (Produit) getDefaultModelObject(); + return (Produit) getDefaultModelObject(); } /** Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/SimpleTooltipPanel.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/SimpleTooltipPanel.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/panels/SimpleTooltipPanel.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,9 +42,9 @@ * @param messageModel Message Model displayed over the image */ public SimpleTooltipPanel(String id, IModel<?> messageModel) { - super(id); - WebComponent img = new Image("tooltip", new PackageResourceReference(SimpleTooltipPanel.class, "tooltip.png")); - img.add(new AttributeModifier("title", messageModel)); - add(img); + super(id); + WebComponent img = new Image("tooltip", new PackageResourceReference(SimpleTooltipPanel.class, "tooltip.png")); + img.add(new AttributeModifier("title", messageModel)); + add(img); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/EnumChoiceRenderer.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/EnumChoiceRenderer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/EnumChoiceRenderer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -43,18 +43,18 @@ * @param page Page */ public EnumChoiceRenderer(TemplatePage page) { - this.page = page; + this.page = page; } /** {@inheritDoc} */ @Override public String getDisplayValue(E enumValue) { - return page.enumValueMessage(enumValue); + return page.enumValueMessage(enumValue); } /** {@inheritDoc} */ @Override public String getIdValue(E enumValue, int index) { - return enumValue.toString(); + return enumValue.toString(); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/MapChoiceRenderer.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/MapChoiceRenderer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/renderers/MapChoiceRenderer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -43,18 +43,18 @@ * @param map Map */ public MapChoiceRenderer(Map<K, V> map) { - this.map = map; + this.map = map; } /** {@inheritDoc} */ @Override public V getDisplayValue(K object) { - return map.get(object); + return map.get(object); } /** {@inheritDoc} */ @Override public String getIdValue(K object, int index) { - return object != null ? object.toString() : null; + return object != null ? object.toString() : null; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/resources/WebMessages.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/resources/WebMessages.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/resources/WebMessages.java 2013-02-18 07:27:17 UTC (rev 119) @@ -47,24 +47,24 @@ * @param source Message source */ public WebMessages(MessageSourceAccessor source) { - AssertTools.assertNotNull(source); - this.source = source; + AssertTools.assertNotNull(source); + this.source = source; } /** {@inheritDoc} */ @Override public String loadStringResource(Class<?> clazz, String key, Locale locale, String style, String variation) { - try { - return source.getMessage(key, locale); - } catch (NoSuchMessageException e) { - return null; - } + try { + return source.getMessage(key, locale); + } catch (NoSuchMessageException e) { + return null; + } } /** {@inheritDoc} */ @Override public String loadStringResource(Component component, String key, Locale locale, String style, String variation) { - return component != null ? loadStringResource(component.getClass(), key, locale, null, null) : null; + return component != null ? loadStringResource(component.getClass(), key, locale, null, null) : null; } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthContainer.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthContainer.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthContainer.java 2013-02-18 07:27:17 UTC (rev 119) @@ -39,8 +39,8 @@ * @param roles Authorized roles */ public AuthContainer(String id, AuthRole... roles) { - super(id); - authorized = AuthStrategy.isAuthorized(roles); + super(id); + authorized = AuthStrategy.isAuthorized(roles); } /** @@ -48,13 +48,13 @@ * @return authorized */ public boolean isAuthorized() { - return authorized; + return authorized; } /** {@inheritDoc} */ @Override protected void onBeforeRender() { - setVisibilityAllowed(isAuthorized()); - super.onBeforeRender(); + setVisibilityAllowed(isAuthorized()); + super.onBeforeRender(); } } \ No newline at end of file Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthSession.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthSession.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthSession.java 2013-02-18 07:27:17 UTC (rev 119) @@ -69,18 +69,18 @@ * @param request Request */ public AuthSession(Request request) { - super(request); - WebApplicationImpl.injectSpringBeans(this); - if (!DataContext.LOCALES.contains(getLocale())) { - setLocale(Locale.getDefault()); - } - setAttribute(ATTRIBUTE_ROLE, new HashSet<TypeDroit>()); - setUtilisateur(null); + super(request); + WebApplicationImpl.injectSpringBeans(this); + if (!DataContext.LOCALES.contains(getLocale())) { + setLocale(Locale.getDefault()); + } + setAttribute(ATTRIBUTE_ROLE, new HashSet<TypeDroit>()); + setUtilisateur(null); - if (!autologin()) { - logout(); - } - bind(); + if (!autologin()) { + logout(); + } + bind(); } /** @@ -89,26 +89,26 @@ */ private boolean autologin() { - String[] cookie = WebApplication.get().getSecuritySettings().getAuthenticationStrategy().load(); - // cookie[0] = courriel, cookie[1] = passwordHash - if (cookie != null && cookie.length == 2 && !StringUtils.isEmpty(cookie[0]) && !StringUtils.isEmpty(cookie[1]) - && authenticate(cookie[0], cookie[1])) { - try { - // connexion without cookie persistance because already exists - connectUser(personneService.loadUtilisateur(cookie[0]), false); - } catch (DataNotFoundException e) { - // just in cas the user is deleted by another user between authenticate and plainLogin - return false; - } - return true; - } - return false; + String[] cookie = WebApplication.get().getSecuritySettings().getAuthenticationStrategy().load(); + // cookie[0] = courriel, cookie[1] = passwordHash + if (cookie != null && cookie.length == 2 && !StringUtils.isEmpty(cookie[0]) && !StringUtils.isEmpty(cookie[1]) + && authenticate(cookie[0], cookie[1])) { + try { + // connexion without cookie persistance because already exists + connectUser(personneService.loadUtilisateur(cookie[0]), false); + } catch (DataNotFoundException e) { + // just in cas the user is deleted by another user between authenticate and plainLogin + return false; + } + return true; + } + return false; } public boolean authenticate(String username, String password) { - boolean authenticate = personneService.authenticateUtilisateur(username, password); - LOG.debug(String.valueOf(authenticate)); - return authenticate; + boolean authenticate = personneService.authenticateUtilisateur(username, password); + LOG.debug(String.valueOf(authenticate)); + return authenticate; } /** @@ -116,7 +116,7 @@ * @return rememberMe */ public Boolean getRememberMe() { - return (Boolean) getAttribute(ATTRIBUTE_REMEMBER_ME); + return (Boolean) getAttribute(ATTRIBUTE_REMEMBER_ME); } /** @@ -124,7 +124,7 @@ * @return role */ public AuthRole getRole() { - return (AuthRole) getAttribute(ATTRIBUTE_ROLE); + return (AuthRole) getAttribute(ATTRIBUTE_ROLE); } /** @@ -132,19 +132,19 @@ * @return utilisateur */ public Utilisateur getUtilisateur() { - Integer idPersonne = (Integer) getAttribute(ATTRIBUTE_UTILISATEUR); - Utilisateur utilisateur = null; - if (idPersonne != null) { - try { - utilisateur = personneService.loadUtilisateur(idPersonne); - } catch (DataNotFoundException e) { - logout(); - } catch (Exception e) { - LOG.debug(e.getClass() + e.getMessage()); - return null; - } - } - return utilisateur; + Integer idPersonne = (Integer) getAttribute(ATTRIBUTE_UTILISATEUR); + Utilisateur utilisateur = null; + if (idPersonne != null) { + try { + utilisateur = personneService.loadUtilisateur(idPersonne); + } catch (DataNotFoundException e) { + logout(); + } catch (Exception e) { + LOG.debug(e.getClass() + e.getMessage()); + return null; + } + } + return utilisateur; } /** @@ -153,24 +153,24 @@ * @param rememberMe True if the authentication is saved in a cookie */ public void connectUser(Utilisateur utilisateur, boolean rememberMe) { - setUtilisateur(utilisateur); - setRole(utilisateur.getTypeDroit() == TypeDroit.UTILISATEUR ? AuthRole.USER : AuthRole.ADMIN); + setUtilisateur(utilisateur); + setRole(utilisateur.getTypeDroit() == TypeDroit.UTILISATEUR ? AuthRole.USER : AuthRole.ADMIN); - setRememberMe(rememberMe); - if (rememberMe) { - WebApplication.get().getSecuritySettings().getAuthenticationStrategy() - .save(utilisateur.getCourriel(), utilisateur.getPasswordHash()); - } + setRememberMe(rememberMe); + if (rememberMe) { + WebApplication.get().getSecuritySettings().getAuthenticationStrategy().save(utilisateur.getCourriel(), + utilisateur.getPasswordHash()); + } } /** * Logout action */ public void logout() { - setUtilisateur(null); - setRememberMe(false); - setRole(AuthRole.VISITOR); - WebApplication.get().getSecuritySettings().getAuthenticationStrategy().remove(); + setUtilisateur(null); + setRememberMe(false); + setRole(AuthRole.VISITOR); + WebApplication.get().getSecuritySettings().getAuthenticationStrategy().remove(); } /** @@ -178,7 +178,7 @@ * @param rememberMe RememberMe */ private void setRememberMe(Boolean rememberMe) { - setAttribute(ATTRIBUTE_REMEMBER_ME, rememberMe); + setAttribute(ATTRIBUTE_REMEMBER_ME, rememberMe); } /** @@ -186,7 +186,7 @@ * @param role Role */ private void setRole(AuthRole role) { - setAttribute(ATTRIBUTE_ROLE, role); + setAttribute(ATTRIBUTE_ROLE, role); } /** @@ -194,7 +194,7 @@ * @param utilisateur Utilisateur */ private void setUtilisateur(Utilisateur utilisateur) { - setAttribute(ATTRIBUTE_UTILISATEUR, utilisateur != null ? utilisateur.getIdPersonne() : null); + setAttribute(ATTRIBUTE_UTILISATEUR, utilisateur != null ? utilisateur.getIdPersonne() : null); } /** @@ -202,6 +202,6 @@ * @param utilisateur Utilisateur */ public void update(Utilisateur utilisateur) { - connectUser(utilisateur, getRememberMe()); + connectUser(utilisateur, getRememberMe()); } } Modified: trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthStrategy.java =================================================================== --- trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthStrategy.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/main/java/nc/ird/cantharella/web/utils/security/AuthStrategy.java 2013-02-18 07:27:17 UTC (rev 119) @@ -42,16 +42,16 @@ * @return TRUE if the personne is authorized or if authorizedRoles is null or empty */ public static boolean isAuthorized(AuthRole[] authorizedRoles) { - return authorizedRoles == null - || authorizedRoles.length == 0 - || new HashSet<AuthRole>(Arrays.asList(authorizedRoles)).contains(((AuthSession) Session.get()) - .getRole()); + return authorizedRoles == null + || authorizedRoles.length == 0 + || new HashSet<AuthRole>(Arrays.asList(authorizedRoles)).contains(((AuthSession) Session.get()) + .getRole()); } /** {@inheritDoc} */ @Override protected <P extends Page> boolean isPageAuthorized(Class<P> pageClass) { - AuthRoles roles = pageClass.getAnnotation(AuthRoles.class); - return roles == null || isAuthorized(roles.value()); + AuthRoles roles = pageClass.getAnnotation(AuthRoles.class); + return roles == null || isAuthorized(roles.value()); } } Modified: trunk/cantharella.web/src/test/java/nc/ird/cantharella/web/AbstractWebTest.java =================================================================== --- trunk/cantharella.web/src/test/java/nc/ird/cantharella/web/AbstractWebTest.java 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/cantharella.web/src/test/java/nc/ird/cantharella/web/AbstractWebTest.java 2013-02-18 07:27:17 UTC (rev 119) @@ -46,6 +46,6 @@ */ @Before public void setUp() { - applicationContext.getAutowireCapableBeanFactory().autowireBean(this); + applicationContext.getAutowireCapableBeanFactory().autowireBean(this); } } \ No newline at end of file Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2013-02-18 00:07:41 UTC (rev 118) +++ trunk/pom.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -107,6 +107,9 @@ <version.hibernate3-maven-plugin>3.0</version.hibernate3-maven-plugin> <version.maven-surefire-plugin>2.13</version.maven-surefire-plugin> <version.animal-sniffer-maven-plugin>1.10</version.animal-sniffer-maven-plugin> + <version.maven-dependency-plugin>2.6</version.maven-dependency-plugin> + <version.maven-java-formatter-plugin>0.3.1 </version.maven-java-formatter-plugin> + <version.maven-assembly-plugin>2.4</version.maven-assembly-plugin> <!-- dependency versions --> <version.junit>4.11</version.junit> @@ -126,7 +129,6 @@ <version.lucene>3.6.2</version.lucene> <version.c3p0>0.9.1</version.c3p0> <version.aspectj>1.7.1</version.aspectj> - <!--<version.javassist>3.8.0.GA</version.javassist>--> <version.spring>3.2.1.RELEASE</version.spring> <version.mail>1.4.6</version.mail> <version.backport-util-concurrent>3.1</version.backport-util-concurrent> @@ -179,8 +181,87 @@ </signature> </configuration> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <version>${version.maven-dependency-plugin}</version> + <executions> + <execution> + <id>unpack-code-formatter-conf</id> + <phase>process-resources</phase> + <goals> + <goal>unpack</goal> + </goals> + <configuration> + <artifactItems> + <artifactItem> + <groupId>nc.ird</groupId> + <artifactId>cantharella</artifactId> + <version>${project.version}</version> + <type>zip</type> + <classifier>code-formatter-conf</classifier> + <overWrite>true</overWrite> + <outputDirectory>${project.build.directory}</outputDirectory> + <includes>**/*.xml</includes> + </artifactItem> + </artifactItems> + <includes>**/*</includes> + <overWriteReleases>true</overWriteReleases> + <overWriteSnapshots>true</overWriteSnapshots> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.googlecode.maven-java-formatter-plugin</groupId> + <artifactId>maven-java-formatter-plugin</artifactId> + <version>${version.maven-java-formatter-plugin}</version> + <executions> + <execution> + <phase>process-resources</phase> + <goals> + <goal>format</goal> + </goals> + </execution> + </executions> + <configuration> + <!-- Use plugin to compiler config vice those in formatter config file --> + <overrideConfigCompilerVersion>true</overrideConfigCompilerVersion> + <compilerSource>${jdk.version}</compilerSource> + <compilerCompliance>${jdk.version}</compilerCompliance> + <compilerTargetPlatform>${jdk.version}</compilerTargetPlatform> + <!-- Use Unix line endings --> + <lineEnding>LF</lineEnding> + <!-- The formatter config file --> + <configFile>${project.build.directory}/code-format.xml</configFile> + </configuration> + </plugin> </plugins> + </pluginManagement> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <version>${version.maven-assembly-plugin}</version> + <inherited>false</inherited> + <configuration> + <descriptors> + <descriptor> + ${project.basedir}/assembly/code-formatter-conf.xml + </descriptor> + </descriptors> + </configuration> + <executions> + <execution> + <id>make-assembly</id> + <phase>package</phase> + <goals> + <goal>single</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> </build> <dependencyManagement> @@ -338,7 +419,7 @@ <artifactId>spring-context-support</artifactId> <version>${version.spring}</version> </dependency> - <dependency> + <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${version.spring}</version> Added: trunk/src/code-formatter-conf/code-format.xml =================================================================== --- trunk/src/code-formatter-conf/code-format.xml (rev 0) +++ trunk/src/code-formatter-conf/code-format.xml 2013-02-18 07:27:17 UTC (rev 119) @@ -0,0 +1,279 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<profiles version="11"> +<profile kind="CodeFormatterProfile" name="code_formatter" version="11"> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="8"/> +<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/> +<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="120"/> +<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/> +<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.5"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="mixed"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.compiler.source" value="1.5"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/> +<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.5"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/> +<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/> +<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/> +</profile> +</profiles>
participants (1)
-
acheype@users.forge.codelutin.com