From 49fa68d091176d5ee03ae790ac2510cead40eb6e Mon Sep 17 00:00:00 2001 From: Julian Cesar dos Santos Date: Thu, 22 Sep 2016 07:44:24 -0300 Subject: [PATCH] Proposta de estruturação dos projetos do framework JEE. --- README.md | 2 +- basic/.gitignore | 3 --- basic/pom.xml | 34 ---------------------------------- basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java | 51 --------------------------------------------------- basic/src/main/resources/demoiselle.properties | 1 - basic/src/main/resources/messages.properties | 1 - configuration/.gitignore | 3 --- configuration/pom.xml | 26 -------------------------- configuration/src/main/java/org/demoiselle/configuration/ConfigType.java | 26 -------------------------- configuration/src/main/java/org/demoiselle/configuration/Configuration.java | 115 ------------------------------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/configuration/ConfigurationException.java | 70 ---------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/configuration/ConfigurationInterceptor.java | 34 ---------------------------------- configuration/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java | 87 --------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationArrayValueExtractor.java | 63 --------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationClassValueExtractor.java | 70 ---------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationEnumValueExtractor.java | 92 -------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationLoader.java | 356 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationMapValueExtractor.java | 93 --------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationPrimitiveOrWrapperValueExtractor.java | 92 -------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationProxyTemplateImpl.java | 67 ------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationStringValueExtractor.java | 62 -------------------------------------------------------------- configuration/src/main/java/org/demoiselle/util/Reflections.java | 383 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/util/ResourceBundle.java | 140 -------------------------------------------------------------------------------------------------------------------------------------------- configuration/src/main/java/org/demoiselle/util/Strings.java | 289 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- configuration/src/main/resources/configuration-bundle.properties | 44 -------------------------------------------- core/.gitignore | 4 ---- core/pom.xml | 35 ----------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java | 56 -------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/Name.java | 98 -------------------------------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java | 96 ------------------------------------------------------------------------------------------------ core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java | 83 ----------------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/Type.java | 60 ------------------------------------------------------------ core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java | 70 ---------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java | 67 ------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java | 53 ----------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java | 71 ----------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/crud/package-info.java | 11 ----------- core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java | 49 ------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java | 45 --------------------------------------------- core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java | 75 --------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java | 30 ------------------------------ core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java | 115 ------------------------------------------------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java | 67 ------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/util/Reflections.java | 367 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java | 136 ---------------------------------------------------------------------------------------------------------------------------------------- core/src/main/java/org/demoiselle/jee/core/util/Strings.java | 300 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java | 36 ------------------------------------ core/src/main/java/org/demoiselle/jee/stereotype/Controller.java | 28 ---------------------------- core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java | 37 ------------------------------------- core/src/main/java/org/demoiselle/jee/stereotype/RestController.java | 36 ------------------------------------ core/src/main/resources/demoiselle.properties | 5 ----- core/src/main/resources/messages.properties | 81 --------------------------------------------------------------------------------- demoiselle-core/.gitignore | 5 +++++ demoiselle-core/pom.xml | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Name.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Type.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/crud/package-info.java | 11 +++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java | 30 ++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/messages/DemoiselleMessages.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Reflections.java | 367 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Strings.java | 300 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java | 36 ++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/Controller.java | 28 ++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java | 37 +++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/RestController.java | 36 ++++++++++++++++++++++++++++++++++++ demoiselle-core/src/main/resources/demoiselle.properties | 5 +++++ demoiselle-core/src/main/resources/messages.properties | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-persistence-jpa/.gitignore | 5 +++++ demoiselle-persistence-jpa/pom.xml | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-persistence-jpa/pom.xml~ | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/context/package-info.java | 11 +++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericCrudDAO.java | 166 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericDataPage.java | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/package-info.java | 11 +++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/DemoisellePersistenceException.java | 27 +++++++++++++++++++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/package-info.java | 11 +++++++++++ demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/interceptor/package-info.java | 11 +++++++++++ demoiselle-security-basic/.gitignore | 3 +++ demoiselle-security-basic/pom.xml | 34 ++++++++++++++++++++++++++++++++++ demoiselle-security-basic/pom.xml~ | 34 ++++++++++++++++++++++++++++++++++ demoiselle-security-basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security-basic/src/main/resources/demoiselle.properties | 1 + demoiselle-security-basic/src/main/resources/messages.properties | 1 + demoiselle-security-basic/target/classes/demoiselle.properties | 1 + demoiselle-security-basic/target/classes/messages.properties | 1 + demoiselle-security-jwt/.gitignore | 3 +++ demoiselle-security-jwt/pom.xml | 41 +++++++++++++++++++++++++++++++++++++++++ demoiselle-security-jwt/pom.xml~ | 41 +++++++++++++++++++++++++++++++++++++++++ demoiselle-security-jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security-jwt/src/main/resources/demoiselle.properties | 1 + demoiselle-security-jwt/src/main/resources/messages.properties | 1 + demoiselle-security-jwt/target/classes/demoiselle.properties | 1 + demoiselle-security-jwt/target/classes/messages.properties | 1 + demoiselle-security/.classpath | 31 +++++++++++++++++++++++++++++++ demoiselle-security/.gitignore | 1 + demoiselle-security/.project | 23 +++++++++++++++++++++++ demoiselle-security/.settings/org.eclipse.core.resources.prefs | 4 ++++ demoiselle-security/.settings/org.eclipse.jdt.core.prefs | 5 +++++ demoiselle-security/.settings/org.eclipse.m2e.core.prefs | 4 ++++ demoiselle-security/pom.xml | 29 +++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/LoggedUser.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/Token.java | 27 +++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java | 37 +++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-security/src/main/resources/messages.properties | 12 ++++++++++++ demoiselle-ws-jaxrs/.classpath | 27 +++++++++++++++++++++++++++ demoiselle-ws-jaxrs/.gitignore | 1 + demoiselle-ws-jaxrs/.project | 36 ++++++++++++++++++++++++++++++++++++ demoiselle-ws-jaxrs/.settings/org.eclipse.core.resources.prefs | 3 +++ demoiselle-ws-jaxrs/.settings/org.eclipse.jdt.core.prefs | 8 ++++++++ demoiselle-ws-jaxrs/.settings/org.eclipse.m2e.core.prefs | 4 ++++ demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.component | 5 +++++ demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.project.facet.core.xml | 5 +++++ demoiselle-ws-jaxrs/pom.xml | 40 ++++++++++++++++++++++++++++++++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/JaxRsFilter.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/crud/package-info.java | 11 +++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/DemoiselleRESTException.java | 41 +++++++++++++++++++++++++++++++++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/mapper/GenericExceptionMapper.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayload.java | 25 +++++++++++++++++++++++++ demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayloadInterceptor.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ jwt/.gitignore | 3 --- jwt/pom.xml | 47 ----------------------------------------------- jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java | 105 --------------------------------------------------------------------------------------------------------- jwt/src/main/resources/demoiselle.properties | 1 - jwt/src/main/resources/messages.properties | 1 - persistence/.gitignore | 4 ---- persistence/pom.xml | 56 -------------------------------------------------------- persistence/src/main/java/org/demoiselle/jee/persistence/context/package-info.java | 11 ----------- persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericCrudDAO.java | 166 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericDataPage.java | 95 ----------------------------------------------------------------------------------------------- persistence/src/main/java/org/demoiselle/jee/persistence/crud/package-info.java | 11 ----------- persistence/src/main/java/org/demoiselle/jee/persistence/exception/DemoisellePersistenceException.java | 27 --------------------------- persistence/src/main/java/org/demoiselle/jee/persistence/exception/package-info.java | 11 ----------- persistence/src/main/java/org/demoiselle/jee/persistence/interceptor/package-info.java | 11 ----------- pom.xml | 14 ++++++-------- security/.gitignore | 4 ---- security/pom.xml | 22 ---------------------- security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java | 75 --------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/LoggedUser.java | 67 ------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/Token.java | 27 --------------------------- security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java | 62 -------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java | 65 ----------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java | 65 ----------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java | 83 ----------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java | 72 ------------------------------------------------------------------------ security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java | 37 ------------------------------------- security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java | 80 -------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java | 60 ------------------------------------------------------------ security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java | 79 ------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java | 128 -------------------------------------------------------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java | 70 ---------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java | 144 ------------------------------------------------------------------------------------------------------------------------------------------------ security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java | 111 --------------------------------------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java | 66 ------------------------------------------------------------------ security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java | 116 -------------------------------------------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java | 57 --------------------------------------------------------- security/src/main/resources/messages.properties | 12 ------------ swagger/.gitignore | 3 --- swagger/pom.xml | 39 --------------------------------------- swagger/src/main/java/org/demoiselle/swagger/SwaggerProducer.java | 17 ----------------- ws/.gitignore | 4 ---- ws/pom.xml | 40 ---------------------------------------- ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java | 58 ---------------------------------------------------------- ws/src/main/java/org/demoiselle/jee/ws/crud/package-info.java | 11 ----------- ws/src/main/java/org/demoiselle/jee/ws/exception/DemoiselleRESTException.java | 37 ------------------------------------- ws/src/main/java/org/demoiselle/jee/ws/exception/mapper/GenericExceptionMapper.java | 62 -------------------------------------------------------------- ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayload.java | 25 ------------------------- ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayloadInterceptor.java | 62 -------------------------------------------------------------- 196 files changed, 4922 insertions(+), 6731 deletions(-) delete mode 100644 basic/.gitignore delete mode 100644 basic/pom.xml delete mode 100644 basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java delete mode 100644 basic/src/main/resources/demoiselle.properties delete mode 100644 basic/src/main/resources/messages.properties delete mode 100644 configuration/.gitignore delete mode 100644 configuration/pom.xml delete mode 100644 configuration/src/main/java/org/demoiselle/configuration/ConfigType.java delete mode 100644 configuration/src/main/java/org/demoiselle/configuration/Configuration.java delete mode 100644 configuration/src/main/java/org/demoiselle/configuration/ConfigurationException.java delete mode 100644 configuration/src/main/java/org/demoiselle/configuration/ConfigurationInterceptor.java delete mode 100644 configuration/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationArrayValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationClassValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationEnumValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationLoader.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationMapValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationPrimitiveOrWrapperValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationProxyTemplateImpl.java delete mode 100644 configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationStringValueExtractor.java delete mode 100644 configuration/src/main/java/org/demoiselle/util/Reflections.java delete mode 100644 configuration/src/main/java/org/demoiselle/util/ResourceBundle.java delete mode 100644 configuration/src/main/java/org/demoiselle/util/Strings.java delete mode 100644 configuration/src/main/resources/configuration-bundle.properties delete mode 100644 core/.gitignore delete mode 100644 core/pom.xml delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/Name.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/Type.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/crud/package-info.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/util/Reflections.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java delete mode 100644 core/src/main/java/org/demoiselle/jee/core/util/Strings.java delete mode 100644 core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java delete mode 100644 core/src/main/java/org/demoiselle/jee/stereotype/Controller.java delete mode 100644 core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java delete mode 100644 core/src/main/java/org/demoiselle/jee/stereotype/RestController.java delete mode 100644 core/src/main/resources/demoiselle.properties delete mode 100644 core/src/main/resources/messages.properties create mode 100644 demoiselle-core/.gitignore create mode 100644 demoiselle-core/pom.xml create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Name.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Type.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/crud/package-info.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/messages/DemoiselleMessages.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Reflections.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Strings.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/Controller.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java create mode 100644 demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/RestController.java create mode 100644 demoiselle-core/src/main/resources/demoiselle.properties create mode 100644 demoiselle-core/src/main/resources/messages.properties create mode 100644 demoiselle-persistence-jpa/.gitignore create mode 100644 demoiselle-persistence-jpa/pom.xml create mode 100644 demoiselle-persistence-jpa/pom.xml~ create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/context/package-info.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericCrudDAO.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericDataPage.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/package-info.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/DemoisellePersistenceException.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/package-info.java create mode 100644 demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/interceptor/package-info.java create mode 100644 demoiselle-security-basic/.gitignore create mode 100644 demoiselle-security-basic/pom.xml create mode 100644 demoiselle-security-basic/pom.xml~ create mode 100644 demoiselle-security-basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java create mode 100644 demoiselle-security-basic/src/main/resources/demoiselle.properties create mode 100644 demoiselle-security-basic/src/main/resources/messages.properties create mode 100644 demoiselle-security-basic/target/classes/demoiselle.properties create mode 100644 demoiselle-security-basic/target/classes/messages.properties create mode 100644 demoiselle-security-jwt/.gitignore create mode 100644 demoiselle-security-jwt/pom.xml create mode 100644 demoiselle-security-jwt/pom.xml~ create mode 100644 demoiselle-security-jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java create mode 100644 demoiselle-security-jwt/src/main/resources/demoiselle.properties create mode 100644 demoiselle-security-jwt/src/main/resources/messages.properties create mode 100644 demoiselle-security-jwt/target/classes/demoiselle.properties create mode 100644 demoiselle-security-jwt/target/classes/messages.properties create mode 100644 demoiselle-security/.classpath create mode 100644 demoiselle-security/.gitignore create mode 100644 demoiselle-security/.project create mode 100644 demoiselle-security/.settings/org.eclipse.core.resources.prefs create mode 100644 demoiselle-security/.settings/org.eclipse.jdt.core.prefs create mode 100644 demoiselle-security/.settings/org.eclipse.m2e.core.prefs create mode 100644 demoiselle-security/pom.xml create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/LoggedUser.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/Token.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java create mode 100644 demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java create mode 100644 demoiselle-security/src/main/resources/messages.properties create mode 100644 demoiselle-ws-jaxrs/.classpath create mode 100644 demoiselle-ws-jaxrs/.gitignore create mode 100644 demoiselle-ws-jaxrs/.project create mode 100644 demoiselle-ws-jaxrs/.settings/org.eclipse.core.resources.prefs create mode 100644 demoiselle-ws-jaxrs/.settings/org.eclipse.jdt.core.prefs create mode 100644 demoiselle-ws-jaxrs/.settings/org.eclipse.m2e.core.prefs create mode 100644 demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.component create mode 100644 demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 demoiselle-ws-jaxrs/pom.xml create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/JaxRsFilter.java create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/crud/package-info.java create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/DemoiselleRESTException.java create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/mapper/GenericExceptionMapper.java create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayload.java create mode 100644 demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayloadInterceptor.java delete mode 100644 jwt/.gitignore delete mode 100644 jwt/pom.xml delete mode 100644 jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java delete mode 100644 jwt/src/main/resources/demoiselle.properties delete mode 100644 jwt/src/main/resources/messages.properties delete mode 100644 persistence/.gitignore delete mode 100644 persistence/pom.xml delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/context/package-info.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericCrudDAO.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericDataPage.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/crud/package-info.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/exception/DemoisellePersistenceException.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/exception/package-info.java delete mode 100644 persistence/src/main/java/org/demoiselle/jee/persistence/interceptor/package-info.java delete mode 100644 security/.gitignore delete mode 100644 security/pom.xml delete mode 100644 security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/LoggedUser.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/Token.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java delete mode 100644 security/src/main/resources/messages.properties delete mode 100644 swagger/.gitignore delete mode 100644 swagger/pom.xml delete mode 100644 swagger/src/main/java/org/demoiselle/swagger/SwaggerProducer.java delete mode 100644 ws/.gitignore delete mode 100644 ws/pom.xml delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/crud/package-info.java delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/exception/DemoiselleRESTException.java delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/exception/mapper/GenericExceptionMapper.java delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayload.java delete mode 100644 ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayloadInterceptor.java diff --git a/README.md b/README.md index 6e6a732..531d3ae 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Demoiselle 2 +Demoiselle 3 ============= O framework Demoiselle implementa o conceito de framework integrador. diff --git a/basic/.gitignore b/basic/.gitignore deleted file mode 100644 index ddd6d6d..0000000 --- a/basic/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/.settings/ -/.classpath -/.project diff --git a/basic/pom.xml b/basic/pom.xml deleted file mode 100644 index 135bb87..0000000 --- a/basic/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-security-basic - 3.0.0-SNAPSHOT - jar - - UTF-8 - 1.8 - 1.8 - - - - - ${project.groupId} - demoiselle-core - ${project.version} - - - - ${project.groupId} - demoiselle-ws - ${project.version} - - - - ${project.groupId} - demoiselle-security - ${project.version} - - - - diff --git a/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java b/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java deleted file mode 100644 index 571110a..0000000 --- a/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.security.basic.impl; - -import java.security.Principal; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; -import javax.enterprise.context.Dependent; -import javax.inject.Inject; -import org.demoiselle.jee.security.Token; -import org.demoiselle.jee.security.interfaces.TokensManager; - -/** - * - * @author 70744416353 - */ -@Dependent -public class TokensManagerImpl implements TokensManager { - - private static ConcurrentHashMap repo = new ConcurrentHashMap<>(); - - @Inject - private Logger logger; - - @Override - public Principal getUser(Token token) { - return repo.get(token.getKey()); - } - - @Override - public Token getToken(Principal user) { - String value = null; - if (!repo.containsValue(user)) { - value = UUID.randomUUID().toString(); - repo.put(value, user); - } else { - for (Map.Entry entry : repo.entrySet()) { - if (entry.getValue().equals(user)) { - return entry.getKey(); - } - } - } - return value; - } - -} diff --git a/basic/src/main/resources/demoiselle.properties b/basic/src/main/resources/demoiselle.properties deleted file mode 100644 index 4f777af..0000000 --- a/basic/src/main/resources/demoiselle.properties +++ /dev/null @@ -1 +0,0 @@ -user-not-authenticated \ No newline at end of file diff --git a/basic/src/main/resources/messages.properties b/basic/src/main/resources/messages.properties deleted file mode 100644 index 65893da..0000000 --- a/basic/src/main/resources/messages.properties +++ /dev/null @@ -1 +0,0 @@ -tipo-seguranca=basic \ No newline at end of file diff --git a/configuration/.gitignore b/configuration/.gitignore deleted file mode 100644 index 7aba5f8..0000000 --- a/configuration/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.settings -.classpath -.project diff --git a/configuration/pom.xml b/configuration/pom.xml deleted file mode 100644 index 7dd9b28..0000000 --- a/configuration/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - org.demoiselle - configuration - 3.0.0-SNAPSHOT - jar - - UTF-8 - 1.8 - 1.8 - - - - ${project.groupId} - core - ${project.version} - - - org.apache.commons - commons-configuration2 - 2.1 - - - diff --git a/configuration/src/main/java/org/demoiselle/configuration/ConfigType.java b/configuration/src/main/java/org/demoiselle/configuration/ConfigType.java deleted file mode 100644 index 6342de0..0000000 --- a/configuration/src/main/java/org/demoiselle/configuration/ConfigType.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.demoiselle.configuration; - -/** - * Defines configuration types to be loaded. - * - * @author SERPRO - */ -@SuppressWarnings("WeakerAccess") -public enum ConfigType { - - /** - * Configuration loaded on {@link System#getProperties()} or {@link System#getenv()}. - */ - @SuppressWarnings("unused") SYSTEM, - - /** - * Configuration loaded on XML resources. - */ - @SuppressWarnings("unused") XML, - - /** - * Configuration loaded on properties resources. - */ - @SuppressWarnings("unused") PROPERTIES - -} diff --git a/configuration/src/main/java/org/demoiselle/configuration/Configuration.java b/configuration/src/main/java/org/demoiselle/configuration/Configuration.java deleted file mode 100644 index c5029b3..0000000 --- a/configuration/src/main/java/org/demoiselle/configuration/Configuration.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.configuration; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Stereotype; -import javax.enterprise.util.Nonbinding; -import javax.inject.Named; -import javax.interceptor.InterceptorBinding; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - *

- * Identifies a configuration class, that is, a structure reserved to store configuration values retrieved from a - * given resource file or system variables. - *

- *

- * Configuration resources are application scoped, meaning only one instance can ever exist in - * a running application. For that reason usually configuration fields are immutable, to avoid - * changes made in one context affecting other contexts in a running application. - *

- *

A Configuration is:

- *
    - *
  • defined when annotated with {@code @Configuration}
  • - *
  • automatically injected whenever {@code @Inject} is used
  • - *
- * - * @author SERPRO - */ -@ApplicationScoped -@Named -@InterceptorBinding -@Stereotype -@Target(TYPE) -@Retention(RUNTIME) -public @interface Configuration { - - /** - * Define the default prefix. - */ - String DEFAULT_PREFIX = "demoiselle"; - - /** - * Define the default resource. - */ - String DEFAULT_RESOURCE = "demoiselle"; - - /** - * Defines the resource type to be used: a properties file, an XML file, or system variables. - * If not specified, a properties resource file is to be considered. - * - * @return ConfigType Type of configuration resource file to look for - */ - @Nonbinding @SuppressWarnings("unused") ConfigType type() default ConfigType.PROPERTIES; - - /** - * Defines an optional prefix to be used on every parameter key. - * For instance, if prefix is set to "demoiselle.pagination" and an attribute named - * defaultPageSize is found in the class, the corresponding key - * demoiselle.pagination.defaultPageSize is expected to be read in the resource file. - * - * @return String prefix common to all attributes to be read by the configuration class - */ - @Nonbinding @SuppressWarnings("unused") String prefix() default DEFAULT_PREFIX; - - /** - * Defines the resource file name to be read by this configuration class. There is no need to specify file extension - * in the case of properties or XML resources. - * For instance, when resource is set to "bookmark" and the type set to properties, a corresponding - * file named bookmark.properties is considered. - * If not specified, the default configuration file demoiselle.properties is used instead. - * - * @return String Name of the resource file to look for (minus file extension) - */ - @Nonbinding @SuppressWarnings("unused") String resource() default DEFAULT_RESOURCE; - -} diff --git a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationException.java b/configuration/src/main/java/org/demoiselle/configuration/ConfigurationException.java deleted file mode 100644 index d9d8a41..0000000 --- a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationException.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.configuration; - -import org.demoiselle.exception.DemoiselleException; - -/** - * Exception class intended to be used by configuration components. - * - * @author SERPRO - */ -@SuppressWarnings("unused") -public class ConfigurationException extends DemoiselleException { - - private static final long serialVersionUID = 1L; - - /** - * Constructor with message. - * - * @param message exception message - * @deprecated - */ - public ConfigurationException(String message) { - super(message); - } - - /** - * Constructor with message and cause. - * - * @param message exception message - * @param cause exception cause - */ - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationInterceptor.java b/configuration/src/main/java/org/demoiselle/configuration/ConfigurationInterceptor.java deleted file mode 100644 index 915f56c..0000000 --- a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationInterceptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.demoiselle.configuration; - -import org.demoiselle.annotation.literal.NamedQualifier; -import org.demoiselle.internal.implementation.ConfigurationLoader; - -import javax.annotation.Priority; -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.spi.CDI; -import javax.inject.Inject; -import javax.inject.Named; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptor; -import javax.interceptor.InvocationContext; - -/** - *

- * Interceptor class that loads the values of configuration files - * into it's mapped class. - *

- */ -@Dependent -@Configuration -@Interceptor -@Priority(Interceptor.Priority.APPLICATION) -public class ConfigurationInterceptor { - @AroundInvoke - public static Object constructConfiguration(final InvocationContext ic) throws Exception { - final ConfigurationLoader configurationLoader = CDI.current().select(ConfigurationLoader.class, new NamedQualifier("demoiselle-configuration-loader")).get(); - - final Class baseClass = ic.getMethod().getDeclaringClass(); - configurationLoader.load(ic.getTarget(), baseClass); - return ic.proceed(); - } -} diff --git a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java b/configuration/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java deleted file mode 100644 index f46b58d..0000000 --- a/configuration/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.configuration; - -import java.lang.reflect.Field; -import org.apache.commons.configuration2.Configuration; - -/** - *

- * Interface that defines how to convert values extracted from configuration - * files to fields in a class annotated with {@link Configuration}. - *

- * - *

- * Primitive types like int and float, their wrapper - * counterparts like {@link Integer} and {@link Float} and the {@link String} class - * can already be converted by the framework, this interface is reserved for specialized - * classes. - *

- * - * @author SERPRO - */ -@SuppressWarnings("unused") -public interface ConfigurationValueExtractor { - - /** - * Method that must appropriately extract the value from a property file and set this value to a - * field in a configuration class. - * - * @param prefix - * optional parte of property name that must be concatenated with key to form the whole - * property name. - * @param key - * key of the property. - * @param field - * configuration field to be setted. - * @param configuration - * a configuration object. - * @return current value of this property - * @throws Exception if the value can't be extracted from the property file - */ - Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception; - - /** - * Checks if the extractor class is appropriate to extract values to the type of deffined by parameter - * field. - * - * @param field - * field to be checked. - * @return true if this extractor can convert this field into the extractor's final type - */ - boolean isSupported(Field field); -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationArrayValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationArrayValueExtractor.java deleted file mode 100644 index 4b3b8cf..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationArrayValueExtractor.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.apache.commons.configuration2.DataConfiguration; -import org.demoiselle.annotation.Priority; -import org.demoiselle.configuration.ConfigurationValueExtractor; - -import javax.enterprise.context.Dependent; -import java.lang.reflect.Field; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Dependent -@Priority(L2_PRIORITY) -public class ConfigurationArrayValueExtractor implements ConfigurationValueExtractor { - - @Override - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - return new DataConfiguration(configuration).getArray(field.getType().getComponentType(), prefix + key); - } - - @Override - public boolean isSupported(Field field) { - return field.getType().isArray(); - } -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationClassValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationClassValueExtractor.java deleted file mode 100644 index ad3c7a1..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationClassValueExtractor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.demoiselle.annotation.Priority; -import org.demoiselle.configuration.ConfigurationValueExtractor; -import org.demoiselle.util.Reflections; - -import javax.enterprise.context.Dependent; -import java.lang.reflect.Field; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Priority(L2_PRIORITY) -@Dependent -public class ConfigurationClassValueExtractor implements ConfigurationValueExtractor { - - @Override - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - Object value = null; - String canonicalName = configuration.getString(prefix + key); - - if (canonicalName != null) { - value = Reflections.forName(canonicalName); - } - - return value; - } - - @Override - public boolean isSupported(Field field) { - return field.getType() == Class.class; - } -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationEnumValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationEnumValueExtractor.java deleted file mode 100644 index f539708..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationEnumValueExtractor.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.apache.commons.configuration2.ex.ConversionException; -import org.demoiselle.annotation.Priority; -import org.demoiselle.annotation.literal.NamedQualifier; -import org.demoiselle.configuration.ConfigurationValueExtractor; -import org.demoiselle.util.ResourceBundle; - -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.spi.CDI; -import java.lang.reflect.Field; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Priority(L2_PRIORITY) -@Dependent -public class ConfigurationEnumValueExtractor implements ConfigurationValueExtractor { - - private transient ResourceBundle bundle; - - @Override - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - String value = configuration.getString(prefix + key); - - if (value != null && !value.trim().equals("")) { - Object enums[] = field.getType().getEnumConstants(); - - for (int i = 0; i < enums.length; i++) { - if (((Enum) enums[i]).name().equals(value)) { - return enums[i]; - } - } - } else { - return null; - } - - throw new ConversionException(getBundle() - .getString("configuration-not-conversion", value, field.getDeclaringClass().getCanonicalName())); - } - - @Override - public boolean isSupported(Field field) { - return field.getType().isEnum(); - } - - private ResourceBundle getBundle() { - if (bundle == null) { - bundle = CDI.current().select(ResourceBundle.class, new NamedQualifier("demoiselle-core-bundle")).get(); - } - - return bundle; - } - -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationLoader.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationLoader.java deleted file mode 100644 index 0627792..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationLoader.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.apache.commons.configuration2.*; -import org.apache.commons.configuration2.builder.BasicConfigurationBuilder; -import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; -import org.apache.commons.configuration2.builder.fluent.Parameters; -import org.demoiselle.annotation.Ignore; -import org.demoiselle.annotation.Name; -import org.demoiselle.annotation.literal.NameQualifier; -import org.demoiselle.configuration.ConfigType; -import org.demoiselle.configuration.ConfigurationException; -import org.demoiselle.util.Reflections; -import org.demoiselle.util.ResourceBundle; -import org.demoiselle.util.Strings; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.spi.CDI; -import javax.inject.Named; -import javax.validation.*; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; -import javax.inject.Inject; -import org.apache.commons.configuration2.ex.ConversionException; - -import static org.demoiselle.configuration.ConfigType.SYSTEM; -import org.demoiselle.configuration.ConfigurationValueExtractor; - -/** - * This component loads a config class annotated with - * {@link org.demoiselle.configuration.Configuration} by filling its attributes - * with {@link org.demoiselle.jsf.util.Parameter} according to a - * {@link org.demoiselle.configuration.ConfigType}. - * - * @author SERPRO - */ -@ApplicationScoped -@Named("demoiselle-configuration-loader") -public class ConfigurationLoader implements Serializable { - - @Inject - private Logger LOG; - - private static final long serialVersionUID = 1L; - - private ResourceBundle bundle; - - private Object object; - - private Class baseClass; - - private ConfigType type; - - private String resource; - - private String prefix; - - private Configuration configuration; - - private Collection fields; - - private final Map loadedCache = new ConcurrentHashMap<>(); - - private Collection> extractorCache; - - public void load(final Object object, Class baseClass) throws ConfigurationException { - Boolean isLoaded = loadedCache.get(object); - - if (isLoaded == null || !isLoaded) { - try { - loadConfiguration(object, baseClass, true); - loadedCache.put(object, true); - } catch (ConfigurationException c) { - loadedCache.put(object, false); - throw c; - } - } - } - - public void load(final Object object, Class baseClass, boolean logLoadingProcess) throws ConfigurationException { - Boolean isLoaded = loadedCache.get(object); - - if (isLoaded == null || !isLoaded) { - try { - loadConfiguration(object, baseClass, logLoadingProcess); - loadedCache.put(object, true); - } catch (ConfigurationException c) { - loadedCache.put(object, false); - throw c; - } - } - } - - private void loadConfiguration(final Object object, Class baseClass, boolean logLoadingProcess) - throws ConfigurationException { - if (logLoadingProcess) { - LOG.fine(getBundle().getString("loading-configuration-class", baseClass.getName())); - } - - this.object = object; - this.baseClass = baseClass; - - loadFields(); - validateFields(); - - loadType(); - loadResource(); - loadConfiguration(); - - if (this.configuration != null) { - loadPrefix(); - loadValues(); - } - - validateValues(); - } - - private void loadFields() { - this.fields = Reflections.getNonStaticFields(baseClass); - } - - private void validateFields() { - this.fields.forEach(this::validateField); - } - - private void validateField(Field field) { - Name annotation = field.getAnnotation(Name.class); - - if (annotation != null && Strings.isEmpty(annotation.value())) { - throw new ConfigurationException(getBundle().getString("configuration-name-attribute-cant-be-empty"), - new IllegalArgumentException()); - } - } - - private void loadType() { - this.type = baseClass.getAnnotation(org.demoiselle.configuration.Configuration.class).type(); - } - - private void loadResource() { - if (this.type != SYSTEM) { - String name = baseClass.getAnnotation(org.demoiselle.configuration.Configuration.class) - .resource(); - String extension = this.type.toString().toLowerCase(); - - this.resource = name + "." + extension; - } - } - - private void loadConfiguration() { - Configuration config; - BasicConfigurationBuilder builder = createConfiguration(); - - if (builder instanceof FileBasedConfigurationBuilder) { - Parameters params = new Parameters(); - - ((FileBasedConfigurationBuilder) builder) - .configure(params.fileBased().setURL(Reflections.getResourceAsURL(this.resource))); - } - - try { - config = builder.getConfiguration(); - } catch (org.apache.commons.configuration2.ex.ConfigurationException e) { - LOG.warning(getBundle().getString("file-not-found", this.resource)); - config = null; - } - - this.configuration = config; - } - - private BasicConfigurationBuilder createConfiguration() { - BasicConfigurationBuilder builder; - - switch (this.type) { - case XML: - builder = new FileBasedConfigurationBuilder(XMLConfiguration.class); - break; - - case SYSTEM: - builder = new BasicConfigurationBuilder<>(SystemConfiguration.class); - break; - - default: - builder = new FileBasedConfigurationBuilder(PropertiesConfiguration.class); - } - - return builder; - } - - private void loadPrefix() { - String prefix = baseClass.getAnnotation(org.demoiselle.configuration.Configuration.class).prefix(); - - if (prefix.endsWith(".")) { - LOG.warning(getBundle().getString("configuration-dot-after-prefix", this.resource)); - } else if (!prefix.isEmpty()) { - prefix += "."; - } - - this.prefix = prefix; - } - - private void loadValues() { - this.fields.forEach(this::loadValue); - } - - private void loadValue(Field field) { - if (hasIgnore(field)) { - return; - } - - Object defaultValue = Reflections.getFieldValue(field, this.object); - Object loadedValue = getValue(field, field.getType(), getKey(field), defaultValue); - Object finalValue = (loadedValue == null ? defaultValue : loadedValue); - - if (loadedValue == null) { - LOG.fine(getBundle().getString("configuration-key-not-found", this.prefix + getKey(field))); - } - - Reflections.setFieldValue(field, this.object, finalValue); - LOG.finer(getBundle() - .getString("configuration-field-loaded", this.prefix + getKey(field), field.getName(), - finalValue == null ? "null" : finalValue)); - } - - private Object getValue(Field field, Class type, String key, Object defaultValue) { - Object value; - - try { - ConfigurationValueExtractor extractor = getValueExtractor(field); - value = extractor.getValue(this.prefix, key, field, this.configuration); - - } catch (ConfigurationException cause) { - throw cause; - - } catch (ConversionException cause) { - throw new ConfigurationException(getBundle() - .getString("configuration-not-conversion", this.prefix + getKey(field), field.getType().toString()), - cause); - } catch (Exception cause) { - throw new ConfigurationException(getBundle() - .getString("configuration-generic-extraction-error", field.getType().toString(), - getValueExtractor(field).getClass().getCanonicalName()), cause); - } - return value; - } - - private ConfigurationValueExtractor getValueExtractor(Field field) { - Collection candidates = new HashSet(); - - - if (elected == null) { - throw new ConfigurationException(getBundle() - .getString("configuration-extractor-not-found", field.toGenericString(), - ConfigurationValueExtractor.class.getName()), new ClassNotFoundException()); - } - - return elected; - } - - private String getKey(Field field) { - String key; - - if (field.isAnnotationPresent(Name.class)) { - key = field.getAnnotation(Name.class).value(); - } else { - key = field.getName(); - } - - return key; - } - - private boolean hasIgnore(Field field) { - return field.isAnnotationPresent(Ignore.class); - } - - private void validateValues() { - for (Field field : this.fields) { - validateValue(field, Reflections.getFieldValue(field, this.object)); - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private void validateValue(Field field, Object value) { - ValidatorFactory dfv = Validation.buildDefaultValidatorFactory(); - Validator validator = dfv.getValidator(); - - Set violations = validator.validateProperty(this.object, field.getName()); - - StringBuilder message = new StringBuilder(); - - if (!violations.isEmpty()) { - for (Iterator iter = violations.iterator(); iter.hasNext();) { - ConstraintViolation violation = (ConstraintViolation) iter.next(); - message.append(field.toGenericString() + " " + violation.getMessage() + "\n"); - } - - throw new ConfigurationException(message.toString(), new ConstraintViolationException(violations)); - } - } - - private Collection> getCache() { - if (this.extractorCache == null) { - this.extractorCache = Collections.synchronizedSet(new HashSet<>()); - } - - return this.extractorCache; - } - - private ResourceBundle getBundle() { - if (bundle == null) { - bundle = CDI.current().select(ResourceBundle.class, new NameQualifier("configuration-bundle")).get(); - } - - return bundle; - } - -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationMapValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationMapValueExtractor.java deleted file mode 100644 index dbd071d..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationMapValueExtractor.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - - - -import org.apache.commons.configuration2.Configuration; -import org.demoiselle.annotation.Priority; -import org.demoiselle.configuration.ConfigurationValueExtractor; - -import javax.enterprise.context.Dependent; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Priority(L2_PRIORITY) -@Dependent -public class ConfigurationMapValueExtractor implements ConfigurationValueExtractor { - - @Override - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - Map value = null; - - String regexp = "^(" + prefix + ")(" + key + ")(\\.(\\w+))?$"; - Pattern pattern = Pattern.compile(regexp); - - for (Iterator iter = configuration.getKeys(); iter.hasNext();) { - String iterKey = iter.next(); - Matcher matcher = pattern.matcher(iterKey); - - if (matcher.matches()) { - String confKey = matcher.group(1) + matcher.group(2) + ( matcher.group(3)!=null ? matcher.group(3) : "" ); - - /*matcher.group(1) + (matcher.group(2) == null ? "" : matcher.group(2)) - + matcher.group(4);*/ - - if (value == null) { - value = new HashMap<>(); - } - - String mapKey = matcher.group(4) == null ? "default" : matcher.group(4); - value.put(mapKey, configuration.getString(confKey)); - } - } - - return value; - } - - @Override - public boolean isSupported(Field field) { - return field.getType() == Map.class; - } -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationPrimitiveOrWrapperValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationPrimitiveOrWrapperValueExtractor.java deleted file mode 100644 index fae0af5..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationPrimitiveOrWrapperValueExtractor.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.apache.commons.configuration2.DataConfiguration; -import org.apache.commons.configuration2.ex.ConversionException; -import org.apache.commons.lang3.ClassUtils; -import org.demoiselle.annotation.Priority; -import org.demoiselle.configuration.ConfigurationValueExtractor; - -import javax.enterprise.context.Dependent; -import java.lang.reflect.Field; -import java.util.HashSet; -import java.util.Set; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Priority(L2_PRIORITY) -@Dependent -public class ConfigurationPrimitiveOrWrapperValueExtractor implements ConfigurationValueExtractor { - - private static final Set wrappers = new HashSet(); - - static { - wrappers.add(Boolean.class); - wrappers.add(Byte.class); - wrappers.add(Character.class); - wrappers.add(Short.class); - wrappers.add(Integer.class); - wrappers.add(Long.class); - wrappers.add(Double.class); - wrappers.add(Float.class); - wrappers.add(Void.TYPE); - } - - @Override - @SuppressWarnings("unchecked") - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - Object value; - - try { - value = new DataConfiguration(configuration) - .get(ClassUtils.primitiveToWrapper(field.getType()), prefix + key); - - } catch (ConversionException cause) { - throw cause; - } - - return value; - } - - @Override - public boolean isSupported(Field field) { - return field.getType().isPrimitive() || wrappers.contains(field.getType()); - } -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationProxyTemplateImpl.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationProxyTemplateImpl.java deleted file mode 100644 index 85bde4f..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationProxyTemplateImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.demoiselle.annotation.Ignore; - -import javax.enterprise.inject.spi.CDI; -import java.io.Serializable; - -public class ConfigurationProxyTemplateImpl implements Serializable { - - private static final long serialVersionUID = 1L; - - @Ignore - private Boolean loaded = false; - - private final Object lock = new Object(); - - @SuppressWarnings("unused") - private void load(Object instance) throws Throwable { - /*synchronized (lock) { - if (!loaded) { - try { - CDI.current().select(ConfigurationLoader.class).get().load(instance); - loaded = true; - } catch (Throwable cause) { - loaded = false; - throw cause; - } - } - }*/ - } -} diff --git a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationStringValueExtractor.java b/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationStringValueExtractor.java deleted file mode 100644 index d42cdef..0000000 --- a/configuration/src/main/java/org/demoiselle/internal/implementation/ConfigurationStringValueExtractor.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.internal.implementation; - -import org.apache.commons.configuration2.Configuration; -import org.demoiselle.annotation.Priority; -import org.demoiselle.configuration.ConfigurationValueExtractor; - -import javax.enterprise.context.Dependent; -import java.lang.reflect.Field; - -import static org.demoiselle.annotation.Priority.L2_PRIORITY; - -@SuppressWarnings("unused") -@Priority(L2_PRIORITY) -@Dependent -public class ConfigurationStringValueExtractor implements ConfigurationValueExtractor { - - @Override - public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception { - return configuration.getString(prefix + key); - } - - @Override - public boolean isSupported(Field field) { - return field.getType() == String.class; - } -} diff --git a/configuration/src/main/java/org/demoiselle/util/Reflections.java b/configuration/src/main/java/org/demoiselle/util/Reflections.java deleted file mode 100644 index cc23c44..0000000 --- a/configuration/src/main/java/org/demoiselle/util/Reflections.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.util; - -import java.io.InputStream; -import java.lang.reflect.*; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Logger; - -/** - * Provides some features to do some operations relating to java reflection. - * - * @author SERPRO - */ -public class Reflections { - - private static final Logger LOG = Logger.getLogger(Reflections.class.getName()); - - protected Reflections() { - // Impede instanciar subclasses desse tipo. - throw new UnsupportedOperationException(); - } - - /** - * Return the parametized type used with a concrete implementation of a - * class that accepts generics. Ex: If you declare - *
-     * public class SpecializedCollection implements Collection<SpecializedType> {
-     *   // ...
-     * }
-     * 
then the code - * getGenericTypeArgument(SpecializedCollection.class , 0); - * will return the type SpecializedType. - * - * @param type Base type to check for generic arguments - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Type type, final int idx) { - ParameterizedType paramType; - try { - paramType = (ParameterizedType) type; - } catch (ClassCastException cause) { - return getGenericTypeArgument((Class) type, idx); - } - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - * Return the parametized type used with a concrete implementation of a - * class that accepts generics. Ex: If you declare - *
-     * 
-     * public class SpecializedCollection implements Collection<SpecializedType> {
-     *   // ...
-     * }
-     * 
-     * 
then the code - * getGenericTypeArgument(SpecializedCollection.class , 0); - * will return the type SpecializedType. - * - * @param clazz Base type to check for generic arguments - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Class clazz, final int idx) { - final Type type = clazz.getGenericSuperclass(); - - ParameterizedType paramType; - try { - paramType = (ParameterizedType) type; - } catch (ClassCastException cause) { - return getGenericTypeArgument((Class) type, idx); - } - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - *

- * Return the parametized type passed to field types that accepts Generics. - *

- * Ex: If you declare - *
-     * 
-     * public class MyClass{
-     *    private Collection<String> myStringCollection;
-     * }
-     * 
-     * 
then the code - * getGenericTypeArgument( MyClass.class.getDeclaredField("myStringCollection") , 0); - * will return the type String. - * - * @param field Field which type is generified - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Field field, final int idx) { - final Type type = field.getGenericType(); - final ParameterizedType paramType = (ParameterizedType) type; - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - *

- * Return the parametized type passed to members (fields or methods) that - * accepts Generics. - *

- * - * @param member Member which type is generified - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - * @see #getGenericTypeArgument(Field field, int idx) - */ - public static Class getGenericTypeArgument(final Member member, final int idx) { - Class result = null; - - if (member instanceof Field) { - result = getGenericTypeArgument((Field) member, idx); - } else if (member instanceof Method) { - result = getGenericTypeArgument((Method) member, idx); - } - - return result; - } - - /** - *

- * Return the parametized type passed to methods that accepts Generics. - *

- * - * @param method Generified method reference - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - * @see #getGenericTypeArgument(Field field, int idx) - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Method method, final int idx) { - return (Class) method.getGenericParameterTypes()[idx]; - } - - /** - * Returns the value contained in the given field. - * - * @param field field to be extracted the value. - * @param object object that contains the field. - * @param Type of the generic argument - * @return value of the field. - */ - @SuppressWarnings("unchecked") - public static T getFieldValue(Field field, Object object) { - T result = null; - - try { - boolean acessible = field.isAccessible(); - field.setAccessible(true); - result = (T) field.get(object); - field.setAccessible(acessible); - - } catch (Exception e) { - LOG.fine(e.getMessage()); - } - - return result; - } - - /** - * Sets a value in a field. - * - * @param field field to be setted. - * @param object object that contains the field. - * @param value value to be setted in the field. - */ - public static void setFieldValue(Field field, Object object, Object value) { - try { - boolean acessible = field.isAccessible(); - field.setAccessible(true); - field.set(object, value); - field.setAccessible(acessible); - - } catch (Exception e) { - LOG.fine(e.getMessage()); - } - } - - /** - * @param type Base type to look for fields - * @return All non static fields from a certain type. Inherited fields are - * not returned, so if you need to get inherited fields you must iterate - * over this type's hierarchy. - */ - public static Field[] getNonStaticDeclaredFields(Class type) { - List fields = new ArrayList(); - - if (type != null) { - for (Field field : type.getDeclaredFields()) { - if (!Modifier.isStatic(field.getModifiers()) && !field.getType().equals(type.getDeclaringClass())) { - fields.add(field); - } - } - } - - return fields.toArray(new Field[0]); - } - - /** - * @param type Base type to look for fields - * @return All non static fields from a certain type, including fields - * declared in superclasses of this type. - */ - public static List getNonStaticFields(Class type) { - List fields = new ArrayList(); - - if (type != null) { - Class currentType = type; - while (currentType != null && !"java.lang.Object".equals(currentType.getCanonicalName())) { - fields.addAll(Arrays.asList(getNonStaticDeclaredFields(currentType))); - currentType = currentType.getSuperclass(); - } - } - - return fields; - } - - /** - * Instantiate an object of the given type. The default constructor with no - * parameters is used. - * - * @param clazz Base type of object to instantiate - * @param Final type of instantiated object - * @return New instance of provided type - */ - public static T instantiate(Class clazz) { - T object = null; - try { - object = clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - LOG.fine(e.getMessage()); - } - return object; - } - - /** - * Verifies if a given class could be converted to a given type. - * - * @param clazz class to be checked. - * @param type type to be checked. - * @return {@link Boolean} true if the given class can be converted to a - * given type, and false otherwise. - */ - public static boolean isOfType(Class clazz, Class type) { - return type.isAssignableFrom(clazz) && clazz != type; - } - - /** - * Obtains the {@link ClassLoader} for the given class, from his canonical - * name. - * - * @param canonicalName canonical name of the the given class. - * @return {@link ClassLoader} ClassLoader for the given class. - */ - public static ClassLoader getClassLoaderForClass(final String canonicalName) { - return Reflections.getClassLoaderForResource(canonicalName.replaceAll("\\.", "/") + ".class"); - } - - /** - * Obtains the {@link ClassLoader} for the given resource. - * - * @param resource String representation of the fully qualified path to the - * resource on the classpath - * @return {@link ClassLoader} ClassLoader for the given resource. - */ - public static ClassLoader getClassLoaderForResource(final String resource) { - final String stripped = resource.charAt(0) == '/' ? resource.substring(1) : resource; - - URL url = null; - ClassLoader result = Thread.currentThread().getContextClassLoader(); - - if (result != null) { - url = result.getResource(stripped); - } - - if (url == null) { - result = Reflections.class.getClassLoader(); - url = Reflections.class.getClassLoader().getResource(stripped); - } - - if (url == null) { - result = null; - } - - return result; - } - - /** - * Return an URL to access a resource available to the active classloader - * for the calling thread. - * - * @param resource String representation of the location of the resource on - * the classpath - * @return The {@link URL} for the resource - */ - public static URL getResourceAsURL(final String resource) { - ClassLoader classLoader = getClassLoaderForResource(resource); - return classLoader != null ? classLoader.getResource(resource) : null; - } - - /** - * Return an InputStream to access a resource available to the active - * classloader for the calling thread. - * - * @param resource String representation of the location of the resource on - * the classpath - * @return An {@link InputStream} that reads data from the resource - */ - public static InputStream getResourceAsStream(final String resource) { - ClassLoader classLoader = getClassLoaderForResource(resource); - return classLoader != null ? classLoader.getResourceAsStream(resource) : null; - } - - /** - * Loads a class with the given name using the active classloader for the - * current thread. - * - * @param className String with fully qualified class name of the desired - * class - * @param Final type of the loaded class - * @return Class representing the loaded type - * @throws ClassNotFoundException If no class with this name exists - */ - @SuppressWarnings("unchecked") - public static Class forName(final String className) throws ClassNotFoundException { - ClassLoader classLoader = getClassLoaderForClass(className); - return (Class) Class.forName(className, true, classLoader); - } -} diff --git a/configuration/src/main/java/org/demoiselle/util/ResourceBundle.java b/configuration/src/main/java/org/demoiselle/util/ResourceBundle.java deleted file mode 100644 index 02b9bcc..0000000 --- a/configuration/src/main/java/org/demoiselle/util/ResourceBundle.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.util; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.Enumeration; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Set; -import javax.inject.Named; - -/** - *

- * The Demoiselle's ResourceBundle extends the abstraction - * {@link java.util.ResourceBundle}, and provide the locale and the base name - * for the bundle.

- * - *

- * To select which resource properties file to load when injecting beans of this - * class, qualify the injection point with - * {@link org.demoiselle.annotation.Name}, using the resource name (without the - * '.properties' extension) as the value. If the injection point isn't qualified - * the default file messages.properties will be loaded from the - * root of the classpath.

- * - * @author SERPRO - */ -public class ResourceBundle extends java.util.ResourceBundle implements Serializable { - - private static final long serialVersionUID = 1L; - - private String baseName; - - private transient java.util.ResourceBundle delegate; - - private final Locale locale; - - private java.util.ResourceBundle getDelegate() { - if (delegate == null) { - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - delegate = ResourceBundle.getBundle(baseName, locale, classLoader); - - } catch (MissingResourceException mre) { - delegate = ResourceBundle.getBundle(baseName, locale); - } - } - - return delegate; - } - - /** - * Constructor that set values of baseName and locale. - * - * @param baseName the base name to construct the complete bundle name. - * - * @param locale locale to define the choosen bundle. - */ - public ResourceBundle(String baseName, Locale locale) { - this.baseName = baseName; - this.locale = locale; - } - - @Override - public boolean containsKey(String key) { - return getDelegate().containsKey(key); - } - - @Override - public Enumeration getKeys() { - return getDelegate().getKeys(); - } - - @Override - public Locale getLocale() { - return getDelegate().getLocale(); - } - - @Override - public Set keySet() { - return getDelegate().keySet(); - } - - public String getString(String key, Object... params) { - return Strings.getString(getString(key), params); - } - - @Override - protected Object handleGetObject(String key) { - Object result; - - try { - Method method = getDelegate().getClass().getMethod("handleGetObject", String.class); - - method.setAccessible(true); - result = method.invoke(delegate, key); - method.setAccessible(false); - - } catch (Exception cause) { - throw new RuntimeException(cause); - } - - return result; - } -} diff --git a/configuration/src/main/java/org/demoiselle/util/Strings.java b/configuration/src/main/java/org/demoiselle/util/Strings.java deleted file mode 100644 index ac534da..0000000 --- a/configuration/src/main/java/org/demoiselle/util/Strings.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.util; - -import org.demoiselle.annotation.Ignore; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Contain a set of methods that implements a set of functionalities that envolves manipulation of strings. - * - * @author SERPRO - */ -public final class Strings { - - private Strings() { - } - - /** - * Returns if some string matches with the format of a ResourceBundle key or not. - * - * @param key string to check if matches with key format of ResourceBundle. - * @return boolean true if matches and false otherwise. - */ - public static boolean isResourceBundleKeyFormat(final String key) { - return Pattern.matches("^\\{(.+)\\}$", key == null ? "" : key); - } - - /** - * Removes specific characteres from a given string. - * - * @param string string to be changed, by the removing of some characters. - * @param chars characters to be removed from string. - * @return String returns the given string without the given characters. - */ - public static String removeChars(String string, char... chars) { - String result = string; - - if (result != null) { - for (char ch : chars) { - result = result.replace(String.valueOf(ch), ""); - } - } - return result; - } - - public static String join(String separator, String... strings) { - StringBuffer result = new StringBuffer(); - - if (strings != null) { - for (int i = 0; i < strings.length; i++) { - if (i != 0 && separator != null) { - result.append(separator); - } - - if (strings[i] != null) { - result.append(strings[i]); - } - } - } - - return result.length() > 0 ? result.toString() : null; - } - - /** - * Inserts the character "0" in the begin of a given string. The quantity of zeros that will be placed depends on - * the difference between the length of the given string and the value of howMuchZeros. - * - * @param string string to insert zeros characthers. - * @param howMuchZeros its controls how much zeros will be insert. - * @return String Retuns the string, added with appropriate number of zeros. For exemplo, if string = "yes" and - * howMuchZeros = 5, the returned string will be "00yes". - */ - public static String insertZeros(String string, int howMuchZeros) { - StringBuffer result = new StringBuffer((string == null ? "" : string).trim()); - int difference = howMuchZeros - result.toString().length(); - - for (int j = 0; j < difference; j++) { - result.insert(0, '0'); - } - - return result.toString(); - } - - /** - * * Replaces the numbers between braces in the given string with the given parameters. The process will replace a - * number between braces for the parameter for which its order in the set of parameters matches with the number of - * the given string. - * For exemple, if is received the following string "Treats an {0} exception" and the set of parameters - * {"DemoiselleException"}, the return will be the following string: "Treats an DemoiselleException exception". - * - * @param string with the numbers with braces to be replaced with the parameters. - * @param params parameters that will replace the number with braces in the given string. - * @return String string with numbers replaced with the matching parameter. - */ - public static String getString(final String string, final Object... params) { - String result = null; - - if (string != null) { - result = new String(string); - } - - if (params != null && string != null) { - for (int i = 0; i < params.length; i++) { - if (params[i] != null) { - result = result.replaceAll("\\{" + i + "\\}", Matcher.quoteReplacement(params[i].toString())); - } - } - } - - return result; - } - - /** - * Verifies if a given string is empty or null. - * - * @param string string to be verified. - * @return boolean returns true if the given string is empty or null and returns false otherwise. - */ - public static boolean isEmpty(String string) { - return string == null || string.trim().isEmpty(); - } - - /** - * Converts any object to string. - * - * @param object object to be converted. - * @return String the given object converted to string. - */ - public static String toString(Object object) { - StringBuffer result = new StringBuffer(); - Object fieldValue; - - if (object != null) { - result.append(object.getClass().getSimpleName()); - result.append(" ["); - - boolean first = true; - for (Field field : Reflections.getNonStaticDeclaredFields(object.getClass())) { - if (!field.isAnnotationPresent(Ignore.class)) { - if (first) { - first = false; - } else { - result.append(", "); - } - - result.append(field.getName()); - result.append('='); - fieldValue = Reflections.getFieldValue(field, object); - result.append(fieldValue != null && fieldValue.getClass().isArray() ? - Arrays.toString((Object[]) fieldValue) : - fieldValue); - } - } - - result.append(']'); - } - - return result.toString(); - } - - /** - * Replace the camel case string for a lowercase string separated for a given symbol. - * - * @param string string that separeted with camel case. - * @param symbol simbol to be the new separator for the given string. - * @return String the given string separated with the given symbol. - */ - public static String camelCaseToSymbolSeparated(String string, String symbol) { - if (symbol == null) { - symbol = ""; - } - - return string == null ? null : string.replaceAll("\\B([A-Z])", symbol + "$1").toLowerCase(); - } - - /** - * Sets the first character of a given string to upper case. - * - * @param string Full string to convert - * @return String the given string with the first character setted to upper case. - */ - public static String firstToUpper(String string) { - String result = string; - - if (!Strings.isEmpty(string)) { - result = string.toUpperCase().charAt(0) + (string.length() > 1 ? string.substring(1) : ""); - } - - return result; - } - - /** - * Removes braces from a given string. - * - * @param string Message to remove braces from - * @return String the given string without braces. - */ - public static String removeBraces(String string) { - String result = string; - - if (isResourceBundleKeyFormat(string)) { - result = string.substring(1, string.length() - 1); - } - - return result; - } - - /** - * Inserts braces in a given string. - * - * @param string Original string to insert braces on. - * @return String the given string with braces. - */ - public static String insertBraces(String string) { - String result = string; - - if (!isEmpty(string)) { - result = "{" + string + "}"; - } - - return result; - } - - public static String parse(InputStream inputStream) throws IOException { - StringBuilder result = new StringBuilder(); - - if (inputStream != null) { - BufferedReader reader = null; - - try { - reader = new BufferedReader(new InputStreamReader(inputStream)); - String line; - - while ((line = reader.readLine()) != null) { - result.append(line); - } - - } finally { - if (reader != null) { - reader.close(); - } - } - } - - return result.length() > 0 ? result.toString() : null; - } -} diff --git a/configuration/src/main/resources/configuration-bundle.properties b/configuration/src/main/resources/configuration-bundle.properties deleted file mode 100644 index 84cee3c..0000000 --- a/configuration/src/main/resources/configuration-bundle.properties +++ /dev/null @@ -1,44 +0,0 @@ -# Demoiselle Framework -# Copyright (C) 2010 SERPRO -# ---------------------------------------------------------------------------- -# This file is part of Demoiselle Framework. -# -# Demoiselle Framework is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License version 3 -# as published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License version 3 -# along with this program; if not, see -# or write to the Free Software Foundation, Inc., 51 Franklin Street, -# Fifth Floor, Boston, MA 02110-1301, USA. -# ---------------------------------------------------------------------------- -# Este arquivo \u00e9 parte do Framework Demoiselle. -# -# O Framework Demoiselle \u00e9 um software livre; voc\u00ea pode redistribu\u00ed-lo e/ou -# modific\u00e1-lo dentro dos termos da GNU LGPL vers\u00e3o 3 como publicada pela Funda\u00e7\u00e3o -# do Software Livre (FSF). -# -# Este programa \u00e9 distribu\u00eddo na esperan\u00e7a que possa ser \u00fatil, mas SEM NENHUMA -# GARANTIA; sem uma garantia impl\u00edcita de ADEQUA\u00c7\u00c3O a qualquer MERCADO ou -# APLICA\u00c7\u00c3O EM PARTICULAR. Veja a Licen\u00e7a P\u00fablica Geral GNU/LGPL em portugu\u00eas -# para maiores detalhes. -# -# Voc\u00ea deve ter recebido uma c\u00f3pia da GNU LGPL vers\u00e3o 3, sob o t\u00edtulo -# "LICENCA.txt", junto com esse programa. Se n\u00e3o, acesse -# ou escreva para a Funda\u00e7\u00e3o do Software Livre (FSF) Inc., -# 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - -loading-configuration-class=Carregando a classe de configura\u00e7\u00e3o {0} -configuration-field-loaded={0}: {2} -configuration-attribute-is-mandatory=A configura\u00e7\u00e3o {0} \u00e9 obrigat\u00f3ria, mas n\u00e3o foi encontrada em {1} -configuration-name-attribute-cant-be-empty=A nota\u00e7\u00e3o @Name n\u00e3o pode estar em branco -configuration-generic-extraction-error=Ocorreu um erro durante a extra\u00e7\u00e3o do tipo {0} com o extrator {1} -configuration-dot-after-prefix=N\u00e3o \u00e9 necess\u00e1rio adicionar o ponto ap\u00f3s o prefixo para uma classe de configura\u00e7\u00e3o. \u00c9 recomendado que sejam retirados, pois poder\u00e3o causar erros em vers\u00f5es futuras do Framework. -configuration-key-not-found={0}\: [n\u00e3o encontrada] -configuration-extractor-not-found=N\u00e3o foi poss\u00edvel encontrar a classe extratora para o atributo {0}. Implemente a interface {1} para criar sua classe extratora. -configuration-not-conversion=N\u00e3o \u00e9 poss\u00edvel converter o valor {0} para o tipo {1} diff --git a/core/.gitignore b/core/.gitignore deleted file mode 100644 index 8121e13..0000000 --- a/core/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.settings -.classpath -.project -/bin/ diff --git a/core/pom.xml b/core/pom.xml deleted file mode 100644 index 0130281..0000000 --- a/core/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-core - 3.0.0-SNAPSHOT - jar - - Demoiselle Core - - Contém funcionalidades comuns a todos os módulos framework. - - - http://demoiselle.org - - - - UTF-8 - 1.8 - 1.8 - - - - javax - javaee-web-api - 7.0 - - - javax.enterprise - cdi-api - 1.2 - - - diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java b/core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java deleted file mode 100644 index 4c793da..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** - *

Used in fields of classes annotated with {@link org.demoiselle.configuration.Configuration} - * to indicate that the system should ignore this field when population the new configuration - * instance with values extracted from the source file.

- * - * @see org.demoiselle.configuration.Configuration - * @author SERPRO - */ -@Target(FIELD) -@Retention(RUNTIME) -public @interface Ignore { -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/Name.java b/core/src/main/java/org/demoiselle/jee/core/annotation/Name.java deleted file mode 100644 index 8e93aaa..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/Name.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation; - -import javax.enterprise.inject.spi.InjectionPoint; -import javax.enterprise.util.Nonbinding; -import javax.inject.Named; -import javax.inject.Qualifier; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - *

- * String based non-binding qualifier. - *

- * - *

- * This annotation is used to qualify beans using an user defined String. {@link javax.enterprise.inject.Produces} - * methods can then read this string and use it to customize the bean creation process. - *

- * - *

- * The {@link #value()} attribute is non-binding (contrary to {@link Named#value()}, meaning multiple classes - * qualified with this annotation, even with different values, will be considered the same candidate for - * injection points. To avoid ambiguous resolutions and select which candidate to choose usually you'll need a - * producer method to read the string and select the best fitted candidate. - *

- * - *

- * The framework classes qualified with this annotation already have such producers and the accepted values for - * this annotation will be detailed in their respective documentations. - *

- * - * - * @author SERPRO - * - * @see org.demoiselle.util.ResourceBundle - * @see org.demoiselle.internal.producer.ResourceBundleProducer#create(InjectionPoint) - * @see org.demoiselle.internal.producer.LoggerProducer#createNamed(InjectionPoint) - */ -@Qualifier -@Inherited -@Retention(RUNTIME) -@Target({ TYPE, FIELD, METHOD, PARAMETER }) -public @interface Name { - - /** - *

- * Specifies a name to access a custom configuration that will change how the annotated bean works. - *

- *

- * This attribute is nonbinding so you can use the {@link Name} annotation to create {@linkplain javax.enterprise.inject.Produces} - * methods or fields and have only one producer that works with all injection points no matter the value of this attribute. - *

- * @return Name of custom settings to personalize how the annotated bean works. - */ - @Nonbinding - String value() default ""; - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java b/core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java deleted file mode 100644 index e1d04ac..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - *

- * Used to prioritize some execution flow, as methods annotated with @startup or @shutdown, - * or some interface implementation. - *

- * - * @author SERPRO - */ -@Target({ TYPE, METHOD }) -@Retention(RUNTIME) -public @interface Priority { - - /** - * Most important priority value. - */ - static int MAX_PRIORITY = Integer.MIN_VALUE; - - /** - * Less important priority value. - */ - static int MIN_PRIORITY = Integer.MAX_VALUE; - - /** - * Less important priority value. - */ - static int L1_PRIORITY = MIN_PRIORITY; - - /** - * Higher priority than L1_PRIORITY - */ - static int L2_PRIORITY = L1_PRIORITY - 100; - - /** - * Higher priority than L2_PRIORITY - */ - static int L3_PRIORITY = L2_PRIORITY - 100; - - /** - * Higher priority than L3_PRIORITY - */ - static int L4_PRIORITY = L3_PRIORITY - 100; - - /** - *

- * An integer value defines the priority order. The lower the value, the greater priority. - *

- * - * @return Priority value, lower values have higher priority. - */ - int value(); -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java b/core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java deleted file mode 100644 index 335692f..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.inject.Qualifier; - -/** - * - *

- * This literal marks a bean to be selected at runtime based on a priority system. - * The user qualifies the injection point with this literal and then at runtime - * the CDI engine will circle through all candidate subtypes to be injected - * that are annotated with {@link Priority}. If there is only one subtype with the - * highest priority then this one will be selected to be injected. - *

- * - *

- * This allows users to plug in libraries with new candidates and have them be selected - * if their priority values are higher than the default values already present. One example - * is the {@link org.demoiselle.security.Authorizer} type, the framework has a {@link org.demoiselle.internal.implementation.DefaultAuthorizer} - * with {@link Priority#L1_PRIORITY the lowest priority} but the user can add libraries with new - * implementations of {@link org.demoiselle.security.Authorizer} annotated with higher priorities, the code will - * then automatically select these new implementations with no extra configuration. - *

- * - *

- * This annotation must be used with supported types. Usually this involves creating {@link javax.enterprise.inject.Produces} CDI - * producer methods that will select the correct strategy. To create your own producer - * methods that support strategy selection, use the utility {@linkplain org.demoiselle.internal.producer.StrategySelector}. - *

- * - * @author SERPRO - */ -@Qualifier -@Inherited -@Retention(RUNTIME) -@Target({ TYPE, FIELD, METHOD, PARAMETER }) -public @interface Strategy { - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/Type.java b/core/src/main/java/org/demoiselle/jee/core/annotation/Type.java deleted file mode 100644 index 6552005..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/Type.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.core.annotation; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.enterprise.util.Nonbinding; -import javax.inject.Qualifier; - -/** - *

- * Type based non-binding qualifier. - *

- * - *

- * This annotation is used to qualify beans using a class type. - * {@link javax.enterprise.inject.Produces} methods can then read this type and - * use it to customize the bean creation process. - *

- * - *

- * The {@link #value()} attribute is non-binding, meaning multiple classes - * qualified with this annotation, even with different values, will be - * considered the same candidate for injection points. To avoid ambiguous - * resolutions and select which candidate to choose usually you'll need a - * producer method to read the type and select the best fitted candidate. - *

- * - *

- * The framework classes qualified with this annotation already have such - * producers and the accepted values for this annotation will be detailed in - * their respective documentations. - *

- * - * - * @author SERPRO - * - */ -@Qualifier -@Inherited -@Retention(RUNTIME) -@Target({ TYPE, FIELD, METHOD, PARAMETER }) -public @interface Type { - - @Nonbinding - Class value() default Object.class; - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java b/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java deleted file mode 100644 index 83eb0de..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation.literal; - -import org.demoiselle.jee.core.annotation.Name; - -import javax.enterprise.util.AnnotationLiteral; - -/** - * Annotation litteral that allows to create instances of the {@link Name} literal. The created instance can then be - * used to call {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)} - * - * @author SERPRO - * @see javax.enterprise.inject.spi.CDI - */ -@SuppressWarnings("all") -public class NameQualifier extends AnnotationLiteral implements Name { - - private static final long serialVersionUID = 1L; - - private final String value; - - /** - * Constructor with string value of name literal. - * - * @param value value of name literal. - */ - public NameQualifier(String value) { - this.value = value; - } - - @Override - public String value() { - return this.value; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java b/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java deleted file mode 100644 index 9f7e0fd..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation.literal; - -import javax.enterprise.util.AnnotationLiteral; -import javax.inject.Named; -import java.lang.annotation.Annotation; - -/** - * Annotation litteral that allows to create instances of the {@link Named} literal. - * Those instances can then be used to call - * {@link javax.enterprise.inject.spi.CDI#select(Class subtype, Annotation... qualifiers)} - * - * @see javax.enterprise.inject.spi.CDI - * @see Named - * - * @author SERPRO - */ -@SuppressWarnings("all") -public class NamedQualifier extends AnnotationLiteral implements Named { - - private static final long serialVersionUID = 6790759427086052113L; - - private String namedValue; - - public NamedQualifier(String value) { - namedValue = value; - } - - public String value() { - return namedValue; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java b/core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java deleted file mode 100644 index 74290d5..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation.literal; - -import org.demoiselle.jee.core.annotation.Strategy; - -import javax.enterprise.util.AnnotationLiteral; - -/** - * Annotation litteral that allows to create instances of the {@link Strategy} literal. The created instance can then be - * used to call {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)}. - * - * @see javax.enterprise.inject.spi.CDI - * @author SERPRO - */ -@SuppressWarnings("all") -public class StrategyQualifier extends AnnotationLiteral implements Strategy { - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java b/core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java deleted file mode 100644 index e7513e8..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.annotation.literal; - -import org.demoiselle.jee.core.annotation.Type; - -import javax.enterprise.util.AnnotationLiteral; - -/** - * Annotation litteral that allows to create instances of the {@link Type} - * literal. The created instance can then be used to call - * {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)}. - * - * @see javax.enterprise.inject.spi.CDI - * @author SERPRO - */ -@SuppressWarnings("all") -public class TypeQualifier extends AnnotationLiteral implements Type { - - private static final long serialVersionUID = 1L; - - private final Class value; - - /** - * Constructor with string value of name literal. - * - * @param value value of name literal. - */ - public TypeQualifier(Class value) { - this.value = value; - } - - @Override - public Class value() { - return this.value; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/crud/package-info.java b/core/src/main/java/org/demoiselle/jee/core/crud/package-info.java deleted file mode 100644 index 88135d8..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/crud/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas aos - * facilitadores de CRUD do framework Demoiselle. - */ -package org.demoiselle.jee.core.crud; \ No newline at end of file diff --git a/core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java b/core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java deleted file mode 100644 index 4051e2f..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.core.exception; - -/** - * Exception class intended to be used by framework configuration and to be derived by other framework exceptions. - * - * @author SERPRO - */ -public class DemoiselleException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Constructor with message. - * - * @param message - * exception message - */ - public DemoiselleException(String message) { - super(message); - } - - /** - * Constructor with cause. - * - * @param cause - * exception cause - */ - public DemoiselleException(Throwable cause) { - super(cause); - } - - /** - * Constructor with message and cause. - * - * @param message - * exception message - * @param cause - * exception cause - */ - public DemoiselleException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java b/core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java deleted file mode 100644 index 53e534c..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.core.internal.producer; - -import java.io.Serializable; -import java.util.logging.Logger; -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Produces; -import javax.enterprise.inject.spi.InjectionPoint; - -/** - * - * @author 70744416353 - */ -@Dependent -public class LoggerProducer implements Serializable { - - private static final long serialVersionUID = 1L; - - /* - * Produces a default {@link Logger} instance. If it's possible - * to infer the injection point's parent class then this class'es - * name will be used to categorize the logger, if not then - * the logger won't be categorized. - * - */ - @Default - @Produces - public static final Logger create(final InjectionPoint ip) { - String name; - - if (ip != null && ip.getMember() != null) { - name = ip.getMember().getDeclaringClass().getName(); - } else { - name = "not.categorized"; - } - - return Logger.getLogger(name); - } - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java b/core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java deleted file mode 100644 index 325e320..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.core.internal.producer; - -import java.io.Serializable; -import java.util.Locale; - -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Produces; -import javax.enterprise.inject.spi.CDI; -import javax.enterprise.inject.spi.InjectionPoint; - -import org.demoiselle.jee.core.annotation.Name; -import org.demoiselle.jee.core.util.CDIUtils; -import org.demoiselle.jee.core.util.ResourceBundle; - -/** - * - * @author 70744416353 - */ -@Dependent -public class ResourceBundleProducer implements Serializable { - - private static final long serialVersionUID = 1L; - - @Default - @Produces - public ResourceBundle createDefault() { - return create((String) null); - } - - /* - * Produces a {@link java.util.ResourceBundle} instance loading the properties file whose name - * is defined by the {@link Name} literal. If no value is specified - * then the default "messages.properties" file is loaded. - */ - @Name - @Produces - public ResourceBundle create(InjectionPoint ip) { - String baseName = null; - if (ip != null && ip.getQualifiers() != null) { - Name nameQualifier = CDIUtils.getQualifier(Name.class, ip); - if (nameQualifier != null) { - baseName = nameQualifier.value(); - if ("".equals(baseName)) { - baseName = null; - } - } - } - - return create(baseName); - } - - @SuppressWarnings("serial") - public static ResourceBundle create(String baseName) { - ResourceBundle bundle; - - try { - bundle = baseName != null - ? new ResourceBundle(baseName, CDI.current().select(Locale.class).get()) { - } - : new ResourceBundle("messages", CDI.current().select(Locale.class).get()); - } catch (RuntimeException e) { - bundle = baseName != null - ? new ResourceBundle(baseName, Locale.getDefault()) - : new ResourceBundle("messages", Locale.getDefault()); - } - - return bundle; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java b/core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java deleted file mode 100644 index b98fa04..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.core.lifecycle; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Annotate other annotations with this one to - * mark them as lifecycle annotations, meaning - * the lifecycle processor of the framework will - * read them and fire events based on their represented - * lifecycle stages. - * - * @author SERPRO - */ -@Inherited -@Target(ElementType.ANNOTATION_TYPE) -@Retention(RUNTIME) -public @interface LifecycleAnnotation { - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java b/core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java deleted file mode 100644 index 69fe64a..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.demoiselle.jee.core.util; - -import java.lang.annotation.Annotation; -import java.util.Collection; - -import javax.enterprise.inject.spi.InjectionPoint; - -/** - * Utility class to peform useful operations on CDI discovered beans. - * - * @author SERPRO - */ -public final class CDIUtils { - - private static final Annotation[] annotationArrayType = new Annotation[0]; - - /** - * Returns true if one annotation of the provided type is present - * on a list of annotations. - * - * @param annotationType Annotation type being looked for. - * @param allAnnotations List of all annotations where to look for. - * @return true if the annotation is present on the list - */ - public static boolean hasAnnotation(Class annotationType, Annotation... allAnnotations) { - for (Annotation currentAnnotation : allAnnotations) { - if (currentAnnotation.annotationType().isAssignableFrom(annotationType)) { - return true; - } - } - - return false; - } - - /** - * @param annotationType Type of the annotation being checked - * @param allAnnotations List of annotations to check for the specific one - * @see #hasAnnotation(Class, Annotation...) - * @return true if the annotation is present on the list - */ - public static boolean hasAnnotation(Class annotationType, - Collection allAnnotations) { - return hasAnnotation(annotationType, allAnnotations.toArray(annotationArrayType)); - } - - /** - * Returns true if a base class is annotated with the provided annotation. - * - * @param annotationType Annotation type to look for - * @param baseType Class to check for the informed annotation - * @see #hasAnnotation(Class, Annotation...) - * @return true if the annotation is present on the list - */ - public static boolean hasAnnotation(Class annotationType, Class baseType) { - return hasAnnotation(annotationType, baseType.getAnnotations()); - } - - /** - * Returns the annotation instance that matches the annotation type provided, - * or null if no annotation of that type is present. - * - * @param annotationType Annotation type being looked for. - * @param allAnnotations List of all annotations where to look for. - * @param Type of the specific annotation returned - * @return The annotation instance found, or null if there is no such annotation present. - */ - @SuppressWarnings("unchecked") - public static T getAnnotation(Class annotationType, Annotation... allAnnotations) { - for (Annotation currentAnnotation : allAnnotations) { - if (currentAnnotation.annotationType().isAssignableFrom(annotationType)) { - return (T) currentAnnotation; - } - } - - return null; - } - - /** - * @param annotationType Annotation type being looked for. - * @param allAnnotations List of all annotations where to look for. - * @param Type of the specific annotation returned - * @see #getAnnotation(Class, Annotation...) - * @return The annotation instance found, or null if there is no such annotation present. - */ - public static T getAnnotation(Class annotationType, - Collection allAnnotations) { - return getAnnotation(annotationType, allAnnotations.toArray(annotationArrayType)); - } - - /** - * Returns true if one qualifier of the provided type is present - * on an injection point. - * - * @param qualifierAnnotationType Annotation type being looked for. - * @param ip Injection point of a bean type. - * @return true if the annotation is present on the list - */ - public static boolean hasQualifier(Class qualifierAnnotationType, InjectionPoint ip) { - return hasAnnotation(qualifierAnnotationType, ip.getQualifiers()); - } - - /** - * Returns the annotation instance that matches the annotation type provided, - * or null if no annotation of that type is present. - * - * @param qualifierAnnotationType Annotation type being looked for. - * @param ip Injection point of a bean type. - * @param Type of the specific annotation returned - * @return The annotation instance found, or null if there is no such annotation present. - */ - public static T getQualifier(Class qualifierAnnotationType, InjectionPoint ip) { - return getAnnotation(qualifierAnnotationType, ip.getQualifiers()); - } - -} diff --git a/core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java b/core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java deleted file mode 100644 index cd2c6da..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.util; - -/** - *Class that offer tow methods that can help with manipulation of throwable exceptions. - * - * @author SERPRO - */ -public final class Exceptions { - - /** - * Constructor without parameters. - */ - private Exceptions() { - } - - /** - * Receives as parameter any kind of Throwable objects, and throws a RuntimeException instead. - * - * @param throwable - * a throwable object. - * - * @throws RuntimeException throws this kind of exception every time that is called. - */ - public static void handleToRuntimeException(final Throwable throwable) throws RuntimeException { - if (throwable instanceof RuntimeException) { - throw (RuntimeException) throwable; - } else { - throw new RuntimeException(throwable); - } - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/util/Reflections.java b/core/src/main/java/org/demoiselle/jee/core/util/Reflections.java deleted file mode 100644 index 06a1670..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/util/Reflections.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.util; - -import java.io.InputStream; -import java.lang.reflect.*; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Provides some features to do some operations relating to java reflection. - * - * @author SERPRO - */ -public class Reflections { - - protected Reflections() { - // Impede instanciar subclasses desse tipo. - throw new UnsupportedOperationException(); - } - - /** - * Return the parametized type used with a concrete implementation of a class that accepts generics. Ex: If you - * declare - *
-	 * public class SpecializedCollection implements Collection<SpecializedType> {
-	 *   // ...
-	 * }
-	 * 
- * then the code getGenericTypeArgument(SpecializedCollection.class , 0); will return the type - * SpecializedType. - * - * @param type Base type to check for generic arguments - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Type type, final int idx) { - ParameterizedType paramType; - try { - paramType = (ParameterizedType) type; - } catch (ClassCastException cause) { - return getGenericTypeArgument((Class) type, idx); - } - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - * Return the parametized type used with a concrete implementation of a class that accepts generics. Ex: If you - * declare - *
-	 * 
-	 * public class SpecializedCollection implements Collection<SpecializedType> {
-	 *   // ...
-	 * }
-	 * 
-	 * 
- * then the code getGenericTypeArgument(SpecializedCollection.class , 0); will return the type - * SpecializedType. - * - * @param clazz Base type to check for generic arguments - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Class clazz, final int idx) { - final Type type = clazz.getGenericSuperclass(); - - ParameterizedType paramType; - try { - paramType = (ParameterizedType) type; - } catch (ClassCastException cause) { - return getGenericTypeArgument((Class) type, idx); - } - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - *

- * Return the parametized type passed to field types that accepts Generics. - *

- * Ex: If you declare - *
-	 * 
-	 * public class MyClass{
-	 *    private Collection<String> myStringCollection;
-	 * }
-	 * 
-	 * 
- * then the code getGenericTypeArgument( MyClass.class.getDeclaredField("myStringCollection") , 0); - * will return the type String. - * - * @param field Field which type is generified - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Field field, final int idx) { - final Type type = field.getGenericType(); - final ParameterizedType paramType = (ParameterizedType) type; - - return (Class) paramType.getActualTypeArguments()[idx]; - } - - /** - *

- * Return the parametized type passed to members (fields or methods) that accepts Generics. - *

- * - * @param member Member which type is generified - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - * @see #getGenericTypeArgument(Field field, int idx) - */ - public static Class getGenericTypeArgument(final Member member, final int idx) { - Class result = null; - - if (member instanceof Field) { - result = getGenericTypeArgument((Field) member, idx); - } else if (member instanceof Method) { - result = getGenericTypeArgument((Method) member, idx); - } - - return result; - } - - /** - *

- * Return the parametized type passed to methods that accepts Generics. - *

- * - * @param method Generified method reference - * @param idx zero based index of the generic argument to get - * @param Type of the generic argument - * @return The class representing the type of the generic argument - * @see #getGenericTypeArgument(Field field, int idx) - */ - @SuppressWarnings("unchecked") - public static Class getGenericTypeArgument(final Method method, final int idx) { - return (Class) method.getGenericParameterTypes()[idx]; - } - - /** - * Returns the value contained in the given field. - * - * @param field field to be extracted the value. - * @param object object that contains the field. - * @param Type of the generic argument - * @return value of the field. - */ - @SuppressWarnings("unchecked") - public static T getFieldValue(Field field, Object object) { - T result = null; - - try { - boolean acessible = field.isAccessible(); - field.setAccessible(true); - result = (T) field.get(object); - field.setAccessible(acessible); - - } catch (Exception e) { - Exceptions.handleToRuntimeException(e); - } - - return result; - } - - /** - * Sets a value in a field. - * - * @param field field to be setted. - * @param object object that contains the field. - * @param value value to be setted in the field. - */ - public static void setFieldValue(Field field, Object object, Object value) { - try { - boolean acessible = field.isAccessible(); - field.setAccessible(true); - field.set(object, value); - field.setAccessible(acessible); - - } catch (Exception e) { - Exceptions.handleToRuntimeException(e); - } - } - - /** - * @param type Base type to look for fields - * @return All non static fields from a certain type. Inherited fields are not returned, so if you need to get - * inherited fields you must iterate over this type's hierarchy. - */ - public static Field[] getNonStaticDeclaredFields(Class type) { - List fields = new ArrayList(); - - if (type != null) { - for (Field field : type.getDeclaredFields()) { - if (!Modifier.isStatic(field.getModifiers()) && !field.getType().equals(type.getDeclaringClass())) { - fields.add(field); - } - } - } - - return fields.toArray(new Field[0]); - } - - /** - * @param type Base type to look for fields - * @return All non static fields from a certain type, including fields declared in superclasses of this type. - */ - public static List getNonStaticFields(Class type) { - List fields = new ArrayList(); - - if (type != null) { - Class currentType = type; - while (currentType != null && !"java.lang.Object".equals(currentType.getCanonicalName())) { - fields.addAll(Arrays.asList(getNonStaticDeclaredFields(currentType))); - currentType = currentType.getSuperclass(); - } - } - - return fields; - } - - /** - * Instantiate an object of the given type. The default constructor with no parameters is used. - * - * @param clazz Base type of object to instantiate - * @param Final type of instantiated object - * @return New instance of provided type - */ - public static T instantiate(Class clazz) { - T object = null; - try { - object = clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - Exceptions.handleToRuntimeException(e); - } - return object; - } - - /** - * Verifies if a given class could be converted to a given type. - * - * @param clazz class to be checked. - * @param type type to be checked. - * @return {@link Boolean} true if the given class can be converted to a given type, and false otherwise. - */ - public static boolean isOfType(Class clazz, Class type) { - return type.isAssignableFrom(clazz) && clazz != type; - } - - /** - * Obtains the {@link ClassLoader} for the given class, from his canonical name. - * - * @param canonicalName canonical name of the the given class. - * @return {@link ClassLoader} ClassLoader for the given class. - */ - public static ClassLoader getClassLoaderForClass(final String canonicalName) { - return Reflections.getClassLoaderForResource(canonicalName.replaceAll("\\.", "/") + ".class"); - } - - /** - * Obtains the {@link ClassLoader} for the given resource. - * - * @param resource String representation of the fully qualified path to the resource on the classpath - * @return {@link ClassLoader} ClassLoader for the given resource. - */ - public static ClassLoader getClassLoaderForResource(final String resource) { - final String stripped = resource.charAt(0) == '/' ? resource.substring(1) : resource; - - URL url = null; - ClassLoader result = Thread.currentThread().getContextClassLoader(); - - if (result != null) { - url = result.getResource(stripped); - } - - if (url == null) { - result = Reflections.class.getClassLoader(); - url = Reflections.class.getClassLoader().getResource(stripped); - } - - if (url == null) { - result = null; - } - - return result; - } - - /** - * Return an URL to access a resource available to the active classloader for the calling thread. - * - * @param resource String representation of the location of the resource on the classpath - * @return The {@link URL} for the resource - */ - public static URL getResourceAsURL(final String resource) { - ClassLoader classLoader = getClassLoaderForResource(resource); - return classLoader != null ? classLoader.getResource(resource) : null; - } - - /** - * Return an InputStream to access a resource available to the active classloader for the calling thread. - * - * @param resource String representation of the location of the resource on the classpath - * @return An {@link InputStream} that reads data from the resource - */ - public static InputStream getResourceAsStream(final String resource) { - ClassLoader classLoader = getClassLoaderForResource(resource); - return classLoader != null ? classLoader.getResourceAsStream(resource) : null; - } - - /** - * Loads a class with the given name using the active classloader for the current thread. - * - * @param className String with fully qualified class name of the desired class - * @param Final type of the loaded class - * @return Class representing the loaded type - * @throws ClassNotFoundException If no class with this name exists - */ - @SuppressWarnings("unchecked") - public static Class forName(final String className) throws ClassNotFoundException { - ClassLoader classLoader = getClassLoaderForClass(className); - return (Class) Class.forName(className, true, classLoader); - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java b/core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java deleted file mode 100644 index be81746..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.util; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.Enumeration; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Set; - -/** - *

The Demoiselle's ResourceBundle extends the abstraction {@link java.util.ResourceBundle}, - * and provide the locale and the base name for the bundle.

- * - *

To select which resource properties file to load when injecting beans of this class, qualify - * the injection point with {@link org.demoiselle.annotation.Name}, using the resource name (without - * the '.properties' extension) as the value. If the injection point isn't qualified the default - * file messages.properties will be loaded from the root of the classpath.

- * - * @author SERPRO - */ -public class ResourceBundle extends java.util.ResourceBundle implements Serializable { - - private static final long serialVersionUID = 1L; - - private String baseName; - - private transient java.util.ResourceBundle delegate; - - private final Locale locale; - - private java.util.ResourceBundle getDelegate() { - if (delegate == null) { - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - delegate = ResourceBundle.getBundle(baseName, locale, classLoader); - - } catch (MissingResourceException mre) { - delegate = ResourceBundle.getBundle(baseName, locale); - } - } - - return delegate; - } - - /** - * Constructor that set values of baseName and locale. - * - * @param baseName - * the base name to construct the complete bundle name. - * - * @param locale - * locale to define the choosen bundle. - */ - public ResourceBundle(String baseName, Locale locale) { - this.baseName = baseName; - this.locale = locale; - } - - @Override - public boolean containsKey(String key) { - return getDelegate().containsKey(key); - } - - @Override - public Enumeration getKeys() { - return getDelegate().getKeys(); - } - - @Override - public Locale getLocale() { - return getDelegate().getLocale(); - } - - @Override - public Set keySet() { - return getDelegate().keySet(); - } - - public String getString(String key, Object... params) { - return Strings.getString(getString(key), params); - } - - @Override - protected Object handleGetObject(String key) { - Object result; - - try { - Method method = getDelegate().getClass().getMethod("handleGetObject", String.class); - - method.setAccessible(true); - result = method.invoke(delegate, key); - method.setAccessible(false); - - } catch (Exception cause) { - throw new RuntimeException(cause); - } - - return result; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/core/util/Strings.java b/core/src/main/java/org/demoiselle/jee/core/util/Strings.java deleted file mode 100644 index d0c01a3..0000000 --- a/core/src/main/java/org/demoiselle/jee/core/util/Strings.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.core.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.demoiselle.jee.core.annotation.Ignore; - -/** - * Contain a set of methods that implements a set of functionalities that - * envolves manipulation of strings. - * - * @author SERPRO - */ -public final class Strings { - - private Strings() { - } - - /** - * Returns if some string matches with the format of a ResourceBundle key or - * not. - * - * @param key string to check if matches with key format of ResourceBundle. - * @return boolean true if matches and false otherwise. - */ - public static boolean isResourceBundleKeyFormat(final String key) { - return Pattern.matches("^\\{(.+)\\}$", key == null ? "" : key); - } - - /** - * Removes specific characteres from a given string. - * - * @param string string to be changed, by the removing of some characters. - * @param chars characters to be removed from string. - * @return String returns the given string without the given characters. - */ - public static String removeChars(String string, char... chars) { - String result = string; - - if (result != null) { - for (char ch : chars) { - result = result.replace(String.valueOf(ch), ""); - } - } - return result; - } - - public static String join(String separator, String... strings) { - StringBuffer result = new StringBuffer(); - - if (strings != null) { - for (int i = 0; i < strings.length; i++) { - if (i != 0 && separator != null) { - result.append(separator); - } - - if (strings[i] != null) { - result.append(strings[i]); - } - } - } - - return result.length() > 0 ? result.toString() : null; - } - - /** - * Inserts the character "0" in the begin of a given string. The quantity of - * zeros that will be placed depends on the difference between the length of - * the given string and the value of howMuchZeros. - * - * @param string string to insert zeros characthers. - * @param howMuchZeros its controls how much zeros will be insert. - * @return String Retuns the string, added with appropriate number of zeros. - * For exemplo, if string = "yes" and howMuchZeros = 5, the returned string - * will be "00yes". - */ - public static String insertZeros(String string, int howMuchZeros) { - StringBuffer result = new StringBuffer((string == null ? "" : string).trim()); - int difference = howMuchZeros - result.toString().length(); - - for (int j = 0; j < difference; j++) { - result.insert(0, '0'); - } - - return result.toString(); - } - - /** - * * Replaces the numbers between braces in the given string with the given - * parameters. The process will replace a number between braces for the - * parameter for which its order in the set of parameters matches with the - * number of the given string. For exemple, if is received the following - * string "Treats an {0} exception" and the set of parameters - * {"DemoiselleException"}, the return will be the following string: "Treats - * an DemoiselleException exception". - * - * @param string with the numbers with braces to be replaced with the - * parameters. - * @param params parameters that will replace the number with braces in the - * given string. - * @return String string with numbers replaced with the matching parameter. - */ - public static String getString(final String string, final Object... params) { - String result = null; - - if (string != null) { - result = new String(string); - } - - if (params != null && string != null) { - for (int i = 0; i < params.length; i++) { - if (params[i] != null) { - result = result.replaceAll("\\{" + i + "\\}", Matcher.quoteReplacement(params[i].toString())); - } - } - } - - return result; - } - - /** - * Verifies if a given string is empty or null. - * - * @param string string to be verified. - * @return boolean returns true if the given string is empty or null and - * returns false otherwise. - */ - public static boolean isEmpty(String string) { - return string == null || string.trim().isEmpty(); - } - - /** - * Converts any object to string. - * - * @param object object to be converted. - * @return String the given object converted to string. - */ - public static String toString(Object object) { - StringBuffer result = new StringBuffer(); - Object fieldValue; - - if (object != null) { - result.append(object.getClass().getSimpleName()); - result.append(" ["); - - boolean first = true; - for (Field field : Reflections.getNonStaticDeclaredFields(object.getClass())) { - if (!field.isAnnotationPresent(Ignore.class)) { - if (first) { - first = false; - } else { - result.append(", "); - } - - result.append(field.getName()); - result.append('='); - fieldValue = Reflections.getFieldValue(field, object); - result.append(fieldValue != null && fieldValue.getClass().isArray() - ? Arrays.toString((Object[]) fieldValue) - : fieldValue); - } - } - - result.append(']'); - } - - return result.toString(); - } - - /** - * Replace the camel case string for a lowercase string separated for a - * given symbol. - * - * @param string string that separeted with camel case. - * @param symbol simbol to be the new separator for the given string. - * @return String the given string separated with the given symbol. - */ - public static String camelCaseToSymbolSeparated(String string, String symbol) { - if (symbol == null) { - symbol = ""; - } - - return string == null ? null : string.replaceAll("\\B([A-Z])", symbol + "$1").toLowerCase(); - } - - /** - * Sets the first character of a given string to upper case. - * - * @param string Full string to convert - * @return String the given string with the first character setted to upper - * case. - */ - public static String firstToUpper(String string) { - String result = string; - - if (!Strings.isEmpty(string)) { - result = string.toUpperCase().charAt(0) + (string.length() > 1 ? string.substring(1) : ""); - } - - return result; - } - - /** - * Removes braces from a given string. - * - * @param string Message to remove braces from - * @return String the given string without braces. - */ - public static String removeBraces(String string) { - String result = string; - - if (isResourceBundleKeyFormat(string)) { - result = string.substring(1, string.length() - 1); - } - - return result; - } - - /** - * Inserts braces in a given string. - * - * @param string Original string to insert braces on. - * @return String the given string with braces. - */ - public static String insertBraces(String string) { - String result = string; - - if (!isEmpty(string)) { - result = "{" + string + "}"; - } - - return result; - } - - public static String parse(InputStream inputStream) throws IOException { - StringBuilder result = new StringBuilder(); - - if (inputStream != null) { - BufferedReader reader = null; - - try { - reader = new BufferedReader(new InputStreamReader(inputStream)); - String line; - - while ((line = reader.readLine()) != null) { - result.append(line); - } - - } finally { - if (reader != null) { - reader.close(); - } - } - } - - return result.length() > 0 ? result.toString() : null; - } -} diff --git a/core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java b/core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java deleted file mode 100644 index 396eb44..0000000 --- a/core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.stereotype; - -import javax.enterprise.inject.Stereotype; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Identifies a business controller class. Business controller objects typically implement the controller design - * pattern, i.e., they contain no data elements but methods that orchestrate interaction among business entities. - *

- * A Business Controller is: - *

    - *
  • defined when annotated with {@code @BusinessController}
  • - *
  • automatically injected whenever {@code @Inject} is used
  • - *
- * - * @author SERPRO - * @see Controller - */ -@Controller -@Stereotype -@Inherited -@Target(TYPE) -@Retention(RUNTIME) -public @interface BusinessController { -} diff --git a/core/src/main/java/org/demoiselle/jee/stereotype/Controller.java b/core/src/main/java/org/demoiselle/jee/stereotype/Controller.java deleted file mode 100644 index f26104b..0000000 --- a/core/src/main/java/org/demoiselle/jee/stereotype/Controller.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.stereotype; - -import javax.interceptor.InterceptorBinding; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Identifies a controller class or stereotype, the latter being most suitable for it. - * - * @author SERPRO - */ -@InterceptorBinding -@Inherited -@Target({ TYPE, METHOD }) -@Retention(RUNTIME) -public @interface Controller { -} diff --git a/core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java b/core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java deleted file mode 100644 index c0ba5ff..0000000 --- a/core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.stereotype; - -import javax.enterprise.inject.Stereotype; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Identifies a persistence controller class. A persistence controller is - * a layer which provides simplified access to data stored in persistent storage - * of some kind, such as an entity-relational database. - *

- * A Persitence Controller is: - *

    - *
  • defined when annotated with {@code @PersistenceController}
  • - *
  • automatically injected whenever {@code @Inject} is used
  • - *
- * - * @author SERPRO - * @see Controller - */ -@Controller -@Stereotype -@Inherited -@Target(TYPE) -@Retention(RUNTIME) -public @interface PersistenceController { -} diff --git a/core/src/main/java/org/demoiselle/jee/stereotype/RestController.java b/core/src/main/java/org/demoiselle/jee/stereotype/RestController.java deleted file mode 100644 index bd9b9e0..0000000 --- a/core/src/main/java/org/demoiselle/jee/stereotype/RestController.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.stereotype; - -import javax.enterprise.inject.Stereotype; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Identifies a facade class. A facade is an object that provides a - * simplified interface to a larger body of code, such as a class library. - *

- * A Facade is: - *

    - *
  • defined when annotated with {@code @FacadeController}
  • - *
  • automatically injected whenever {@code @Inject} is used
  • - *
- * - * @author SERPRO - * @see Controller - */ -@Controller -@Stereotype -@Inherited -@Target(TYPE) -@Retention(RUNTIME) -public @interface RestController { -} diff --git a/core/src/main/resources/demoiselle.properties b/core/src/main/resources/demoiselle.properties deleted file mode 100644 index 71ae24e..0000000 --- a/core/src/main/resources/demoiselle.properties +++ /dev/null @@ -1,5 +0,0 @@ -# Enables JPA transaction strategy, automatically detected if demoiselle-jpa component is detected. Use only if you need to overwrite the default behaviour -#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JPATransaction - -# Enables JTA transaction strategy, automatically detected if demoiselle-jta component is detected. Use only if you need to overwrite the default behaviour -#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JTATransaction diff --git a/core/src/main/resources/messages.properties b/core/src/main/resources/messages.properties deleted file mode 100644 index 62cae56..0000000 --- a/core/src/main/resources/messages.properties +++ /dev/null @@ -1,81 +0,0 @@ - -version=${project.version} -engine-on=Iniciando o Demoiselle Framework ${project.version} (Neo) -resource-not-found=Arquivo {0} n\u00e3o foi encontrado -key-not-found=A chave {0} n\u00e3o foi encontrada -ambiguous-strategy-resolution=Foi detectada ambiguidade da interface {0} com as seguintes implementa\u00e7\u00f5es\: {1}. Para resolver o conflito, defina explicitamente a implementa\u00e7\u00e3o no demoiselle.properties. -ambiguous-bean-resolution=Falha ao obter {0} pois foi detectada ambiguidade nas seguintes implementa\u00e7\u00f5es\: {1} -bean-not-found=Voc\u00ea est\u00e1 tentando obter um objeto n\u00e3o reconhecido pelo CDI via Beans.getReference({0}) -store-not-found=O objeto do tipo [{0}] n\u00e3o pode ser armazenado no escopo indicado\: {1} -more-than-one-exceptionhandler-defined-for-same-class=Foi definido mais de um m\u00e9todo na classe {0} para tratar a exce\u00e7\u00e3o {1} -handling-exception=Tratando a exce\u00e7\u00e3o {0} -taking-off=O Demoiselle ${project.version} decolou -engine-off=Desligando os motores do Demoiselle ${project.version} -setting-up-bean-manager=BeanManager dispon\u00edvel atrav\u00e9s do utilit\u00e1rio {0} - -user-transaction-lookup-fail=N\u00e3o foi encontrada nenhuma transa\u00e7\u00e3o com o nome {0} no contexto JNDI -transactional-execution=Execu\u00e7\u00e3o transacional de {0} -begin-transaction=Transa\u00e7\u00e3o iniciada -transaction-marked-rollback=Transa\u00e7\u00e3o marcada para rollback [{0}] -transaction-already-finalized=A transa\u00e7\u00e3o j\u00e1 havia sido finalizada -transaction-commited=Transa\u00e7\u00e3o finalizada com sucesso -transaction-rolledback=Transa\u00e7\u00e3o finalizada com rollback - -bootstrap.configuration.processing=Processando {0} -bootstrap-context-already-managed=O contexto {0} para o escopo {1} j\u00e1 foi adicionado -bootstrap-context-added=Adicionando o contexto {0} para o escopo {1} - -loading-configuration-class=Carregando a classe de configura\u00e7\u00e3o {0} -configuration-field-loaded={0}: {2} -configuration-attribute-is-mandatory=A configura\u00e7\u00e3o {0} \u00e9 obrigat\u00f3ria, mas n\u00e3o foi encontrada em {1} -configuration-name-attribute-cant-be-empty=A nota\u00e7\u00e3o @Name n\u00e3o pode estar em branco -configuration-generic-extraction-error=Ocorreu um erro durante a extra\u00e7\u00e3o do tipo {0} com o extrator {1} -configuration-dot-after-prefix=N\u00e3o \u00e9 necess\u00e1rio adicionar o ponto ap\u00f3s o prefixo para uma classe de configura\u00e7\u00e3o. \u00c9 recomendado que sejam retirados, pois poder\u00e3o causar erros em vers\u00f5es futuras do Framework. -configuration-key-not-found={0}\: [n\u00e3o encontrada] -configuration-extractor-not-found=N\u00e3o foi poss\u00edvel encontrar a classe extratora para o atributo {0}. Implemente a interface {1} para criar sua classe extratora. -configuration-not-conversion=N\u00e3o \u00e9 poss\u00edvel converter o valor {0} para o tipo {1} - -transaction-not-defined=Nenhuma transa\u00e7\u00e3o foi definida. Para utilizar @{0} \u00e9 preciso definir a propriedade frameworkdemoiselle.transaction.class com a estrat\u00e9gia de transa\u00e7\u00e3o desejada no arquivo demoiselle.properties -executing-all=Executando m\u00e9todos anotados com @{0} -custom-context-selected=Produzindo inst\u00e2ncia do contexto {0} -custom-context-was-activated=O contexto {0} foi ativado para o escopo {1} -custom-context-was-deactivated=O contexto {0} foi desativado para o escopo {1} -custom-context-already-activated=N\u00e3o foi poss\u00edvel ativar o contexto {0}, o escopo {1} j\u00e1 est\u00e1 ativo no contexto {2} -custom-context-not-found=N\u00e3o foi encontrado um contexto gerenciado do tipo [{0}] para o escopo [{1}] -custom-context-manager-not-initialized=ContextManager n\u00e3o foi inicializado. Chame [initialize] ao capturar o evento [AfterBeanDiscovery] em uma extens\u00e3o CDI - -error-creating-new-instance-for=Error creating a new instance for "{0}" -executed-successfully={0} execultado com sucesso -must-declare-one-single-parameter=Voc\u00ea deve declarar um par\u00e2metro \u00fanico em {0} -loading-default-transaction-manager=Carregando o gerenciador de transa\u00e7\u00e3o padr\u00e3o {0} -results-count-greater-page-size=Quantidade de resultados {0} \u00e9 maior que o tamanho da p\u00e1gina {1} -page-result=Resultado paginado [p\u00e1gina\={0}, total de resultados\={1}] -pagination-not-initialized=Pagina\u00e7\u00e3o n\u00e3o inicializada. Inicialize o sistema de pagina\u00e7\u00e3o definindo a p\u00e1gina atual ou o total de resultados ao menos uma vez na requisi\u00e7\u00e3o. -pagination-invalid-value=Valor inv\u00e1lido para paginador: [{0}]. -page=P\u00e1gina [n\u00famero\={0}, tamanho\={1}] -processing=Processando\: {0} -processing-fail=Falha no processamento devido a uma exce\u00e7\u00e3o lan\u00e7ada pela aplica\u00e7\u00e3o -for= \ para\: -file-not-found=O arquivo {0} n\u00e3o foi encontrado - -management-notification-attribute-changed=O atributo [{0}] da classe gerenciada [{1}] foi alterado -management-null-class-defined=O controlador de gerenciamento informado n\u00e3o pode ser [null] -management-abstract-class-defined=O controlador de gerenciamento [{0}] precisa ser uma classe concreta -management-no-annotation-found=Classe {0} precisa ser anotada com @ManagementController -management-invalid-property-no-getter-setter=Falha ao inicializar classe gerenciada {0}, n\u00e3o foi encontrado um m\u00e9todo get ou m\u00e9todo set para a propriedade {1} -management-invalid-property-as-operation=Falha ao inicializar classe gerenciada {0}, n\u00e3o \u00e9 poss\u00edvel declarar uma propriedade cujo m\u00e9todo get ou set \u00e9 uma opera\u00e7\u00e3o -management-introspection-error=Erro ao ler atributos da classe gerenciada {0} -management-type-not-found=A classe gerenciada informada n\u00e3o existe\: {0} -management-invoke-error=Erro ao tentar invocar a opera\u00e7\u00e3o "{0}" da classe gerenciada, a opera\u00e7\u00e3o n\u00e3o foi encontrada -management-write-value-error=N\u00e3o foi poss\u00edvel definir um valor para a propriedade {0} -management-read-value-error=N\u00e3o foi poss\u00edvel ler o valor da propriedade {0} -management-debug-acessing-property=Acessando propriedade {0} da classe gerenciada {1} -management-debug-setting-property=Definindo novo valor para propriedade {0} da classe gerenciada {1} -management-debug-invoking-operation=Invocando opera\u00e7\u00e3o {0} da classe gerenciada {1} -management-debug-starting-custom-context=Levantando contexto {0} para executar comando na classe gerenciada {1} -management-debug-stoping-custom-context=Desligando contexto {0} para classe gerenciada {1} -management-debug-registering-managed-type=Registrando classe gerenciada [{0}] -management-debug-processing-management-extension=Processando extens\u00e3o de gerenciamento [{0}] -management-debug-removing-management-extension=Desativando extens\u00e3o de gerenciamento [{0}] -management-validation-constraint-violation=Ocorreu um erro de valida\u00e7\u00e3o na classe [{0}] ao definir um valor para a propriedade [{1}]\: [{2}] -management-validation-validator-not-found=Nenhum provedor de valida\u00e7\u00e3o de beans encontrado, as anota\u00e7\u00f5es de valida\u00e7\u00e3o n\u00e3o ser\u00e3o processadas diff --git a/demoiselle-core/.gitignore b/demoiselle-core/.gitignore new file mode 100644 index 0000000..d38113d --- /dev/null +++ b/demoiselle-core/.gitignore @@ -0,0 +1,5 @@ +.settings +.classpath +.project +/bin/ +/target/ diff --git a/demoiselle-core/pom.xml b/demoiselle-core/pom.xml new file mode 100644 index 0000000..dfcbba0 --- /dev/null +++ b/demoiselle-core/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-core + 3.0.0-SNAPSHOT + jar + + Demoiselle Core + + Contém funcionalidades comuns a todos os módulos framework. + + + http://demoiselle.org + + + + UTF-8 + 1.8 + 1.8 + + + + javax + javaee-web-api + 7.0 + + + javax.enterprise + cdi-api + 1.2 + + + + + org.apache.deltaspike.core + deltaspike-core-api + compile + 1.7.1 + + + org.apache.deltaspike.core + deltaspike-core-impl + runtime + 1.7.1 + + + diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java new file mode 100644 index 0000000..4c793da --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Ignore.java @@ -0,0 +1,56 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + *

Used in fields of classes annotated with {@link org.demoiselle.configuration.Configuration} + * to indicate that the system should ignore this field when population the new configuration + * instance with values extracted from the source file.

+ * + * @see org.demoiselle.configuration.Configuration + * @author SERPRO + */ +@Target(FIELD) +@Retention(RUNTIME) +public @interface Ignore { +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Name.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Name.java new file mode 100644 index 0000000..8e93aaa --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Name.java @@ -0,0 +1,98 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation; + +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.util.Nonbinding; +import javax.inject.Named; +import javax.inject.Qualifier; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + *

+ * String based non-binding qualifier. + *

+ * + *

+ * This annotation is used to qualify beans using an user defined String. {@link javax.enterprise.inject.Produces} + * methods can then read this string and use it to customize the bean creation process. + *

+ * + *

+ * The {@link #value()} attribute is non-binding (contrary to {@link Named#value()}, meaning multiple classes + * qualified with this annotation, even with different values, will be considered the same candidate for + * injection points. To avoid ambiguous resolutions and select which candidate to choose usually you'll need a + * producer method to read the string and select the best fitted candidate. + *

+ * + *

+ * The framework classes qualified with this annotation already have such producers and the accepted values for + * this annotation will be detailed in their respective documentations. + *

+ * + * + * @author SERPRO + * + * @see org.demoiselle.util.ResourceBundle + * @see org.demoiselle.internal.producer.ResourceBundleProducer#create(InjectionPoint) + * @see org.demoiselle.internal.producer.LoggerProducer#createNamed(InjectionPoint) + */ +@Qualifier +@Inherited +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +public @interface Name { + + /** + *

+ * Specifies a name to access a custom configuration that will change how the annotated bean works. + *

+ *

+ * This attribute is nonbinding so you can use the {@link Name} annotation to create {@linkplain javax.enterprise.inject.Produces} + * methods or fields and have only one producer that works with all injection points no matter the value of this attribute. + *

+ * @return Name of custom settings to personalize how the annotated bean works. + */ + @Nonbinding + String value() default ""; + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java new file mode 100644 index 0000000..e1d04ac --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Priority.java @@ -0,0 +1,96 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + *

+ * Used to prioritize some execution flow, as methods annotated with @startup or @shutdown, + * or some interface implementation. + *

+ * + * @author SERPRO + */ +@Target({ TYPE, METHOD }) +@Retention(RUNTIME) +public @interface Priority { + + /** + * Most important priority value. + */ + static int MAX_PRIORITY = Integer.MIN_VALUE; + + /** + * Less important priority value. + */ + static int MIN_PRIORITY = Integer.MAX_VALUE; + + /** + * Less important priority value. + */ + static int L1_PRIORITY = MIN_PRIORITY; + + /** + * Higher priority than L1_PRIORITY + */ + static int L2_PRIORITY = L1_PRIORITY - 100; + + /** + * Higher priority than L2_PRIORITY + */ + static int L3_PRIORITY = L2_PRIORITY - 100; + + /** + * Higher priority than L3_PRIORITY + */ + static int L4_PRIORITY = L3_PRIORITY - 100; + + /** + *

+ * An integer value defines the priority order. The lower the value, the greater priority. + *

+ * + * @return Priority value, lower values have higher priority. + */ + int value(); +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java new file mode 100644 index 0000000..335692f --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Strategy.java @@ -0,0 +1,83 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.inject.Qualifier; + +/** + * + *

+ * This literal marks a bean to be selected at runtime based on a priority system. + * The user qualifies the injection point with this literal and then at runtime + * the CDI engine will circle through all candidate subtypes to be injected + * that are annotated with {@link Priority}. If there is only one subtype with the + * highest priority then this one will be selected to be injected. + *

+ * + *

+ * This allows users to plug in libraries with new candidates and have them be selected + * if their priority values are higher than the default values already present. One example + * is the {@link org.demoiselle.security.Authorizer} type, the framework has a {@link org.demoiselle.internal.implementation.DefaultAuthorizer} + * with {@link Priority#L1_PRIORITY the lowest priority} but the user can add libraries with new + * implementations of {@link org.demoiselle.security.Authorizer} annotated with higher priorities, the code will + * then automatically select these new implementations with no extra configuration. + *

+ * + *

+ * This annotation must be used with supported types. Usually this involves creating {@link javax.enterprise.inject.Produces} CDI + * producer methods that will select the correct strategy. To create your own producer + * methods that support strategy selection, use the utility {@linkplain org.demoiselle.internal.producer.StrategySelector}. + *

+ * + * @author SERPRO + */ +@Qualifier +@Inherited +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +public @interface Strategy { + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Type.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Type.java new file mode 100644 index 0000000..6552005 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/Type.java @@ -0,0 +1,60 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.core.annotation; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.enterprise.util.Nonbinding; +import javax.inject.Qualifier; + +/** + *

+ * Type based non-binding qualifier. + *

+ * + *

+ * This annotation is used to qualify beans using a class type. + * {@link javax.enterprise.inject.Produces} methods can then read this type and + * use it to customize the bean creation process. + *

+ * + *

+ * The {@link #value()} attribute is non-binding, meaning multiple classes + * qualified with this annotation, even with different values, will be + * considered the same candidate for injection points. To avoid ambiguous + * resolutions and select which candidate to choose usually you'll need a + * producer method to read the type and select the best fitted candidate. + *

+ * + *

+ * The framework classes qualified with this annotation already have such + * producers and the accepted values for this annotation will be detailed in + * their respective documentations. + *

+ * + * + * @author SERPRO + * + */ +@Qualifier +@Inherited +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +public @interface Type { + + @Nonbinding + Class value() default Object.class; + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java new file mode 100644 index 0000000..83eb0de --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NameQualifier.java @@ -0,0 +1,70 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation.literal; + +import org.demoiselle.jee.core.annotation.Name; + +import javax.enterprise.util.AnnotationLiteral; + +/** + * Annotation litteral that allows to create instances of the {@link Name} literal. The created instance can then be + * used to call {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)} + * + * @author SERPRO + * @see javax.enterprise.inject.spi.CDI + */ +@SuppressWarnings("all") +public class NameQualifier extends AnnotationLiteral implements Name { + + private static final long serialVersionUID = 1L; + + private final String value; + + /** + * Constructor with string value of name literal. + * + * @param value value of name literal. + */ + public NameQualifier(String value) { + this.value = value; + } + + @Override + public String value() { + return this.value; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java new file mode 100644 index 0000000..9f7e0fd --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/NamedQualifier.java @@ -0,0 +1,67 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation.literal; + +import javax.enterprise.util.AnnotationLiteral; +import javax.inject.Named; +import java.lang.annotation.Annotation; + +/** + * Annotation litteral that allows to create instances of the {@link Named} literal. + * Those instances can then be used to call + * {@link javax.enterprise.inject.spi.CDI#select(Class subtype, Annotation... qualifiers)} + * + * @see javax.enterprise.inject.spi.CDI + * @see Named + * + * @author SERPRO + */ +@SuppressWarnings("all") +public class NamedQualifier extends AnnotationLiteral implements Named { + + private static final long serialVersionUID = 6790759427086052113L; + + private String namedValue; + + public NamedQualifier(String value) { + namedValue = value; + } + + public String value() { + return namedValue; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java new file mode 100644 index 0000000..74290d5 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/StrategyQualifier.java @@ -0,0 +1,53 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation.literal; + +import org.demoiselle.jee.core.annotation.Strategy; + +import javax.enterprise.util.AnnotationLiteral; + +/** + * Annotation litteral that allows to create instances of the {@link Strategy} literal. The created instance can then be + * used to call {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)}. + * + * @see javax.enterprise.inject.spi.CDI + * @author SERPRO + */ +@SuppressWarnings("all") +public class StrategyQualifier extends AnnotationLiteral implements Strategy { + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java new file mode 100644 index 0000000..e7513e8 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/annotation/literal/TypeQualifier.java @@ -0,0 +1,71 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.annotation.literal; + +import org.demoiselle.jee.core.annotation.Type; + +import javax.enterprise.util.AnnotationLiteral; + +/** + * Annotation litteral that allows to create instances of the {@link Type} + * literal. The created instance can then be used to call + * {@link javax.enterprise.inject.spi.CDI#select(Class subtype, java.lang.annotation.Annotation... qualifiers)}. + * + * @see javax.enterprise.inject.spi.CDI + * @author SERPRO + */ +@SuppressWarnings("all") +public class TypeQualifier extends AnnotationLiteral implements Type { + + private static final long serialVersionUID = 1L; + + private final Class value; + + /** + * Constructor with string value of name literal. + * + * @param value value of name literal. + */ + public TypeQualifier(Class value) { + this.value = value; + } + + @Override + public Class value() { + return this.value; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/crud/package-info.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/crud/package-info.java new file mode 100644 index 0000000..88135d8 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/crud/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas aos + * facilitadores de CRUD do framework Demoiselle. + */ +package org.demoiselle.jee.core.crud; \ No newline at end of file diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java new file mode 100644 index 0000000..ec72e53 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/exception/DemoiselleException.java @@ -0,0 +1,57 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.core.exception; + +/** + * Exception class intended to be used by framework configuration and to be derived by other framework exceptions. + * + * @author SERPRO + */ +public class DemoiselleException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor . + * + */ + public DemoiselleException() { + + } + + /** + * Constructor with message. + * + * @param message + * exception message + */ + public DemoiselleException(String message) { + super(message); + } + + /** + * Constructor with cause. + * + * @param cause + * exception cause + */ + public DemoiselleException(Throwable cause) { + super(cause); + } + + /** + * Constructor with message and cause. + * + * @param message + * exception message + * @param cause + * exception cause + */ + public DemoiselleException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java new file mode 100644 index 0000000..53e534c --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/LoggerProducer.java @@ -0,0 +1,45 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.core.internal.producer; + +import java.io.Serializable; +import java.util.logging.Logger; +import javax.enterprise.context.Dependent; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; + +/** + * + * @author 70744416353 + */ +@Dependent +public class LoggerProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + /* + * Produces a default {@link Logger} instance. If it's possible + * to infer the injection point's parent class then this class'es + * name will be used to categorize the logger, if not then + * the logger won't be categorized. + * + */ + @Default + @Produces + public static final Logger create(final InjectionPoint ip) { + String name; + + if (ip != null && ip.getMember() != null) { + name = ip.getMember().getDeclaringClass().getName(); + } else { + name = "not.categorized"; + } + + return Logger.getLogger(name); + } + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java new file mode 100644 index 0000000..325e320 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/internal/producer/ResourceBundleProducer.java @@ -0,0 +1,75 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.core.internal.producer; + +import java.io.Serializable; +import java.util.Locale; + +import javax.enterprise.context.Dependent; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.CDI; +import javax.enterprise.inject.spi.InjectionPoint; + +import org.demoiselle.jee.core.annotation.Name; +import org.demoiselle.jee.core.util.CDIUtils; +import org.demoiselle.jee.core.util.ResourceBundle; + +/** + * + * @author 70744416353 + */ +@Dependent +public class ResourceBundleProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + @Default + @Produces + public ResourceBundle createDefault() { + return create((String) null); + } + + /* + * Produces a {@link java.util.ResourceBundle} instance loading the properties file whose name + * is defined by the {@link Name} literal. If no value is specified + * then the default "messages.properties" file is loaded. + */ + @Name + @Produces + public ResourceBundle create(InjectionPoint ip) { + String baseName = null; + if (ip != null && ip.getQualifiers() != null) { + Name nameQualifier = CDIUtils.getQualifier(Name.class, ip); + if (nameQualifier != null) { + baseName = nameQualifier.value(); + if ("".equals(baseName)) { + baseName = null; + } + } + } + + return create(baseName); + } + + @SuppressWarnings("serial") + public static ResourceBundle create(String baseName) { + ResourceBundle bundle; + + try { + bundle = baseName != null + ? new ResourceBundle(baseName, CDI.current().select(Locale.class).get()) { + } + : new ResourceBundle("messages", CDI.current().select(Locale.class).get()); + } catch (RuntimeException e) { + bundle = baseName != null + ? new ResourceBundle(baseName, Locale.getDefault()) + : new ResourceBundle("messages", Locale.getDefault()); + } + + return bundle; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java new file mode 100644 index 0000000..b98fa04 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/lifecycle/LifecycleAnnotation.java @@ -0,0 +1,30 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.core.lifecycle; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Annotate other annotations with this one to + * mark them as lifecycle annotations, meaning + * the lifecycle processor of the framework will + * read them and fire events based on their represented + * lifecycle stages. + * + * @author SERPRO + */ +@Inherited +@Target(ElementType.ANNOTATION_TYPE) +@Retention(RUNTIME) +public @interface LifecycleAnnotation { + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/messages/DemoiselleMessages.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/messages/DemoiselleMessages.java new file mode 100644 index 0000000..b0e806f --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/messages/DemoiselleMessages.java @@ -0,0 +1,51 @@ +package org.demoiselle.jee.core.messages; + +import org.apache.deltaspike.core.api.message.MessageBundle; +import org.apache.deltaspike.core.api.message.MessageTemplate; + +@MessageBundle +public interface DemoiselleMessages { + + @MessageTemplate("{version}") + String version(); + + @MessageTemplate("{engine-on}") + String engineOn(); + + @MessageTemplate("{resource-not-found}") + String resourceNotFound(); + + @MessageTemplate("{key-not-found}") + String keyNotFound(String key); + + @MessageTemplate("{ambiguous-strategy-resolution}") + String ambiguousStrategyResolution(String interfaceString, String implementations); + + @MessageTemplate("{ambiguous-bean-resolution}") + String ambiguousBeanResolution(String implementation); + + @MessageTemplate("{bean-not-found}") + String beanNotFound(String bean); + + @MessageTemplate("{store-not-found}") + String storeNotFound(String object, String scope); + + @MessageTemplate("{more-than-one-exceptionhandler-defined-for-same-class}") + String moreThanOneExceptionhandlerDefinedForSameClass(String clazz, String ex); + + @MessageTemplate("{handling-exception}") + String handlingException(String ex); + + @MessageTemplate("{taking-off}") + String takingOff(); + + @MessageTemplate("{engine-off}") + String engineOff(String ex); + + @MessageTemplate("{setting-up-bean-manager}") + String settingUpBeanManagerException(String util); + + @MessageTemplate("{processing-fail}") + String processingFail(); + +} \ No newline at end of file diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java new file mode 100644 index 0000000..69fe64a --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/CDIUtils.java @@ -0,0 +1,115 @@ +package org.demoiselle.jee.core.util; + +import java.lang.annotation.Annotation; +import java.util.Collection; + +import javax.enterprise.inject.spi.InjectionPoint; + +/** + * Utility class to peform useful operations on CDI discovered beans. + * + * @author SERPRO + */ +public final class CDIUtils { + + private static final Annotation[] annotationArrayType = new Annotation[0]; + + /** + * Returns true if one annotation of the provided type is present + * on a list of annotations. + * + * @param annotationType Annotation type being looked for. + * @param allAnnotations List of all annotations where to look for. + * @return true if the annotation is present on the list + */ + public static boolean hasAnnotation(Class annotationType, Annotation... allAnnotations) { + for (Annotation currentAnnotation : allAnnotations) { + if (currentAnnotation.annotationType().isAssignableFrom(annotationType)) { + return true; + } + } + + return false; + } + + /** + * @param annotationType Type of the annotation being checked + * @param allAnnotations List of annotations to check for the specific one + * @see #hasAnnotation(Class, Annotation...) + * @return true if the annotation is present on the list + */ + public static boolean hasAnnotation(Class annotationType, + Collection allAnnotations) { + return hasAnnotation(annotationType, allAnnotations.toArray(annotationArrayType)); + } + + /** + * Returns true if a base class is annotated with the provided annotation. + * + * @param annotationType Annotation type to look for + * @param baseType Class to check for the informed annotation + * @see #hasAnnotation(Class, Annotation...) + * @return true if the annotation is present on the list + */ + public static boolean hasAnnotation(Class annotationType, Class baseType) { + return hasAnnotation(annotationType, baseType.getAnnotations()); + } + + /** + * Returns the annotation instance that matches the annotation type provided, + * or null if no annotation of that type is present. + * + * @param annotationType Annotation type being looked for. + * @param allAnnotations List of all annotations where to look for. + * @param Type of the specific annotation returned + * @return The annotation instance found, or null if there is no such annotation present. + */ + @SuppressWarnings("unchecked") + public static T getAnnotation(Class annotationType, Annotation... allAnnotations) { + for (Annotation currentAnnotation : allAnnotations) { + if (currentAnnotation.annotationType().isAssignableFrom(annotationType)) { + return (T) currentAnnotation; + } + } + + return null; + } + + /** + * @param annotationType Annotation type being looked for. + * @param allAnnotations List of all annotations where to look for. + * @param Type of the specific annotation returned + * @see #getAnnotation(Class, Annotation...) + * @return The annotation instance found, or null if there is no such annotation present. + */ + public static T getAnnotation(Class annotationType, + Collection allAnnotations) { + return getAnnotation(annotationType, allAnnotations.toArray(annotationArrayType)); + } + + /** + * Returns true if one qualifier of the provided type is present + * on an injection point. + * + * @param qualifierAnnotationType Annotation type being looked for. + * @param ip Injection point of a bean type. + * @return true if the annotation is present on the list + */ + public static boolean hasQualifier(Class qualifierAnnotationType, InjectionPoint ip) { + return hasAnnotation(qualifierAnnotationType, ip.getQualifiers()); + } + + /** + * Returns the annotation instance that matches the annotation type provided, + * or null if no annotation of that type is present. + * + * @param qualifierAnnotationType Annotation type being looked for. + * @param ip Injection point of a bean type. + * @param Type of the specific annotation returned + * @return The annotation instance found, or null if there is no such annotation present. + */ + public static T getQualifier(Class qualifierAnnotationType, InjectionPoint ip) { + return getAnnotation(qualifierAnnotationType, ip.getQualifiers()); + } + +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java new file mode 100644 index 0000000..cd2c6da --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Exceptions.java @@ -0,0 +1,67 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.util; + +/** + *Class that offer tow methods that can help with manipulation of throwable exceptions. + * + * @author SERPRO + */ +public final class Exceptions { + + /** + * Constructor without parameters. + */ + private Exceptions() { + } + + /** + * Receives as parameter any kind of Throwable objects, and throws a RuntimeException instead. + * + * @param throwable + * a throwable object. + * + * @throws RuntimeException throws this kind of exception every time that is called. + */ + public static void handleToRuntimeException(final Throwable throwable) throws RuntimeException { + if (throwable instanceof RuntimeException) { + throw (RuntimeException) throwable; + } else { + throw new RuntimeException(throwable); + } + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Reflections.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Reflections.java new file mode 100644 index 0000000..06a1670 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Reflections.java @@ -0,0 +1,367 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.util; + +import java.io.InputStream; +import java.lang.reflect.*; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Provides some features to do some operations relating to java reflection. + * + * @author SERPRO + */ +public class Reflections { + + protected Reflections() { + // Impede instanciar subclasses desse tipo. + throw new UnsupportedOperationException(); + } + + /** + * Return the parametized type used with a concrete implementation of a class that accepts generics. Ex: If you + * declare + *
+	 * public class SpecializedCollection implements Collection<SpecializedType> {
+	 *   // ...
+	 * }
+	 * 
+ * then the code getGenericTypeArgument(SpecializedCollection.class , 0); will return the type + * SpecializedType. + * + * @param type Base type to check for generic arguments + * @param idx zero based index of the generic argument to get + * @param Type of the generic argument + * @return The class representing the type of the generic argument + */ + @SuppressWarnings("unchecked") + public static Class getGenericTypeArgument(final Type type, final int idx) { + ParameterizedType paramType; + try { + paramType = (ParameterizedType) type; + } catch (ClassCastException cause) { + return getGenericTypeArgument((Class) type, idx); + } + + return (Class) paramType.getActualTypeArguments()[idx]; + } + + /** + * Return the parametized type used with a concrete implementation of a class that accepts generics. Ex: If you + * declare + *
+	 * 
+	 * public class SpecializedCollection implements Collection<SpecializedType> {
+	 *   // ...
+	 * }
+	 * 
+	 * 
+ * then the code getGenericTypeArgument(SpecializedCollection.class , 0); will return the type + * SpecializedType. + * + * @param clazz Base type to check for generic arguments + * @param idx zero based index of the generic argument to get + * @param Type of the generic argument + * @return The class representing the type of the generic argument + */ + @SuppressWarnings("unchecked") + public static Class getGenericTypeArgument(final Class clazz, final int idx) { + final Type type = clazz.getGenericSuperclass(); + + ParameterizedType paramType; + try { + paramType = (ParameterizedType) type; + } catch (ClassCastException cause) { + return getGenericTypeArgument((Class) type, idx); + } + + return (Class) paramType.getActualTypeArguments()[idx]; + } + + /** + *

+ * Return the parametized type passed to field types that accepts Generics. + *

+ * Ex: If you declare + *
+	 * 
+	 * public class MyClass{
+	 *    private Collection<String> myStringCollection;
+	 * }
+	 * 
+	 * 
+ * then the code getGenericTypeArgument( MyClass.class.getDeclaredField("myStringCollection") , 0); + * will return the type String. + * + * @param field Field which type is generified + * @param idx zero based index of the generic argument to get + * @param Type of the generic argument + * @return The class representing the type of the generic argument + */ + @SuppressWarnings("unchecked") + public static Class getGenericTypeArgument(final Field field, final int idx) { + final Type type = field.getGenericType(); + final ParameterizedType paramType = (ParameterizedType) type; + + return (Class) paramType.getActualTypeArguments()[idx]; + } + + /** + *

+ * Return the parametized type passed to members (fields or methods) that accepts Generics. + *

+ * + * @param member Member which type is generified + * @param idx zero based index of the generic argument to get + * @param Type of the generic argument + * @return The class representing the type of the generic argument + * @see #getGenericTypeArgument(Field field, int idx) + */ + public static Class getGenericTypeArgument(final Member member, final int idx) { + Class result = null; + + if (member instanceof Field) { + result = getGenericTypeArgument((Field) member, idx); + } else if (member instanceof Method) { + result = getGenericTypeArgument((Method) member, idx); + } + + return result; + } + + /** + *

+ * Return the parametized type passed to methods that accepts Generics. + *

+ * + * @param method Generified method reference + * @param idx zero based index of the generic argument to get + * @param Type of the generic argument + * @return The class representing the type of the generic argument + * @see #getGenericTypeArgument(Field field, int idx) + */ + @SuppressWarnings("unchecked") + public static Class getGenericTypeArgument(final Method method, final int idx) { + return (Class) method.getGenericParameterTypes()[idx]; + } + + /** + * Returns the value contained in the given field. + * + * @param field field to be extracted the value. + * @param object object that contains the field. + * @param Type of the generic argument + * @return value of the field. + */ + @SuppressWarnings("unchecked") + public static T getFieldValue(Field field, Object object) { + T result = null; + + try { + boolean acessible = field.isAccessible(); + field.setAccessible(true); + result = (T) field.get(object); + field.setAccessible(acessible); + + } catch (Exception e) { + Exceptions.handleToRuntimeException(e); + } + + return result; + } + + /** + * Sets a value in a field. + * + * @param field field to be setted. + * @param object object that contains the field. + * @param value value to be setted in the field. + */ + public static void setFieldValue(Field field, Object object, Object value) { + try { + boolean acessible = field.isAccessible(); + field.setAccessible(true); + field.set(object, value); + field.setAccessible(acessible); + + } catch (Exception e) { + Exceptions.handleToRuntimeException(e); + } + } + + /** + * @param type Base type to look for fields + * @return All non static fields from a certain type. Inherited fields are not returned, so if you need to get + * inherited fields you must iterate over this type's hierarchy. + */ + public static Field[] getNonStaticDeclaredFields(Class type) { + List fields = new ArrayList(); + + if (type != null) { + for (Field field : type.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers()) && !field.getType().equals(type.getDeclaringClass())) { + fields.add(field); + } + } + } + + return fields.toArray(new Field[0]); + } + + /** + * @param type Base type to look for fields + * @return All non static fields from a certain type, including fields declared in superclasses of this type. + */ + public static List getNonStaticFields(Class type) { + List fields = new ArrayList(); + + if (type != null) { + Class currentType = type; + while (currentType != null && !"java.lang.Object".equals(currentType.getCanonicalName())) { + fields.addAll(Arrays.asList(getNonStaticDeclaredFields(currentType))); + currentType = currentType.getSuperclass(); + } + } + + return fields; + } + + /** + * Instantiate an object of the given type. The default constructor with no parameters is used. + * + * @param clazz Base type of object to instantiate + * @param Final type of instantiated object + * @return New instance of provided type + */ + public static T instantiate(Class clazz) { + T object = null; + try { + object = clazz.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + Exceptions.handleToRuntimeException(e); + } + return object; + } + + /** + * Verifies if a given class could be converted to a given type. + * + * @param clazz class to be checked. + * @param type type to be checked. + * @return {@link Boolean} true if the given class can be converted to a given type, and false otherwise. + */ + public static boolean isOfType(Class clazz, Class type) { + return type.isAssignableFrom(clazz) && clazz != type; + } + + /** + * Obtains the {@link ClassLoader} for the given class, from his canonical name. + * + * @param canonicalName canonical name of the the given class. + * @return {@link ClassLoader} ClassLoader for the given class. + */ + public static ClassLoader getClassLoaderForClass(final String canonicalName) { + return Reflections.getClassLoaderForResource(canonicalName.replaceAll("\\.", "/") + ".class"); + } + + /** + * Obtains the {@link ClassLoader} for the given resource. + * + * @param resource String representation of the fully qualified path to the resource on the classpath + * @return {@link ClassLoader} ClassLoader for the given resource. + */ + public static ClassLoader getClassLoaderForResource(final String resource) { + final String stripped = resource.charAt(0) == '/' ? resource.substring(1) : resource; + + URL url = null; + ClassLoader result = Thread.currentThread().getContextClassLoader(); + + if (result != null) { + url = result.getResource(stripped); + } + + if (url == null) { + result = Reflections.class.getClassLoader(); + url = Reflections.class.getClassLoader().getResource(stripped); + } + + if (url == null) { + result = null; + } + + return result; + } + + /** + * Return an URL to access a resource available to the active classloader for the calling thread. + * + * @param resource String representation of the location of the resource on the classpath + * @return The {@link URL} for the resource + */ + public static URL getResourceAsURL(final String resource) { + ClassLoader classLoader = getClassLoaderForResource(resource); + return classLoader != null ? classLoader.getResource(resource) : null; + } + + /** + * Return an InputStream to access a resource available to the active classloader for the calling thread. + * + * @param resource String representation of the location of the resource on the classpath + * @return An {@link InputStream} that reads data from the resource + */ + public static InputStream getResourceAsStream(final String resource) { + ClassLoader classLoader = getClassLoaderForResource(resource); + return classLoader != null ? classLoader.getResourceAsStream(resource) : null; + } + + /** + * Loads a class with the given name using the active classloader for the current thread. + * + * @param className String with fully qualified class name of the desired class + * @param Final type of the loaded class + * @return Class representing the loaded type + * @throws ClassNotFoundException If no class with this name exists + */ + @SuppressWarnings("unchecked") + public static Class forName(final String className) throws ClassNotFoundException { + ClassLoader classLoader = getClassLoaderForClass(className); + return (Class) Class.forName(className, true, classLoader); + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java new file mode 100644 index 0000000..be81746 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/ResourceBundle.java @@ -0,0 +1,136 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.util; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Enumeration; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.Set; + +/** + *

The Demoiselle's ResourceBundle extends the abstraction {@link java.util.ResourceBundle}, + * and provide the locale and the base name for the bundle.

+ * + *

To select which resource properties file to load when injecting beans of this class, qualify + * the injection point with {@link org.demoiselle.annotation.Name}, using the resource name (without + * the '.properties' extension) as the value. If the injection point isn't qualified the default + * file messages.properties will be loaded from the root of the classpath.

+ * + * @author SERPRO + */ +public class ResourceBundle extends java.util.ResourceBundle implements Serializable { + + private static final long serialVersionUID = 1L; + + private String baseName; + + private transient java.util.ResourceBundle delegate; + + private final Locale locale; + + private java.util.ResourceBundle getDelegate() { + if (delegate == null) { + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + delegate = ResourceBundle.getBundle(baseName, locale, classLoader); + + } catch (MissingResourceException mre) { + delegate = ResourceBundle.getBundle(baseName, locale); + } + } + + return delegate; + } + + /** + * Constructor that set values of baseName and locale. + * + * @param baseName + * the base name to construct the complete bundle name. + * + * @param locale + * locale to define the choosen bundle. + */ + public ResourceBundle(String baseName, Locale locale) { + this.baseName = baseName; + this.locale = locale; + } + + @Override + public boolean containsKey(String key) { + return getDelegate().containsKey(key); + } + + @Override + public Enumeration getKeys() { + return getDelegate().getKeys(); + } + + @Override + public Locale getLocale() { + return getDelegate().getLocale(); + } + + @Override + public Set keySet() { + return getDelegate().keySet(); + } + + public String getString(String key, Object... params) { + return Strings.getString(getString(key), params); + } + + @Override + protected Object handleGetObject(String key) { + Object result; + + try { + Method method = getDelegate().getClass().getMethod("handleGetObject", String.class); + + method.setAccessible(true); + result = method.invoke(delegate, key); + method.setAccessible(false); + + } catch (Exception cause) { + throw new RuntimeException(cause); + } + + return result; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Strings.java b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Strings.java new file mode 100644 index 0000000..d0c01a3 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/core/util/Strings.java @@ -0,0 +1,300 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.core.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.demoiselle.jee.core.annotation.Ignore; + +/** + * Contain a set of methods that implements a set of functionalities that + * envolves manipulation of strings. + * + * @author SERPRO + */ +public final class Strings { + + private Strings() { + } + + /** + * Returns if some string matches with the format of a ResourceBundle key or + * not. + * + * @param key string to check if matches with key format of ResourceBundle. + * @return boolean true if matches and false otherwise. + */ + public static boolean isResourceBundleKeyFormat(final String key) { + return Pattern.matches("^\\{(.+)\\}$", key == null ? "" : key); + } + + /** + * Removes specific characteres from a given string. + * + * @param string string to be changed, by the removing of some characters. + * @param chars characters to be removed from string. + * @return String returns the given string without the given characters. + */ + public static String removeChars(String string, char... chars) { + String result = string; + + if (result != null) { + for (char ch : chars) { + result = result.replace(String.valueOf(ch), ""); + } + } + return result; + } + + public static String join(String separator, String... strings) { + StringBuffer result = new StringBuffer(); + + if (strings != null) { + for (int i = 0; i < strings.length; i++) { + if (i != 0 && separator != null) { + result.append(separator); + } + + if (strings[i] != null) { + result.append(strings[i]); + } + } + } + + return result.length() > 0 ? result.toString() : null; + } + + /** + * Inserts the character "0" in the begin of a given string. The quantity of + * zeros that will be placed depends on the difference between the length of + * the given string and the value of howMuchZeros. + * + * @param string string to insert zeros characthers. + * @param howMuchZeros its controls how much zeros will be insert. + * @return String Retuns the string, added with appropriate number of zeros. + * For exemplo, if string = "yes" and howMuchZeros = 5, the returned string + * will be "00yes". + */ + public static String insertZeros(String string, int howMuchZeros) { + StringBuffer result = new StringBuffer((string == null ? "" : string).trim()); + int difference = howMuchZeros - result.toString().length(); + + for (int j = 0; j < difference; j++) { + result.insert(0, '0'); + } + + return result.toString(); + } + + /** + * * Replaces the numbers between braces in the given string with the given + * parameters. The process will replace a number between braces for the + * parameter for which its order in the set of parameters matches with the + * number of the given string. For exemple, if is received the following + * string "Treats an {0} exception" and the set of parameters + * {"DemoiselleException"}, the return will be the following string: "Treats + * an DemoiselleException exception". + * + * @param string with the numbers with braces to be replaced with the + * parameters. + * @param params parameters that will replace the number with braces in the + * given string. + * @return String string with numbers replaced with the matching parameter. + */ + public static String getString(final String string, final Object... params) { + String result = null; + + if (string != null) { + result = new String(string); + } + + if (params != null && string != null) { + for (int i = 0; i < params.length; i++) { + if (params[i] != null) { + result = result.replaceAll("\\{" + i + "\\}", Matcher.quoteReplacement(params[i].toString())); + } + } + } + + return result; + } + + /** + * Verifies if a given string is empty or null. + * + * @param string string to be verified. + * @return boolean returns true if the given string is empty or null and + * returns false otherwise. + */ + public static boolean isEmpty(String string) { + return string == null || string.trim().isEmpty(); + } + + /** + * Converts any object to string. + * + * @param object object to be converted. + * @return String the given object converted to string. + */ + public static String toString(Object object) { + StringBuffer result = new StringBuffer(); + Object fieldValue; + + if (object != null) { + result.append(object.getClass().getSimpleName()); + result.append(" ["); + + boolean first = true; + for (Field field : Reflections.getNonStaticDeclaredFields(object.getClass())) { + if (!field.isAnnotationPresent(Ignore.class)) { + if (first) { + first = false; + } else { + result.append(", "); + } + + result.append(field.getName()); + result.append('='); + fieldValue = Reflections.getFieldValue(field, object); + result.append(fieldValue != null && fieldValue.getClass().isArray() + ? Arrays.toString((Object[]) fieldValue) + : fieldValue); + } + } + + result.append(']'); + } + + return result.toString(); + } + + /** + * Replace the camel case string for a lowercase string separated for a + * given symbol. + * + * @param string string that separeted with camel case. + * @param symbol simbol to be the new separator for the given string. + * @return String the given string separated with the given symbol. + */ + public static String camelCaseToSymbolSeparated(String string, String symbol) { + if (symbol == null) { + symbol = ""; + } + + return string == null ? null : string.replaceAll("\\B([A-Z])", symbol + "$1").toLowerCase(); + } + + /** + * Sets the first character of a given string to upper case. + * + * @param string Full string to convert + * @return String the given string with the first character setted to upper + * case. + */ + public static String firstToUpper(String string) { + String result = string; + + if (!Strings.isEmpty(string)) { + result = string.toUpperCase().charAt(0) + (string.length() > 1 ? string.substring(1) : ""); + } + + return result; + } + + /** + * Removes braces from a given string. + * + * @param string Message to remove braces from + * @return String the given string without braces. + */ + public static String removeBraces(String string) { + String result = string; + + if (isResourceBundleKeyFormat(string)) { + result = string.substring(1, string.length() - 1); + } + + return result; + } + + /** + * Inserts braces in a given string. + * + * @param string Original string to insert braces on. + * @return String the given string with braces. + */ + public static String insertBraces(String string) { + String result = string; + + if (!isEmpty(string)) { + result = "{" + string + "}"; + } + + return result; + } + + public static String parse(InputStream inputStream) throws IOException { + StringBuilder result = new StringBuilder(); + + if (inputStream != null) { + BufferedReader reader = null; + + try { + reader = new BufferedReader(new InputStreamReader(inputStream)); + String line; + + while ((line = reader.readLine()) != null) { + result.append(line); + } + + } finally { + if (reader != null) { + reader.close(); + } + } + } + + return result.length() > 0 ? result.toString() : null; + } +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java new file mode 100644 index 0000000..396eb44 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/BusinessController.java @@ -0,0 +1,36 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.stereotype; + +import javax.enterprise.inject.Stereotype; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Identifies a business controller class. Business controller objects typically implement the controller design + * pattern, i.e., they contain no data elements but methods that orchestrate interaction among business entities. + *

+ * A Business Controller is: + *

    + *
  • defined when annotated with {@code @BusinessController}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + * @see Controller + */ +@Controller +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface BusinessController { +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/Controller.java b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/Controller.java new file mode 100644 index 0000000..f26104b --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/Controller.java @@ -0,0 +1,28 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.stereotype; + +import javax.interceptor.InterceptorBinding; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Identifies a controller class or stereotype, the latter being most suitable for it. + * + * @author SERPRO + */ +@InterceptorBinding +@Inherited +@Target({ TYPE, METHOD }) +@Retention(RUNTIME) +public @interface Controller { +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java new file mode 100644 index 0000000..c0ba5ff --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/PersistenceController.java @@ -0,0 +1,37 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.stereotype; + +import javax.enterprise.inject.Stereotype; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Identifies a persistence controller class. A persistence controller is + * a layer which provides simplified access to data stored in persistent storage + * of some kind, such as an entity-relational database. + *

+ * A Persitence Controller is: + *

    + *
  • defined when annotated with {@code @PersistenceController}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + * @see Controller + */ +@Controller +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface PersistenceController { +} diff --git a/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/RestController.java b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/RestController.java new file mode 100644 index 0000000..bd9b9e0 --- /dev/null +++ b/demoiselle-core/src/main/java/org/demoiselle/jee/stereotype/RestController.java @@ -0,0 +1,36 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.stereotype; + +import javax.enterprise.inject.Stereotype; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Identifies a facade class. A facade is an object that provides a + * simplified interface to a larger body of code, such as a class library. + *

+ * A Facade is: + *

    + *
  • defined when annotated with {@code @FacadeController}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + * @see Controller + */ +@Controller +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface RestController { +} diff --git a/demoiselle-core/src/main/resources/demoiselle.properties b/demoiselle-core/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..71ae24e --- /dev/null +++ b/demoiselle-core/src/main/resources/demoiselle.properties @@ -0,0 +1,5 @@ +# Enables JPA transaction strategy, automatically detected if demoiselle-jpa component is detected. Use only if you need to overwrite the default behaviour +#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JPATransaction + +# Enables JTA transaction strategy, automatically detected if demoiselle-jta component is detected. Use only if you need to overwrite the default behaviour +#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JTATransaction diff --git a/demoiselle-core/src/main/resources/messages.properties b/demoiselle-core/src/main/resources/messages.properties new file mode 100644 index 0000000..62cae56 --- /dev/null +++ b/demoiselle-core/src/main/resources/messages.properties @@ -0,0 +1,81 @@ + +version=${project.version} +engine-on=Iniciando o Demoiselle Framework ${project.version} (Neo) +resource-not-found=Arquivo {0} n\u00e3o foi encontrado +key-not-found=A chave {0} n\u00e3o foi encontrada +ambiguous-strategy-resolution=Foi detectada ambiguidade da interface {0} com as seguintes implementa\u00e7\u00f5es\: {1}. Para resolver o conflito, defina explicitamente a implementa\u00e7\u00e3o no demoiselle.properties. +ambiguous-bean-resolution=Falha ao obter {0} pois foi detectada ambiguidade nas seguintes implementa\u00e7\u00f5es\: {1} +bean-not-found=Voc\u00ea est\u00e1 tentando obter um objeto n\u00e3o reconhecido pelo CDI via Beans.getReference({0}) +store-not-found=O objeto do tipo [{0}] n\u00e3o pode ser armazenado no escopo indicado\: {1} +more-than-one-exceptionhandler-defined-for-same-class=Foi definido mais de um m\u00e9todo na classe {0} para tratar a exce\u00e7\u00e3o {1} +handling-exception=Tratando a exce\u00e7\u00e3o {0} +taking-off=O Demoiselle ${project.version} decolou +engine-off=Desligando os motores do Demoiselle ${project.version} +setting-up-bean-manager=BeanManager dispon\u00edvel atrav\u00e9s do utilit\u00e1rio {0} + +user-transaction-lookup-fail=N\u00e3o foi encontrada nenhuma transa\u00e7\u00e3o com o nome {0} no contexto JNDI +transactional-execution=Execu\u00e7\u00e3o transacional de {0} +begin-transaction=Transa\u00e7\u00e3o iniciada +transaction-marked-rollback=Transa\u00e7\u00e3o marcada para rollback [{0}] +transaction-already-finalized=A transa\u00e7\u00e3o j\u00e1 havia sido finalizada +transaction-commited=Transa\u00e7\u00e3o finalizada com sucesso +transaction-rolledback=Transa\u00e7\u00e3o finalizada com rollback + +bootstrap.configuration.processing=Processando {0} +bootstrap-context-already-managed=O contexto {0} para o escopo {1} j\u00e1 foi adicionado +bootstrap-context-added=Adicionando o contexto {0} para o escopo {1} + +loading-configuration-class=Carregando a classe de configura\u00e7\u00e3o {0} +configuration-field-loaded={0}: {2} +configuration-attribute-is-mandatory=A configura\u00e7\u00e3o {0} \u00e9 obrigat\u00f3ria, mas n\u00e3o foi encontrada em {1} +configuration-name-attribute-cant-be-empty=A nota\u00e7\u00e3o @Name n\u00e3o pode estar em branco +configuration-generic-extraction-error=Ocorreu um erro durante a extra\u00e7\u00e3o do tipo {0} com o extrator {1} +configuration-dot-after-prefix=N\u00e3o \u00e9 necess\u00e1rio adicionar o ponto ap\u00f3s o prefixo para uma classe de configura\u00e7\u00e3o. \u00c9 recomendado que sejam retirados, pois poder\u00e3o causar erros em vers\u00f5es futuras do Framework. +configuration-key-not-found={0}\: [n\u00e3o encontrada] +configuration-extractor-not-found=N\u00e3o foi poss\u00edvel encontrar a classe extratora para o atributo {0}. Implemente a interface {1} para criar sua classe extratora. +configuration-not-conversion=N\u00e3o \u00e9 poss\u00edvel converter o valor {0} para o tipo {1} + +transaction-not-defined=Nenhuma transa\u00e7\u00e3o foi definida. Para utilizar @{0} \u00e9 preciso definir a propriedade frameworkdemoiselle.transaction.class com a estrat\u00e9gia de transa\u00e7\u00e3o desejada no arquivo demoiselle.properties +executing-all=Executando m\u00e9todos anotados com @{0} +custom-context-selected=Produzindo inst\u00e2ncia do contexto {0} +custom-context-was-activated=O contexto {0} foi ativado para o escopo {1} +custom-context-was-deactivated=O contexto {0} foi desativado para o escopo {1} +custom-context-already-activated=N\u00e3o foi poss\u00edvel ativar o contexto {0}, o escopo {1} j\u00e1 est\u00e1 ativo no contexto {2} +custom-context-not-found=N\u00e3o foi encontrado um contexto gerenciado do tipo [{0}] para o escopo [{1}] +custom-context-manager-not-initialized=ContextManager n\u00e3o foi inicializado. Chame [initialize] ao capturar o evento [AfterBeanDiscovery] em uma extens\u00e3o CDI + +error-creating-new-instance-for=Error creating a new instance for "{0}" +executed-successfully={0} execultado com sucesso +must-declare-one-single-parameter=Voc\u00ea deve declarar um par\u00e2metro \u00fanico em {0} +loading-default-transaction-manager=Carregando o gerenciador de transa\u00e7\u00e3o padr\u00e3o {0} +results-count-greater-page-size=Quantidade de resultados {0} \u00e9 maior que o tamanho da p\u00e1gina {1} +page-result=Resultado paginado [p\u00e1gina\={0}, total de resultados\={1}] +pagination-not-initialized=Pagina\u00e7\u00e3o n\u00e3o inicializada. Inicialize o sistema de pagina\u00e7\u00e3o definindo a p\u00e1gina atual ou o total de resultados ao menos uma vez na requisi\u00e7\u00e3o. +pagination-invalid-value=Valor inv\u00e1lido para paginador: [{0}]. +page=P\u00e1gina [n\u00famero\={0}, tamanho\={1}] +processing=Processando\: {0} +processing-fail=Falha no processamento devido a uma exce\u00e7\u00e3o lan\u00e7ada pela aplica\u00e7\u00e3o +for= \ para\: +file-not-found=O arquivo {0} n\u00e3o foi encontrado + +management-notification-attribute-changed=O atributo [{0}] da classe gerenciada [{1}] foi alterado +management-null-class-defined=O controlador de gerenciamento informado n\u00e3o pode ser [null] +management-abstract-class-defined=O controlador de gerenciamento [{0}] precisa ser uma classe concreta +management-no-annotation-found=Classe {0} precisa ser anotada com @ManagementController +management-invalid-property-no-getter-setter=Falha ao inicializar classe gerenciada {0}, n\u00e3o foi encontrado um m\u00e9todo get ou m\u00e9todo set para a propriedade {1} +management-invalid-property-as-operation=Falha ao inicializar classe gerenciada {0}, n\u00e3o \u00e9 poss\u00edvel declarar uma propriedade cujo m\u00e9todo get ou set \u00e9 uma opera\u00e7\u00e3o +management-introspection-error=Erro ao ler atributos da classe gerenciada {0} +management-type-not-found=A classe gerenciada informada n\u00e3o existe\: {0} +management-invoke-error=Erro ao tentar invocar a opera\u00e7\u00e3o "{0}" da classe gerenciada, a opera\u00e7\u00e3o n\u00e3o foi encontrada +management-write-value-error=N\u00e3o foi poss\u00edvel definir um valor para a propriedade {0} +management-read-value-error=N\u00e3o foi poss\u00edvel ler o valor da propriedade {0} +management-debug-acessing-property=Acessando propriedade {0} da classe gerenciada {1} +management-debug-setting-property=Definindo novo valor para propriedade {0} da classe gerenciada {1} +management-debug-invoking-operation=Invocando opera\u00e7\u00e3o {0} da classe gerenciada {1} +management-debug-starting-custom-context=Levantando contexto {0} para executar comando na classe gerenciada {1} +management-debug-stoping-custom-context=Desligando contexto {0} para classe gerenciada {1} +management-debug-registering-managed-type=Registrando classe gerenciada [{0}] +management-debug-processing-management-extension=Processando extens\u00e3o de gerenciamento [{0}] +management-debug-removing-management-extension=Desativando extens\u00e3o de gerenciamento [{0}] +management-validation-constraint-violation=Ocorreu um erro de valida\u00e7\u00e3o na classe [{0}] ao definir um valor para a propriedade [{1}]\: [{2}] +management-validation-validator-not-found=Nenhum provedor de valida\u00e7\u00e3o de beans encontrado, as anota\u00e7\u00f5es de valida\u00e7\u00e3o n\u00e3o ser\u00e3o processadas diff --git a/demoiselle-persistence-jpa/.gitignore b/demoiselle-persistence-jpa/.gitignore new file mode 100644 index 0000000..f65bf53 --- /dev/null +++ b/demoiselle-persistence-jpa/.gitignore @@ -0,0 +1,5 @@ +/.settings/ +/.project +/.classpath +/bin/ +/target/ diff --git a/demoiselle-persistence-jpa/pom.xml b/demoiselle-persistence-jpa/pom.xml new file mode 100644 index 0000000..777115d --- /dev/null +++ b/demoiselle-persistence-jpa/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-persistence-jpa + 3.0.0-SNAPSHOT + jar + + Demoiselle Persistence + + Demoiselle Persistence + + + + UTF-8 + 1.8 + 1.8 + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + javax.ejb + javax.ejb-api + 3.2 + provided + + + javax.cache + cache-api + 1.0.0 + jar + + + javax.cache + cache-api + 1.0.0 + jar + + + javax.persistence + persistence-api + 1.0.2 + jar + + + javax.transaction + javax.transaction-api + 1.2 + jar + + + diff --git a/demoiselle-persistence-jpa/pom.xml~ b/demoiselle-persistence-jpa/pom.xml~ new file mode 100644 index 0000000..0de0c6e --- /dev/null +++ b/demoiselle-persistence-jpa/pom.xml~ @@ -0,0 +1,56 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-persistence + 3.0.0-SNAPSHOT + jar + + Demoiselle Persistence + + Demoiselle Persistence + + + + UTF-8 + 1.8 + 1.8 + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + javax.ejb + javax.ejb-api + 3.2 + provided + + + javax.cache + cache-api + 1.0.0 + jar + + + javax.cache + cache-api + 1.0.0 + jar + + + javax.persistence + persistence-api + 1.0.2 + jar + + + javax.transaction + javax.transaction-api + 1.2 + jar + + + diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/context/package-info.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/context/package-info.java new file mode 100644 index 0000000..118e886 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/context/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas ao contexto da + * camada de persistência do framework Demoiselle. + */ +package org.demoiselle.jee.persistence.jpa.context; \ No newline at end of file diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericCrudDAO.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericCrudDAO.java new file mode 100644 index 0000000..7e6a4fd --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericCrudDAO.java @@ -0,0 +1,166 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.persistence.jpa.crud; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +public abstract class GenericCrudDAO { + + private Class entityClass; + + public GenericCrudDAO(Class entityClass) { + this.entityClass = entityClass; + } + + protected abstract EntityManager getEntityManager(); + + public void create(T entity) { + getEntityManager().persist(entity); + } + + public void edit(T entity) { + getEntityManager().merge(entity); + } + + public void remove(T entity) { + getEntityManager().remove(getEntityManager().merge(entity)); + } + + public T find(Object id) { + return getEntityManager().find(entityClass, id); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public List findAll() { + javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); + cq.select(cq.from(entityClass)); + return getEntityManager().createQuery(cq).getResultList(); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public List findRange(int[] range) { + javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); + cq.select(cq.from(entityClass)); + javax.persistence.Query q = getEntityManager().createQuery(cq); + q.setMaxResults(range[1] - range[0] + 1); + q.setFirstResult(range[0]); + return q.getResultList(); + } + + @SuppressWarnings("rawtypes") + public GenericDataPage pageResult(String sort, String order, Integer from, Integer size, String search, + String fields, HashMap filter) { + + // TODO: Rever esta validação + // if (GPUtils.isEmpty(sort, order) || !((order.equalsIgnoreCase("asc") + // || order.equalsIgnoreCase("desc")) + // && (GPUtils.fieldInClass(sort, this.entityClass)))) { + // throw new GPException(GPMessage.LIST_PARAM_ERROR); + // } + + if (from == null) { + from = 0; + } + if (size == null) { + size = Integer.MAX_VALUE; + } + boolean hasSearch = search != null && !search.isEmpty(); + + String query = new String("select u from " + this.entityClass.getSimpleName() + " u "); + if (hasSearch) { + query += " where lower(concat("; + String[] f = fields.split(","); + for (int i = 0; i < f.length; i++) { + query += "u." + f[i]; + if (i < f.length - 1) { + query += ", ' ',"; + } + } + query += ")) like concat('%', :part, '%')"; + } + + if (filter != null && !filter.isEmpty()) { + Iterator keys = filter.keySet().iterator(); + if (hasSearch) { + while (keys.hasNext()) { + String key = keys.next(); + query += " AND u." + key + "=" + filter.get(key); + } + } else { + query += " where "; + while (keys.hasNext()) { + String key = keys.next(); + query += " u." + key + "=" + filter.get(key); + if (keys.hasNext()) { + query += " and "; + } + } + } + } + // Total de Registros + String query_total = query.replaceFirst("select u", "select COUNT(u)"); + Query qr = getEntityManager().createQuery(query_total); + if (hasSearch) { + qr.setParameter("part", search.toLowerCase()); + } + Long total = (Long) qr.getSingleResult(); + + // Conteudo + qr = getEntityManager().createQuery(query.toString() + " ORDER BY " + sort + " " + order); + List content = null; + if (hasSearch) { + qr.setParameter("part", search.toLowerCase()); + } + content = qr.setFirstResult(from).setMaxResults(size).getResultList(); + return new GenericDataPage(content, from, size, total, fields, search); + } + + public GenericDataPage list(String field, String order) { + List list = getEntityManager() + .createQuery("select u from " + this.entityClass.getSimpleName() + " u ORDER BY " + field + " " + order, + this.entityClass) + .getResultList(); + return new GenericDataPage(list, 0, list.size(), list.size()); + } + + public GenericDataPage list() { + List list = getEntityManager() + .createQuery("select u from " + this.entityClass.getSimpleName() + " u ", this.entityClass) + .getResultList(); + return new GenericDataPage(list, 0, list.size(), list.size()); + } + + public List list(String field, String order, int init, int qtde) { + return getEntityManager() + .createQuery("select u from " + this.entityClass.getSimpleName() + " u ORDER BY " + field + " " + order, + this.entityClass) + .setFirstResult(init).setMaxResults(qtde).getResultList(); + } + + public List find(String whereField, String whereValue, String fieldOrder, String order, int init, int qtde) { + return getEntityManager() + .createQuery("select u from " + this.entityClass.getSimpleName() + " u where u." + whereField + " = " + + whereValue + " ORDER BY " + fieldOrder + " " + order, this.entityClass) + .setFirstResult(init).setMaxResults(qtde).getResultList(); + } + + public Long count() { + return (Long) getEntityManager().createQuery("select COUNT(u) from " + this.entityClass.getSimpleName() + " u") + .getSingleResult(); + } + + public Long count(String whereField, String whereValue) { + return (Long) getEntityManager().createQuery("select COUNT(u) from " + this.entityClass.getSimpleName() + + " u where u." + whereField + " = " + whereValue).getSingleResult(); + } + +} diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericDataPage.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericDataPage.java new file mode 100644 index 0000000..1704207 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/GenericDataPage.java @@ -0,0 +1,95 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.persistence.jpa.crud; + +import java.io.Serializable; +import java.util.List; + +@SuppressWarnings("rawtypes") +public class GenericDataPage implements Serializable { + + private static final long serialVersionUID = 1L; + + private long total; + + private int from; + + private int size; + + private String fields; + + private String search; + + private List content; + + public GenericDataPage(List content, int from, int size, long total) { + super(); + this.from = from; + this.size = size; + this.total = total; + this.content = content; + } + + public GenericDataPage(List content, int from, int size, long total, String fields, String search) { + super(); + this.from = from; + this.size = size; + this.total = total; + this.fields = fields; + this.search = search; + this.content = content; + } + + public long getTotal() { + return total; + } + + public void setTotal(long total) { + this.total = total; + } + + public int getFrom() { + return from; + } + + public void setFrom(int from) { + this.from = from; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public String getFields() { + return fields; + } + + public void setFields(String fields) { + this.fields = fields; + } + + public String getSearch() { + return search; + } + + public void setSearch(String search) { + this.search = search; + } + + public List getContent() { + return content; + } + + public void setContent(List content) { + this.content = content; + } + +} diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/package-info.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/package-info.java new file mode 100644 index 0000000..f06b6e5 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/crud/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas aos + * facilitadores de CRUD do framework Demoiselle. + */ +package org.demoiselle.jee.persistence.jpa.crud; \ No newline at end of file diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/DemoisellePersistenceException.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/DemoisellePersistenceException.java new file mode 100644 index 0000000..4a88363 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/DemoisellePersistenceException.java @@ -0,0 +1,27 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.persistence.jpa.exception; + +import org.demoiselle.jee.core.exception.DemoiselleException; + +public class DemoisellePersistenceException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + public DemoisellePersistenceException(String message) { + super(message); + } + + public DemoisellePersistenceException(Throwable cause) { + super(cause); + } + + public DemoisellePersistenceException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/package-info.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/package-info.java new file mode 100644 index 0000000..06db4b0 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/exception/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas as Exceptions da + * persistencia do framework Demoiselle. + */ +package org.demoiselle.jee.persistence.jpa.exception; \ No newline at end of file diff --git a/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/interceptor/package-info.java b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/interceptor/package-info.java new file mode 100644 index 0000000..cc9c348 --- /dev/null +++ b/demoiselle-persistence-jpa/src/main/java/org/demoiselle/jee/persistence/jpa/interceptor/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas aos + * interceptadores da persistencia do framework Demoiselle. + */ +package org.demoiselle.jee.persistence.jpa.interceptor; \ No newline at end of file diff --git a/demoiselle-security-basic/.gitignore b/demoiselle-security-basic/.gitignore new file mode 100644 index 0000000..ddd6d6d --- /dev/null +++ b/demoiselle-security-basic/.gitignore @@ -0,0 +1,3 @@ +/.settings/ +/.classpath +/.project diff --git a/demoiselle-security-basic/pom.xml b/demoiselle-security-basic/pom.xml new file mode 100644 index 0000000..2e148e1 --- /dev/null +++ b/demoiselle-security-basic/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-basic + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-ws-jaxrs + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + diff --git a/demoiselle-security-basic/pom.xml~ b/demoiselle-security-basic/pom.xml~ new file mode 100644 index 0000000..135bb87 --- /dev/null +++ b/demoiselle-security-basic/pom.xml~ @@ -0,0 +1,34 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-basic + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-ws + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + diff --git a/demoiselle-security-basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java b/demoiselle-security-basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java new file mode 100644 index 0000000..571110a --- /dev/null +++ b/demoiselle-security-basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java @@ -0,0 +1,51 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security.basic.impl; + +import java.security.Principal; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; +import javax.enterprise.context.Dependent; +import javax.inject.Inject; +import org.demoiselle.jee.security.Token; +import org.demoiselle.jee.security.interfaces.TokensManager; + +/** + * + * @author 70744416353 + */ +@Dependent +public class TokensManagerImpl implements TokensManager { + + private static ConcurrentHashMap repo = new ConcurrentHashMap<>(); + + @Inject + private Logger logger; + + @Override + public Principal getUser(Token token) { + return repo.get(token.getKey()); + } + + @Override + public Token getToken(Principal user) { + String value = null; + if (!repo.containsValue(user)) { + value = UUID.randomUUID().toString(); + repo.put(value, user); + } else { + for (Map.Entry entry : repo.entrySet()) { + if (entry.getValue().equals(user)) { + return entry.getKey(); + } + } + } + return value; + } + +} diff --git a/demoiselle-security-basic/src/main/resources/demoiselle.properties b/demoiselle-security-basic/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..4f777af --- /dev/null +++ b/demoiselle-security-basic/src/main/resources/demoiselle.properties @@ -0,0 +1 @@ +user-not-authenticated \ No newline at end of file diff --git a/demoiselle-security-basic/src/main/resources/messages.properties b/demoiselle-security-basic/src/main/resources/messages.properties new file mode 100644 index 0000000..65893da --- /dev/null +++ b/demoiselle-security-basic/src/main/resources/messages.properties @@ -0,0 +1 @@ +tipo-seguranca=basic \ No newline at end of file diff --git a/demoiselle-security-basic/target/classes/demoiselle.properties b/demoiselle-security-basic/target/classes/demoiselle.properties new file mode 100644 index 0000000..4f777af --- /dev/null +++ b/demoiselle-security-basic/target/classes/demoiselle.properties @@ -0,0 +1 @@ +user-not-authenticated \ No newline at end of file diff --git a/demoiselle-security-basic/target/classes/messages.properties b/demoiselle-security-basic/target/classes/messages.properties new file mode 100644 index 0000000..65893da --- /dev/null +++ b/demoiselle-security-basic/target/classes/messages.properties @@ -0,0 +1 @@ +tipo-seguranca=basic \ No newline at end of file diff --git a/demoiselle-security-jwt/.gitignore b/demoiselle-security-jwt/.gitignore new file mode 100644 index 0000000..ddd6d6d --- /dev/null +++ b/demoiselle-security-jwt/.gitignore @@ -0,0 +1,3 @@ +/.settings/ +/.classpath +/.project diff --git a/demoiselle-security-jwt/pom.xml b/demoiselle-security-jwt/pom.xml new file mode 100644 index 0000000..edfb5f2 --- /dev/null +++ b/demoiselle-security-jwt/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-jwt + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + org.bitbucket.b_c + jose4j + 0.4.1 + + + + com.google.code.gson + gson + 2.2.2 + compile + + + + diff --git a/demoiselle-security-jwt/pom.xml~ b/demoiselle-security-jwt/pom.xml~ new file mode 100644 index 0000000..edfb5f2 --- /dev/null +++ b/demoiselle-security-jwt/pom.xml~ @@ -0,0 +1,41 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-jwt + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + org.bitbucket.b_c + jose4j + 0.4.1 + + + + com.google.code.gson + gson + 2.2.2 + compile + + + + diff --git a/demoiselle-security-jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java b/demoiselle-security-jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java new file mode 100644 index 0000000..6e7f77c --- /dev/null +++ b/demoiselle-security-jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java @@ -0,0 +1,105 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security.jwt.impl; + +import com.google.gson.Gson; +import java.security.Key; +import java.security.Principal; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.enterprise.context.Dependent; +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import org.demoiselle.jee.security.interfaces.TokensManager; +import org.jose4j.jwk.RsaJsonWebKey; +import org.jose4j.jwk.RsaJwkGenerator; +import org.jose4j.jws.AlgorithmIdentifiers; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwt.JwtClaims; +import org.jose4j.jwt.consumer.InvalidJwtException; +import org.jose4j.jwt.consumer.JwtConsumer; +import org.jose4j.jwt.consumer.JwtConsumerBuilder; +import org.jose4j.lang.JoseException; + +/** + * + * @author 70744416353 + */ +@Dependent +public class TokensManagerImpl implements TokensManager { + + @Inject + private HttpServletRequest httpRequest; + + private RsaJsonWebKey rsaJsonWebKey; + + @Inject + private Logger logger; + + public TokensManagerImpl() throws JoseException { + RsaJsonWebKey chave = RsaJwkGenerator.generateJwk(2048); + logger.info("Se você quiser usar sua app em cluster, coloque o parametro jwt.key no app.properties e reinicie a aplicacao"); + logger.log(Level.INFO, "jwt.key={0}", chave); + logger.info("Se você não usar esse parametro, a cada reinicialização será gerada uma nova chave privada, isso inviabiliza o uso em cluster "); + rsaJsonWebKey = (RsaJsonWebKey) RsaJsonWebKey.Factory.newPublicJwk((Key) chave); + rsaJsonWebKey.setKeyId("demoiselle-security-jwt"); + } + + @Override + public Principal getUser(String jwt) { + Principal usuario = null; + if (jwt != null && !jwt.isEmpty()) { + JwtConsumer jwtConsumer = new JwtConsumerBuilder() + .setRequireExpirationTime() // the JWT must have an expiration time + .setAllowedClockSkewInSeconds(60) // allow some leeway in validating time based claims to account for clock skew + .setExpectedIssuer("demoiselle") // whom the JWT needs to have been issued by + .setExpectedAudience("demoiselle") // to whom the JWT is intended for + .setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key + .build(); // create the JwtConsumer instance + + try { + JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); + usuario = new Gson().fromJson((String) jwtClaims.getClaimValue("user"), Principal.class); + + String ip = httpRequest.getRemoteAddr(); + if (!ip.equalsIgnoreCase((String) jwtClaims.getClaimValue("ip"))) { + usuario = null; + } + } catch (InvalidJwtException e) { + //Logger.getLogger(TokenRepository.class.getName()).log(Level.SEVERE, null, e); + } + } + return usuario; + } + + @Override + public String getToken(Principal user) { + try { + JwtClaims claims = new JwtClaims(); + claims.setIssuer("demoiselle"); + claims.setAudience("demoiselle"); + claims.setExpirationTimeMinutesInTheFuture(720); + claims.setGeneratedJwtId(); + claims.setIssuedAtToNow(); + claims.setNotBeforeMinutesInThePast(1); + + claims.setClaim("ip", httpRequest.getRemoteAddr()); + claims.setClaim("user", new Gson().toJson(user)); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setPayload(claims.toJson()); + jws.setKey(rsaJsonWebKey.getPrivateKey()); + jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId()); + jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); + return jws.getCompactSerialization(); + } catch (JoseException ex) { + logger.severe(ex.getMessage()); + } + return null; + + } + +} diff --git a/demoiselle-security-jwt/src/main/resources/demoiselle.properties b/demoiselle-security-jwt/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..4f777af --- /dev/null +++ b/demoiselle-security-jwt/src/main/resources/demoiselle.properties @@ -0,0 +1 @@ +user-not-authenticated \ No newline at end of file diff --git a/demoiselle-security-jwt/src/main/resources/messages.properties b/demoiselle-security-jwt/src/main/resources/messages.properties new file mode 100644 index 0000000..65893da --- /dev/null +++ b/demoiselle-security-jwt/src/main/resources/messages.properties @@ -0,0 +1 @@ +tipo-seguranca=basic \ No newline at end of file diff --git a/demoiselle-security-jwt/target/classes/demoiselle.properties b/demoiselle-security-jwt/target/classes/demoiselle.properties new file mode 100644 index 0000000..4f777af --- /dev/null +++ b/demoiselle-security-jwt/target/classes/demoiselle.properties @@ -0,0 +1 @@ +user-not-authenticated \ No newline at end of file diff --git a/demoiselle-security-jwt/target/classes/messages.properties b/demoiselle-security-jwt/target/classes/messages.properties new file mode 100644 index 0000000..65893da --- /dev/null +++ b/demoiselle-security-jwt/target/classes/messages.properties @@ -0,0 +1 @@ +tipo-seguranca=basic \ No newline at end of file diff --git a/demoiselle-security/.classpath b/demoiselle-security/.classpath new file mode 100644 index 0000000..6d7587a --- /dev/null +++ b/demoiselle-security/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/demoiselle-security/.gitignore b/demoiselle-security/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/demoiselle-security/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/demoiselle-security/.project b/demoiselle-security/.project new file mode 100644 index 0000000..4bd8474 --- /dev/null +++ b/demoiselle-security/.project @@ -0,0 +1,23 @@ + + + demoiselle-security + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/demoiselle-security/.settings/org.eclipse.core.resources.prefs b/demoiselle-security/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..abdea9a --- /dev/null +++ b/demoiselle-security/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding/=UTF-8 diff --git a/demoiselle-security/.settings/org.eclipse.jdt.core.prefs b/demoiselle-security/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..714351a --- /dev/null +++ b/demoiselle-security/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/demoiselle-security/.settings/org.eclipse.m2e.core.prefs b/demoiselle-security/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/demoiselle-security/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/demoiselle-security/pom.xml b/demoiselle-security/pom.xml new file mode 100644 index 0000000..4d5e8aa --- /dev/null +++ b/demoiselle-security/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security + 3.0.0-SNAPSHOT + jar + + Demoiselle Security + + Demoiselle Security + + + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java new file mode 100644 index 0000000..9d3353e --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java @@ -0,0 +1,75 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security; + +import java.io.IOException; +import org.demoiselle.jee.security.interfaces.SecurityContext; +import java.util.logging.Logger; +import javax.annotation.PostConstruct; +import javax.inject.Inject; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; + +/** + * + * @author 70744416353 + */ +@Provider +@PreMatching +public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, ContainerResponseFilter { + + @Inject + private Logger LOG; + + @Inject + private SecurityContext securityContext; + + @PostConstruct + public void init() { + LOG.info("Demoiselle Module - Security"); + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { + responseContext.getHeaders().putSingle("Authorization", "enabled"); + responseContext.getHeaders().putSingle("x-content-type-options", "nosniff"); + responseContext.getHeaders().putSingle("x-frame-options", "SAMEORIGIN"); + responseContext.getHeaders().putSingle("x-xss-protection", "1; mode=block"); + } + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + try { + if (requestContext.getHeaders().containsKey("Authorization")) { + String token = requestContext.getHeaders().get("Authorization").toString().replace("[", "").replace("]", ""); + if (!token.isEmpty()) { + securityContext.setToken(token); + } + } + } catch (Exception e) { + } + + } + + @Override + public void filter(ClientRequestContext requestContext) throws IOException { + + } + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + + } + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/LoggedUser.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/LoggedUser.java new file mode 100644 index 0000000..d7ecb62 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/LoggedUser.java @@ -0,0 +1,67 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security; + +import java.io.Serializable; +import java.security.Principal; +import java.util.List; +import java.util.Map; +import javax.enterprise.context.RequestScoped; + +/** + * + * @author 70744416353 + */ +@RequestScoped +public class LoggedUser { + + private String id; + private String username; + private String email; + private Map premissions; + private List roles; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Map getPremissions() { + return premissions; + } + + public void setPremissions(Map premissions) { + this.premissions = premissions; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/Token.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/Token.java new file mode 100644 index 0000000..d67d746 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/Token.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security; + +import javax.enterprise.context.RequestScoped; + +/** + * + * @author 70744416353 + */ +@RequestScoped +public class Token { + + private String key; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java new file mode 100644 index 0000000..f8380f6 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java @@ -0,0 +1,62 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ + +package org.demoiselle.jee.security.annotations; + +import javax.interceptor.InterceptorBinding; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + *

+ * Indicates that a specific permission is required in order to invocate the annotated method or class. + *

+ * + * @author SERPRO + */ + +@Inherited +@InterceptorBinding +@Target({ METHOD, TYPE }) +@Retention(RUNTIME) +public @interface LoggedIn { +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java new file mode 100644 index 0000000..8642348 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java @@ -0,0 +1,65 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.annotations; + +import javax.enterprise.util.Nonbinding; +import javax.interceptor.InterceptorBinding; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Indicates that a specific permission is required in order to invocate the annotated method or class. + * + * @author SERPRO + */ +@Inherited +@InterceptorBinding +@Target({ METHOD, TYPE }) +@Retention(RUNTIME) +public @interface RequiredPermission { + + @Nonbinding + String resource() default ""; + + @Nonbinding + String operation() default ""; +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java new file mode 100644 index 0000000..7847dc0 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java @@ -0,0 +1,65 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.annotations; + +import javax.enterprise.util.Nonbinding; +import javax.interceptor.InterceptorBinding; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + *

+ * Indicates that the annotated method or class requires the user to have one or more roles associated in order to be + * invocated. + *

+ * + * @author SERPRO + */ +@Inherited +@InterceptorBinding +@Target({ METHOD, TYPE }) +@Retention(RUNTIME) +public @interface RequiredRole { + + @Nonbinding + String[] value(); +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java new file mode 100644 index 0000000..f02d355 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java @@ -0,0 +1,83 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.exception; + +/** + *

+ * Thrown when the mecanism responsible for the entire authentication lifecycle fails. + *

+ * + * @author SERPRO + */ +public class AuthenticationException extends SecurityException { + + private static final long serialVersionUID = 1L; + + /** + *

+ * Constructor with message. + *

+ * + * @param message exception message + */ + public AuthenticationException(String message) { + super(message); + } + + /** + *

+ * Constructor with the cause. + *

+ * + * @param cause exception cause + */ + public AuthenticationException(Throwable cause) { + super(cause); + } + + /** + *

+ * Constructor with message and cause. + *

+ * + * @param message exception message + * @param cause exception cause + */ + public AuthenticationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java new file mode 100644 index 0000000..03261c8 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java @@ -0,0 +1,72 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.exception; + +/** + *

+ * Thrown when a fail on trying to access some resource and/or execute an + * operation without the proper authorization. + *

+ * + * @author SERPRO + */ +public class AuthorizationException extends SecurityException { + + private static final long serialVersionUID = 1L; + + /** + *

+ * Constructor with message. + *

+ * + * @param message exception message + */ + public AuthorizationException(String message) { + super(message); + } + + /** + *

+ * Constructor with the cause. + *

+ * + * @param cause exception cause + */ + public AuthorizationException(Throwable cause) { + super(cause); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java new file mode 100644 index 0000000..f7ab235 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java @@ -0,0 +1,37 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.security.exception; + +import java.util.HashMap; + +import org.demoiselle.jee.core.exception.DemoiselleException; + +public class DemoiselleSecurityException extends DemoiselleException { + + private static final long serialVersionUID = 519965615171844237L; + + private HashMap messages = new HashMap(); + + private int statusCode; + + public DemoiselleSecurityException(String string) { + super(string); + } + + public int getStatusCode() { + return statusCode; + } + + public void addMessage(String field, String msg) { + this.statusCode = 422; + messages.put(field, msg); + } + + public HashMap getMessages() { + return messages; + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java new file mode 100644 index 0000000..5582096 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java @@ -0,0 +1,80 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.exception; + +import javax.enterprise.inject.spi.CDI; +import org.demoiselle.jee.core.annotation.literal.NameQualifier; +import org.demoiselle.jee.core.util.ResourceBundle; + +/** + *

+ * Thrown when the user's credentials are invalid. + *

+ * + * @author SERPRO + */ +public class InvalidCredentialsException extends AuthenticationException { + + private static final long serialVersionUID = 1L; + + public InvalidCredentialsException() { + super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); + } + + /** + *

+ * Constructs an InvalidCredentialsException with a message. + *

+ * + * @param message exception message. + */ + public InvalidCredentialsException(String message) { + super(message); + } + + /** + *

+ * Constructor with message and cause. + *

+ * + * @param message exception message. + * @param cause exception cause. + */ + public InvalidCredentialsException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java new file mode 100644 index 0000000..b2069bf --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java @@ -0,0 +1,60 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.exception; + +/** + *

+ * Thrown when trying to access some resource or execute an operation that requires authentication. + *

+ * + * @author SERPRO + */ +public class NotLoggedInException extends AuthenticationException { + + private static final long serialVersionUID = 1L; + + /** + *

+ * Constructs an NotLoggedInException with a message. + *

+ * + * @param message exception message + */ + public NotLoggedInException(String message) { + super(message); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java new file mode 100644 index 0000000..f995a9c --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java @@ -0,0 +1,79 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.exception; + +import org.demoiselle.jee.core.exception.DemoiselleException; + +/** + * SecurityException is the superclass of those exceptions that can + * be thrown due to any security related issue. + * + * @author SERPRO + */ +public class SecurityException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + /** + * Constructs an SecurityException with the specified detail + * message. + * + * @param message the detail message. + */ + SecurityException(String message) { + super(message); + } + + /** + * Constructor with the cause. + * + * @param cause exception cause + */ + SecurityException(Throwable cause) { + super(cause); + } + + /** + * Constructor with message and cause. + * + * @param message exception message + * @param cause exception cause + */ + SecurityException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java new file mode 100644 index 0000000..2bc3e65 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java @@ -0,0 +1,128 @@ +package org.demoiselle.jee.security.impl; + +import org.demoiselle.jee.security.Token; +import javax.enterprise.context.Dependent; +import java.security.Principal; +import java.util.Map; +import java.util.Set; +import javax.inject.Inject; +import org.demoiselle.jee.core.util.ResourceBundle; +import org.demoiselle.jee.security.LoggedUser; +import org.demoiselle.jee.security.interfaces.SecurityContext; +import org.demoiselle.jee.security.exception.NotLoggedInException; +import org.demoiselle.jee.security.interfaces.TokensManager; + +/** + *

+ * This is the default implementation of {@link SecurityContext} interface. + *

+ * + * @author SERPRO + */ +@Dependent +public class SecurityContextImpl implements SecurityContext { + + private static final long serialVersionUID = 1L; + + @Inject + private TokensManager tm; + + @Inject + private Token token; + + @Inject + private LoggedUser loggedUser; + + @Inject + private ResourceBundle bundle; + + /** + * @see org.demoiselle.security.SecurityContext#hasPermission(String, + * String) + */ + @Override + public boolean hasPermission(String resource, String operation) { + boolean result = true; + + return result; + } + + /** + * @see org.demoiselle.security.SecurityContext#hasRole(String) + */ + @Override + public boolean hasRole(String role) { + boolean result = true; + + return result; + } + + /** + * @see org.demoiselle.security.SecurityContext#isLoggedIn() + */ + @Override + public boolean isLoggedIn() { + return getUser() != null; + } + + /** + * @see org.demoiselle.security.SecurityContext#getUser() + */ + @Override + public Principal getUser() { +// if (token.getKey() != null && !token.getKey().isEmpty()) { +// return tm.getUser(token.getKey()); +// } + return null;//token.getPrincipal(); + } + + public void checkLoggedIn() throws NotLoggedInException { + if (!isLoggedIn()) { + throw new NotLoggedInException(bundle.getString("user-not-authenticated")); + } + } + + @Override + public void setRoles(Set roles) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setPermission(Map permissions) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public Set getResources(String operation) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public Set getOperations(String resources) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setUser(Principal principal) { +// token.setKey(tm.getToken(principal)); +// token.setPrincipal(principal); + } + + @Override + public String getToken() { +// if (token.getKey() != null && token.getKey().isEmpty()) { +// token.setKey(tm.getToken(token.getPrincipal())); +// } + return token.getKey(); + } + + @Override + public void setToken(String chave) { +// token.setPrincipal(tm.getUser(chave)); +// if (token.getPrincipal() == null) { +// throw new NotLoggedInException(bundle.getString("user-not-authenticated")); +// } + token.setKey(chave); + } + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java new file mode 100644 index 0000000..723f529 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java @@ -0,0 +1,70 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.interceptor; + +import javax.annotation.Priority; +import javax.inject.Inject; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; +import java.io.Serializable; +import org.demoiselle.jee.security.annotations.LoggedIn; +import org.demoiselle.jee.security.interfaces.SecurityContext; + +/** + *

+ * Intercepts calls with {@link LoggedIn} annotations. + *

+ * + * @author SERPRO + */ +@LoggedIn +@Interceptor +@Priority(Interceptor.Priority.APPLICATION) +public class LoggedInInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + private SecurityContext securityContext; + + @AroundInvoke + public Object manage(final InvocationContext ic) throws Exception { + securityContext.checkLoggedIn(); + return ic.proceed(); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java new file mode 100644 index 0000000..15e9009 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java @@ -0,0 +1,144 @@ +package org.demoiselle.jee.security.interceptor; + +import org.demoiselle.jee.security.exception.AuthorizationException; + +import javax.annotation.Priority; +import javax.enterprise.inject.spi.CDI; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; +import java.io.Serializable; +import java.util.logging.Logger; +import javax.inject.Inject; +import static javax.sql.rowset.spi.SyncFactory.getLogger; +import org.demoiselle.jee.core.annotation.Name; +import org.demoiselle.jee.core.util.ResourceBundle; +import org.demoiselle.jee.core.util.Strings; +import org.demoiselle.jee.security.annotations.RequiredPermission; +import org.demoiselle.jee.security.interfaces.SecurityContext; + +/** + *

+ * Intercepts calls with {@code @RequiredPermission} annotation. + *

+ * + * @author SERPRO + */ +@RequiredPermission +@Interceptor +@Priority(Interceptor.Priority.APPLICATION) +public class RequiredPermissionInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + private ResourceBundle bundle; + + @Inject + private Logger logger; + + /** + *

+ * Gets the values for both resource and operation properties of + * {@code @RequiredPermission}. Delegates to {@code SecurityContext} check + * permissions. If the user has the required permission it executes the + * mehtod, otherwise throws an exception. Returns what is returned from the + * intercepted method. If the method's return type is {@code void} returns + * {@code null}. + *

+ * + * @param ic the {@code InvocationContext} in which the method is being + * called. + * @return what is returned from the intercepted method. If the method's + * return type is {@code void} returns {@code null}. + * @throws Exception if there is an error during the permission check or + * during the method's processing. + */ + @AroundInvoke + public Object manage(final InvocationContext ic) throws Exception { + String resource = getResource(ic); + String operation = getOperation(ic); + String username = null; + + if (getSecurityContext().isLoggedIn()) { + username = getSecurityContext().getUser().getName(); + getLogger().finest(bundle.getString("access-checking", username, operation, resource)); + } + + if (!getSecurityContext().hasPermission(resource, operation)) { + getLogger().severe(bundle.getString("access-denied", username, operation, resource)); + throw new AuthorizationException(bundle.getString("access-denied-ui", resource, operation)); + } + + getLogger().fine(bundle.getString("access-allowed", username, operation, resource)); + return ic.proceed(); + } + + /** + *

+ * Returns the resource defined in {@code @RequiredPermission} annotation, + * the name defined in {@code @AmbiguousQualifier} annotation or the class + * name itself. + *

+ * + * @param ic the {@code InvocationContext} in which the method is being + * called. + * @return the resource defined in {@code @RequiredPermission} annotation, + * the name defined in {@code @AmbiguousQualifier} annotation or the class + * name itself. + */ + private String getResource(InvocationContext ic) { + RequiredPermission requiredPermission; + requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); + + if (requiredPermission == null) { + requiredPermission = ic.getTarget().getClass().getAnnotation(RequiredPermission.class); + } + + if (Strings.isEmpty(requiredPermission.resource())) { + if (ic.getTarget().getClass().getAnnotation(Name.class) == null) { + return ic.getTarget().getClass().getSimpleName(); + } else { + return ic.getTarget().getClass().getAnnotation(Name.class).value(); + } + } else { + return requiredPermission.resource(); + } + } + + /** + *

+ * Returns the operation defined in {@code @RequiredPermission} annotation, + * the name defined in {@code @AmbiguousQualifier} annotation or the + * method's name itself. + *

+ * + * @param ic the {@code InvocationContext} in which the method is being + * called. + * @return the operation defined in {@code @RequiredPermission} annotation, + * the name defined in {@code @AmbiguousQualifier} annotation or the + * method's name itself. + */ + private String getOperation(InvocationContext ic) { + RequiredPermission requiredPermission; + requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); + + if (requiredPermission == null) { + requiredPermission = ic.getTarget().getClass().getAnnotation(RequiredPermission.class); + } + + if (Strings.isEmpty(requiredPermission.operation())) { + if (ic.getMethod().getAnnotation(Name.class) == null) { + return ic.getMethod().getName(); + } else { + return ic.getMethod().getAnnotation(Name.class).value(); + } + } else { + return requiredPermission.operation(); + } + } + + private SecurityContext getSecurityContext() { + return CDI.current().select(SecurityContext.class).get(); + } +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java new file mode 100644 index 0000000..8706173 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java @@ -0,0 +1,111 @@ +package org.demoiselle.jee.security.interceptor; + +import org.demoiselle.jee.security.exception.AuthorizationException; + +import javax.annotation.Priority; +import javax.enterprise.inject.spi.CDI; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import java.util.logging.Logger; +import javax.inject.Inject; +import org.demoiselle.jee.core.util.ResourceBundle; +import org.demoiselle.jee.security.annotations.RequiredRole; +import org.demoiselle.jee.security.interfaces.SecurityContext; + +/** + *

+ * Intercepts calls with {@code @RequiredRole} annotations. + *

+ * + * @author SERPRO + */ +@RequiredRole(value = "") +@Interceptor +@Priority(Interceptor.Priority.APPLICATION) +public class RequiredRoleInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + private ResourceBundle bundle; + + @Inject + private Logger logger; + + /** + *

+ * Gets the value property of {@code @RequiredRole}. Delegates to + * {@code SecurityContext} check role. If the user has the required role it + * executes the mehtod, otherwise throws an exception. Returns what is + * returned from the intercepted method. If the method's return type is + * {@code void} returns {@code null}. + *

+ * + * @param ic the {@code InvocationContext} in which the method is being + * called. + * @return what is returned from the intercepted method. If the method's + * return type is {@code void} returns {@code null}. + * @throws Exception if there is an error during the role check or during + * the method's processing. + */ + @AroundInvoke + public Object manage(final InvocationContext ic) throws Exception { + List roles = getRoles(ic); + + if (getSecurityContext().isLoggedIn()) { + logger.info( + bundle.getString("has-role-verification", getSecurityContext().getUser().getName(), roles)); + } + + List userRoles = new ArrayList(); + + for (String role : roles) { + if (getSecurityContext().hasRole(role)) { + userRoles.add(role); + } + } + + if (userRoles.isEmpty()) { + logger.severe( + bundle.getString("does-not-have-role", getSecurityContext().getUser().getName(), roles)); + + throw new AuthorizationException(bundle.getString("does-not-have-role-ui", roles)); + } + + logger.fine(bundle.getString("user-has-role", getSecurityContext().getUser().getName(), userRoles)); + + return ic.proceed(); + } + + /** + *

+ * Returns the value defined in {@code @RequiredRole} annotation. + *

+ * + * @param ic the {@code InvocationContext} in which the method is being + * called. + * @return the value defined in {@code @RequiredRole} annotation. + */ + private List getRoles(InvocationContext ic) { + String[] roles = {}; + + if (ic.getMethod().getAnnotation(RequiredRole.class) == null) { + roles = ic.getTarget().getClass().getAnnotation(RequiredRole.class).value(); + } else { + roles = ic.getMethod().getAnnotation(RequiredRole.class).value(); + } + + return Arrays.asList(roles); + } + + private SecurityContext getSecurityContext() { + return CDI.current().select(SecurityContext.class).get(); + } + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java new file mode 100644 index 0000000..0f5bbe7 --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java @@ -0,0 +1,66 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.interfaces; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import javax.enterprise.context.RequestScoped; + +/** + *

+ * Structure used to handle both authentication and authorizations mechanisms. + *

+ * + * @author SERPRO + */ +@RequestScoped +public interface LoggedUser extends Serializable { + + public String getId(); + + public void setId(String id); + + public Map getPermissions(); + + public void setPermissions(Map premissions); + + public List getRoles(); + + public void setRoles(List roles); + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java new file mode 100644 index 0000000..f90ce8e --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java @@ -0,0 +1,116 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.interfaces; + +import java.io.Serializable; +import java.security.Principal; +import java.util.Map; +import java.util.Set; +import org.demoiselle.jee.security.exception.AuthorizationException; +import org.demoiselle.jee.security.exception.NotLoggedInException; + +/** + *

+ * Structure used to handle both authentication and authorizations mechanisms. + *

+ * + * @author SERPRO + */ +public interface SecurityContext extends Serializable { + + /** + * Checks if a specific user is logged in. + * + * @return {@code true} if the user is logged in + */ + boolean isLoggedIn(); + + /** + * @throws NotLoggedInException if there is no user logged in a specific + * session + */ + void checkLoggedIn(); + + /** + * Checks if the logged user has permission to execute an specific operation + * on a specific resource. + * + * @param resource resource to be checked + * @param operation operation to be checked + * @return {@code true} if the user has the permission + * @throws AuthorizationException When the permission checking fails, this + * exception is thrown. + * @throws NotLoggedInException if there is no user logged in a specific + * session. + */ + boolean hasPermission(String resource, String operation); + + /** + * Checks if the logged user has an specific role + * + * @param role role to be checked + * @return {@code true} if the user has the role + * @throws AuthorizationException When the permission checking fails, this + * exception is thrown. + * @throws NotLoggedInException if there is no user logged in a specific + * session. + */ + boolean hasRole(String role); + + /** + * Return the user logged in the session. + * + * @return the user logged in a specific authenticated session. If there is + * no active session {@code null} is returned. + */ + Principal getUser(); + + void setUser(Principal principal); + + String getToken(); + + void setToken(String token); + + void setRoles(Set roles); + + void setPermission(Map permissions); + + Set getResources(String operation); + + Set getOperations(String resources); + +} diff --git a/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java new file mode 100644 index 0000000..667eece --- /dev/null +++ b/demoiselle-security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java @@ -0,0 +1,57 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package org.demoiselle.jee.security.interfaces; + +import java.io.Serializable; +import java.security.Principal; +import org.demoiselle.jee.security.LoggedUser; +import org.demoiselle.jee.security.Token; + +/** + *

+ * Structure used to handle both authentication and authorizations mechanisms. + *

+ * + * @author SERPRO + */ +public interface TokensManager extends Serializable { + + public LoggedUser getUser(Token token); + + public String create(LoggedUser user); + +} diff --git a/demoiselle-security/src/main/resources/messages.properties b/demoiselle-security/src/main/resources/messages.properties new file mode 100644 index 0000000..fc646ec --- /dev/null +++ b/demoiselle-security/src/main/resources/messages.properties @@ -0,0 +1,12 @@ +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +access-checking=Verificando permiss\u00e3o do usu\u00e1rio {0} para executar a a\u00e7\u00e3o {1} no recurso {2} +access-allowed=O usu\u00e1rio {0} acessou o recurso {2} com a a\u00e7\u00e3o {1} +access-denied=O usu\u00e1rio {0} n\u00e3o possui permiss\u00e3o para executar a a\u00e7\u00e3o {1} no recurso {2} +access-denied-ui=Voc\u00ea n\u00e3o est\u00e1 autorizado a executar a a\u00e7\u00e3o {1} no recurso {0} +authorizer-not-defined=Nenhuma regra de resolu\u00e7\u00e3o de permiss\u00f5es foi definida. Para utilizar @{0} \u00e9 preciso definir a propriedade frameworkdemoiselle.security.authorizer.class como regra de resolu\u00e7\u00e3o de permiss\u00f5es desejada no arquivo demoiselle.properties. +user-not-authenticated=Usu\u00e1rio n\u00e3o autenticado +invalid-credentials=Usu\u00e1rio ou senha inv\u00e1lidos +has-role-verification=Verificando se o usu\u00e1rio {0} possui a(s) role(s)\: {1} +does-not-have-role=Usu\u00e1rio {0} n\u00e3o possui a(s) role(s)\: {1} +does-not-have-role-ui=Para acessar este recurso \u00e9 necess\u00e1rio ser {0} +user-has-role=Usu\u00e1rio {0} possui a(s) role(s)\: {1} \ No newline at end of file diff --git a/demoiselle-ws-jaxrs/.classpath b/demoiselle-ws-jaxrs/.classpath new file mode 100644 index 0000000..b10870e --- /dev/null +++ b/demoiselle-ws-jaxrs/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/demoiselle-ws-jaxrs/.gitignore b/demoiselle-ws-jaxrs/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/demoiselle-ws-jaxrs/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/demoiselle-ws-jaxrs/.project b/demoiselle-ws-jaxrs/.project new file mode 100644 index 0000000..248ffed --- /dev/null +++ b/demoiselle-ws-jaxrs/.project @@ -0,0 +1,36 @@ + + + demoiselle-ws-jaxrs + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + + diff --git a/demoiselle-ws-jaxrs/.settings/org.eclipse.core.resources.prefs b/demoiselle-ws-jaxrs/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..e9441bb --- /dev/null +++ b/demoiselle-ws-jaxrs/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding/=UTF-8 diff --git a/demoiselle-ws-jaxrs/.settings/org.eclipse.jdt.core.prefs b/demoiselle-ws-jaxrs/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..6e80039 --- /dev/null +++ b/demoiselle-ws-jaxrs/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/demoiselle-ws-jaxrs/.settings/org.eclipse.m2e.core.prefs b/demoiselle-ws-jaxrs/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/demoiselle-ws-jaxrs/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.component b/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..813585d --- /dev/null +++ b/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.component @@ -0,0 +1,5 @@ + + + + + diff --git a/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.project.facet.core.xml b/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..fb95c45 --- /dev/null +++ b/demoiselle-ws-jaxrs/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/demoiselle-ws-jaxrs/pom.xml b/demoiselle-ws-jaxrs/pom.xml new file mode 100644 index 0000000..b3d8c3d --- /dev/null +++ b/demoiselle-ws-jaxrs/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-ws-jaxrs + 3.0.0-SNAPSHOT + jar + + Demoiselle Web Service + + Demoiselle Web Service + + + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + + javax.json + javax.json-api + 1.0 + + + + diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/JaxRsFilter.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/JaxRsFilter.java new file mode 100644 index 0000000..604f220 --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/JaxRsFilter.java @@ -0,0 +1,58 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.ws.jaxrs; + +import java.util.logging.Logger; +import javax.annotation.PostConstruct; +import javax.inject.Inject; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; + +/** + * + * @author 70744416353 + */ +@Provider +@PreMatching +public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, ContainerResponseFilter { + + @Inject + private Logger LOG; + + @Override + public void filter(ClientRequestContext requestContext) { + } + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + } + + @Override + public void filter(ContainerRequestContext requestContext) { + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) { + response.getHeaders().putSingle("Demoiselle", "3.0.0"); + response.getHeaders().putSingle("Access-Control-Allow-Origin", "*"); + response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE"); + response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type"); + } + + @PostConstruct + public void init() { + LOG.info("Demoiselle Module - Rest"); + } + +} diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/crud/package-info.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/crud/package-info.java new file mode 100644 index 0000000..d7ae709 --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/crud/package-info.java @@ -0,0 +1,11 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +/** + * Esta pacote tem o objetivo de conter as classes relacionadas aos + * facilitadores de CRUD do framework Demoiselle. + */ +package org.demoiselle.jee.ws.jaxrs.crud; \ No newline at end of file diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/DemoiselleRESTException.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/DemoiselleRESTException.java new file mode 100644 index 0000000..81d962c --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/DemoiselleRESTException.java @@ -0,0 +1,41 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.ws.jaxrs.exception; + +import java.util.HashMap; + +import org.demoiselle.jee.core.exception.DemoiselleException; + +public class DemoiselleRESTException extends DemoiselleException { + + private static final long serialVersionUID = 519965615171844237L; + + private HashMap messages = new HashMap(); + + private int statusCode; + + public DemoiselleRESTException() { + + } + + public DemoiselleRESTException(String string) { + super(string); + } + + public int getStatusCode() { + return statusCode; + } + + public void addMessage(String field, String msg) { + this.statusCode = 422; + messages.put(field, msg); + } + + public HashMap getMessages() { + return messages; + } +} diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/mapper/GenericExceptionMapper.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/mapper/GenericExceptionMapper.java new file mode 100644 index 0000000..1c11fbc --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/exception/mapper/GenericExceptionMapper.java @@ -0,0 +1,62 @@ +package org.demoiselle.jee.ws.jaxrs.exception.mapper; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.HashMap; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.demoiselle.jee.ws.jaxrs.exception.DemoiselleRESTException; + +@Provider +public class GenericExceptionMapper implements ExceptionMapper { + + public Response toResponse(Exception ex) { + + StringWriter errorStackTrace = new StringWriter(); + ex.printStackTrace(new PrintWriter(errorStackTrace)); + + // Verifica se a exception é de validação de PAYLOAD do REST + if (ex.getCause() instanceof DemoiselleRESTException) { + DemoiselleRESTException exDemoiselleREST = (DemoiselleRESTException) ex.getCause(); + if (!exDemoiselleREST.getMessages().isEmpty()) { + return Response.status(exDemoiselleREST.getStatusCode()).entity(exDemoiselleREST.getMessages()) + .type(MediaType.APPLICATION_JSON).build(); + } + } + + HashMap entity = new HashMap(); + + // No caso de existir message ele mostra a MESSAGE da Exception + if (ex.getMessage() != null) { + entity.put("error", ex.getMessage()); + + // Pega toda as mensagens da stacktrace + int level = 1; + while (ex.getCause() != null) { + ex = (Exception) ex.getCause(); + if (!ex.getMessage().isEmpty()) { + entity.put("inner_cause_" + level, ex.getMessage()); + } + level += 1; + } + + // Por padrão retorna SERVER ERROR, mas tenta encontrar o status do RESPONSE se for WebApplicationException + // http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html + int responseCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); + if (ex instanceof WebApplicationException) { + responseCode = ((WebApplicationException)ex).getResponse().getStatus(); + } + + return Response.status(responseCode).entity(entity).type(MediaType.APPLICATION_JSON).build(); + } + + entity.put("error", "Erro interno desconhecido no servidor."); + return Response.status(500).entity(entity).type(MediaType.APPLICATION_JSON).build(); + } + +} diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayload.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayload.java new file mode 100644 index 0000000..2f4eba5 --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayload.java @@ -0,0 +1,25 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.ws.jaxrs.interceptor; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.interceptor.InterceptorBinding; + +@Inherited +@InterceptorBinding +@Target({ METHOD, TYPE }) +@Retention(RUNTIME) +public @interface ValidatePayload { + +} \ No newline at end of file diff --git a/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayloadInterceptor.java b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayloadInterceptor.java new file mode 100644 index 0000000..6505ff2 --- /dev/null +++ b/demoiselle-ws-jaxrs/src/main/java/org/demoiselle/jee/ws/jaxrs/interceptor/ValidatePayloadInterceptor.java @@ -0,0 +1,62 @@ +/* + * Demoiselle Framework + * + * License: GNU Lesser General Public License (LGPL), version 3 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.demoiselle.jee.ws.jaxrs.interceptor; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; +import javax.validation.ConstraintViolation; +import javax.validation.UnexpectedTypeException; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.demoiselle.jee.ws.jaxrs.exception.DemoiselleRESTException; + +@Interceptor +@ValidatePayload +public class ValidatePayloadInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + @AroundInvoke + public Object manage(final InvocationContext ic) throws Exception { + DemoiselleRESTException ex = new DemoiselleRESTException(); + Set> violations = new HashSet>(); + for (Object params : ic.getParameters()) { + if (params != null) { + ValidatorFactory dfv = Validation.buildDefaultValidatorFactory(); + Validator validator = dfv.getValidator(); + try { + violations.addAll(validator.validate(params)); + for (ConstraintViolation violation : violations) { + String field = (violation.getRootBeanClass().getSimpleName() + "_" + + violation.getPropertyPath()).toLowerCase(); + // GPMessage msg = + // GPMessage.INVALID_FIELD_P1.setSufix(violation.getConstraintDescriptor() + // .getAnnotation().annotationType().getSimpleName().toLowerCase()); + + ex.addMessage(field, violation.getMessage()); + } + } catch (UnexpectedTypeException cause) { + // GPMessage msg = GPMessage.GENERAL_ERROR_P1; + // msg.setParam(cause.getMessage()); + throw new DemoiselleRESTException("ERRO GENERICO -> ALTERAR"); + } + } + } + + if (!violations.isEmpty() && !ex.getMessages().isEmpty()) { + throw ex; + } + return ic.proceed(); + } +} \ No newline at end of file diff --git a/jwt/.gitignore b/jwt/.gitignore deleted file mode 100644 index ddd6d6d..0000000 --- a/jwt/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/.settings/ -/.classpath -/.project diff --git a/jwt/pom.xml b/jwt/pom.xml deleted file mode 100644 index d3179e6..0000000 --- a/jwt/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-security-jwt - 3.0.0-SNAPSHOT - jar - - UTF-8 - 1.8 - 1.8 - - - - - ${project.groupId} - demoiselle-core - ${project.version} - - - - ${project.groupId} - demoiselle-ws - ${project.version} - - - - ${project.groupId} - demoiselle-security - ${project.version} - - - - org.bitbucket.b_c - jose4j - 0.4.1 - - - - com.google.code.gson - gson - 2.2.2 - compile - - - - diff --git a/jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java b/jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java deleted file mode 100644 index 6e7f77c..0000000 --- a/jwt/src/main/java/org/demoiselle/jee/security/jwt/impl/TokensManagerImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.security.jwt.impl; - -import com.google.gson.Gson; -import java.security.Key; -import java.security.Principal; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.enterprise.context.Dependent; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import org.demoiselle.jee.security.interfaces.TokensManager; -import org.jose4j.jwk.RsaJsonWebKey; -import org.jose4j.jwk.RsaJwkGenerator; -import org.jose4j.jws.AlgorithmIdentifiers; -import org.jose4j.jws.JsonWebSignature; -import org.jose4j.jwt.JwtClaims; -import org.jose4j.jwt.consumer.InvalidJwtException; -import org.jose4j.jwt.consumer.JwtConsumer; -import org.jose4j.jwt.consumer.JwtConsumerBuilder; -import org.jose4j.lang.JoseException; - -/** - * - * @author 70744416353 - */ -@Dependent -public class TokensManagerImpl implements TokensManager { - - @Inject - private HttpServletRequest httpRequest; - - private RsaJsonWebKey rsaJsonWebKey; - - @Inject - private Logger logger; - - public TokensManagerImpl() throws JoseException { - RsaJsonWebKey chave = RsaJwkGenerator.generateJwk(2048); - logger.info("Se você quiser usar sua app em cluster, coloque o parametro jwt.key no app.properties e reinicie a aplicacao"); - logger.log(Level.INFO, "jwt.key={0}", chave); - logger.info("Se você não usar esse parametro, a cada reinicialização será gerada uma nova chave privada, isso inviabiliza o uso em cluster "); - rsaJsonWebKey = (RsaJsonWebKey) RsaJsonWebKey.Factory.newPublicJwk((Key) chave); - rsaJsonWebKey.setKeyId("demoiselle-security-jwt"); - } - - @Override - public Principal getUser(String jwt) { - Principal usuario = null; - if (jwt != null && !jwt.isEmpty()) { - JwtConsumer jwtConsumer = new JwtConsumerBuilder() - .setRequireExpirationTime() // the JWT must have an expiration time - .setAllowedClockSkewInSeconds(60) // allow some leeway in validating time based claims to account for clock skew - .setExpectedIssuer("demoiselle") // whom the JWT needs to have been issued by - .setExpectedAudience("demoiselle") // to whom the JWT is intended for - .setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key - .build(); // create the JwtConsumer instance - - try { - JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); - usuario = new Gson().fromJson((String) jwtClaims.getClaimValue("user"), Principal.class); - - String ip = httpRequest.getRemoteAddr(); - if (!ip.equalsIgnoreCase((String) jwtClaims.getClaimValue("ip"))) { - usuario = null; - } - } catch (InvalidJwtException e) { - //Logger.getLogger(TokenRepository.class.getName()).log(Level.SEVERE, null, e); - } - } - return usuario; - } - - @Override - public String getToken(Principal user) { - try { - JwtClaims claims = new JwtClaims(); - claims.setIssuer("demoiselle"); - claims.setAudience("demoiselle"); - claims.setExpirationTimeMinutesInTheFuture(720); - claims.setGeneratedJwtId(); - claims.setIssuedAtToNow(); - claims.setNotBeforeMinutesInThePast(1); - - claims.setClaim("ip", httpRequest.getRemoteAddr()); - claims.setClaim("user", new Gson().toJson(user)); - - JsonWebSignature jws = new JsonWebSignature(); - jws.setPayload(claims.toJson()); - jws.setKey(rsaJsonWebKey.getPrivateKey()); - jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId()); - jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); - return jws.getCompactSerialization(); - } catch (JoseException ex) { - logger.severe(ex.getMessage()); - } - return null; - - } - -} diff --git a/jwt/src/main/resources/demoiselle.properties b/jwt/src/main/resources/demoiselle.properties deleted file mode 100644 index 4f777af..0000000 --- a/jwt/src/main/resources/demoiselle.properties +++ /dev/null @@ -1 +0,0 @@ -user-not-authenticated \ No newline at end of file diff --git a/jwt/src/main/resources/messages.properties b/jwt/src/main/resources/messages.properties deleted file mode 100644 index 65893da..0000000 --- a/jwt/src/main/resources/messages.properties +++ /dev/null @@ -1 +0,0 @@ -tipo-seguranca=basic \ No newline at end of file diff --git a/persistence/.gitignore b/persistence/.gitignore deleted file mode 100644 index a4ee882..0000000 --- a/persistence/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/.settings/ -/.project -/.classpath -/bin/ diff --git a/persistence/pom.xml b/persistence/pom.xml deleted file mode 100644 index 0de0c6e..0000000 --- a/persistence/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-persistence - 3.0.0-SNAPSHOT - jar - - Demoiselle Persistence - - Demoiselle Persistence - - - - UTF-8 - 1.8 - 1.8 - - - - ${project.groupId} - demoiselle-core - ${project.version} - - - javax.ejb - javax.ejb-api - 3.2 - provided - - - javax.cache - cache-api - 1.0.0 - jar - - - javax.cache - cache-api - 1.0.0 - jar - - - javax.persistence - persistence-api - 1.0.2 - jar - - - javax.transaction - javax.transaction-api - 1.2 - jar - - - diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/context/package-info.java b/persistence/src/main/java/org/demoiselle/jee/persistence/context/package-info.java deleted file mode 100644 index 9b0eceb..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/context/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas ao contexto da - * camada de persistência do framework Demoiselle. - */ -package org.demoiselle.jee.persistence.context; \ No newline at end of file diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericCrudDAO.java b/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericCrudDAO.java deleted file mode 100644 index 4252323..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericCrudDAO.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.persistence.crud; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -public abstract class GenericCrudDAO { - - private Class entityClass; - - public GenericCrudDAO(Class entityClass) { - this.entityClass = entityClass; - } - - protected abstract EntityManager getEntityManager(); - - public void create(T entity) { - getEntityManager().persist(entity); - } - - public void edit(T entity) { - getEntityManager().merge(entity); - } - - public void remove(T entity) { - getEntityManager().remove(getEntityManager().merge(entity)); - } - - public T find(Object id) { - return getEntityManager().find(entityClass, id); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public List findAll() { - javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); - cq.select(cq.from(entityClass)); - return getEntityManager().createQuery(cq).getResultList(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public List findRange(int[] range) { - javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); - cq.select(cq.from(entityClass)); - javax.persistence.Query q = getEntityManager().createQuery(cq); - q.setMaxResults(range[1] - range[0] + 1); - q.setFirstResult(range[0]); - return q.getResultList(); - } - - @SuppressWarnings("rawtypes") - public GenericDataPage pageResult(String sort, String order, Integer from, Integer size, String search, - String fields, HashMap filter) { - - // TODO: Rever esta validação - // if (GPUtils.isEmpty(sort, order) || !((order.equalsIgnoreCase("asc") - // || order.equalsIgnoreCase("desc")) - // && (GPUtils.fieldInClass(sort, this.entityClass)))) { - // throw new GPException(GPMessage.LIST_PARAM_ERROR); - // } - - if (from == null) { - from = 0; - } - if (size == null) { - size = Integer.MAX_VALUE; - } - boolean hasSearch = search != null && !search.isEmpty(); - - String query = new String("select u from " + this.entityClass.getSimpleName() + " u "); - if (hasSearch) { - query += " where lower(concat("; - String[] f = fields.split(","); - for (int i = 0; i < f.length; i++) { - query += "u." + f[i]; - if (i < f.length - 1) { - query += ", ' ',"; - } - } - query += ")) like concat('%', :part, '%')"; - } - - if (filter != null && !filter.isEmpty()) { - Iterator keys = filter.keySet().iterator(); - if (hasSearch) { - while (keys.hasNext()) { - String key = keys.next(); - query += " AND u." + key + "=" + filter.get(key); - } - } else { - query += " where "; - while (keys.hasNext()) { - String key = keys.next(); - query += " u." + key + "=" + filter.get(key); - if (keys.hasNext()) { - query += " and "; - } - } - } - } - // Total de Registros - String query_total = query.replaceFirst("select u", "select COUNT(u)"); - Query qr = getEntityManager().createQuery(query_total); - if (hasSearch) { - qr.setParameter("part", search.toLowerCase()); - } - Long total = (Long) qr.getSingleResult(); - - // Conteudo - qr = getEntityManager().createQuery(query.toString() + " ORDER BY " + sort + " " + order); - List content = null; - if (hasSearch) { - qr.setParameter("part", search.toLowerCase()); - } - content = qr.setFirstResult(from).setMaxResults(size).getResultList(); - return new GenericDataPage(content, from, size, total, fields, search); - } - - public GenericDataPage list(String field, String order) { - List list = getEntityManager() - .createQuery("select u from " + this.entityClass.getSimpleName() + " u ORDER BY " + field + " " + order, - this.entityClass) - .getResultList(); - return new GenericDataPage(list, 0, list.size(), list.size()); - } - - public GenericDataPage list() { - List list = getEntityManager() - .createQuery("select u from " + this.entityClass.getSimpleName() + " u ", this.entityClass) - .getResultList(); - return new GenericDataPage(list, 0, list.size(), list.size()); - } - - public List list(String field, String order, int init, int qtde) { - return getEntityManager() - .createQuery("select u from " + this.entityClass.getSimpleName() + " u ORDER BY " + field + " " + order, - this.entityClass) - .setFirstResult(init).setMaxResults(qtde).getResultList(); - } - - public List find(String whereField, String whereValue, String fieldOrder, String order, int init, int qtde) { - return getEntityManager() - .createQuery("select u from " + this.entityClass.getSimpleName() + " u where u." + whereField + " = " - + whereValue + " ORDER BY " + fieldOrder + " " + order, this.entityClass) - .setFirstResult(init).setMaxResults(qtde).getResultList(); - } - - public Long count() { - return (Long) getEntityManager().createQuery("select COUNT(u) from " + this.entityClass.getSimpleName() + " u") - .getSingleResult(); - } - - public Long count(String whereField, String whereValue) { - return (Long) getEntityManager().createQuery("select COUNT(u) from " + this.entityClass.getSimpleName() - + " u where u." + whereField + " = " + whereValue).getSingleResult(); - } - -} diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericDataPage.java b/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericDataPage.java deleted file mode 100644 index 9307544..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/GenericDataPage.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.persistence.crud; - -import java.io.Serializable; -import java.util.List; - -@SuppressWarnings("rawtypes") -public class GenericDataPage implements Serializable { - - private static final long serialVersionUID = 1L; - - private long total; - - private int from; - - private int size; - - private String fields; - - private String search; - - private List content; - - public GenericDataPage(List content, int from, int size, long total) { - super(); - this.from = from; - this.size = size; - this.total = total; - this.content = content; - } - - public GenericDataPage(List content, int from, int size, long total, String fields, String search) { - super(); - this.from = from; - this.size = size; - this.total = total; - this.fields = fields; - this.search = search; - this.content = content; - } - - public long getTotal() { - return total; - } - - public void setTotal(long total) { - this.total = total; - } - - public int getFrom() { - return from; - } - - public void setFrom(int from) { - this.from = from; - } - - public int getSize() { - return size; - } - - public void setSize(int size) { - this.size = size; - } - - public String getFields() { - return fields; - } - - public void setFields(String fields) { - this.fields = fields; - } - - public String getSearch() { - return search; - } - - public void setSearch(String search) { - this.search = search; - } - - public List getContent() { - return content; - } - - public void setContent(List content) { - this.content = content; - } - -} diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/package-info.java b/persistence/src/main/java/org/demoiselle/jee/persistence/crud/package-info.java deleted file mode 100644 index c42a8e9..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/crud/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas aos - * facilitadores de CRUD do framework Demoiselle. - */ -package org.demoiselle.jee.persistence.crud; \ No newline at end of file diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/exception/DemoisellePersistenceException.java b/persistence/src/main/java/org/demoiselle/jee/persistence/exception/DemoisellePersistenceException.java deleted file mode 100644 index 5acc64c..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/exception/DemoisellePersistenceException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.persistence.exception; - -import org.demoiselle.jee.core.exception.DemoiselleException; - -public class DemoisellePersistenceException extends DemoiselleException { - - private static final long serialVersionUID = 1L; - - public DemoisellePersistenceException(String message) { - super(message); - } - - public DemoisellePersistenceException(Throwable cause) { - super(cause); - } - - public DemoisellePersistenceException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/exception/package-info.java b/persistence/src/main/java/org/demoiselle/jee/persistence/exception/package-info.java deleted file mode 100644 index 0a8f5b6..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/exception/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas as Exceptions da - * persistencia do framework Demoiselle. - */ -package org.demoiselle.jee.persistence.exception; \ No newline at end of file diff --git a/persistence/src/main/java/org/demoiselle/jee/persistence/interceptor/package-info.java b/persistence/src/main/java/org/demoiselle/jee/persistence/interceptor/package-info.java deleted file mode 100644 index 0ee25e8..0000000 --- a/persistence/src/main/java/org/demoiselle/jee/persistence/interceptor/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas aos - * interceptadores da persistencia do framework Demoiselle. - */ -package org.demoiselle.jee.persistence.interceptor; \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2e9c6aa..1e66a0a 100644 --- a/pom.xml +++ b/pom.xml @@ -24,14 +24,12 @@ - - core - persistence - ws - - security - basic - jwt + demoiselle-core + demoiselle-persistence-jpa + demoiselle-security + + + demoiselle-ws-jaxrs diff --git a/security/.gitignore b/security/.gitignore deleted file mode 100644 index 29109ab..0000000 --- a/security/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/.settings/ -/.classpath -/.project -/bin/ diff --git a/security/pom.xml b/security/pom.xml deleted file mode 100644 index 6590c2d..0000000 --- a/security/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-security - 3.0.0-SNAPSHOT - jar - - UTF-8 - 1.8 - 1.8 - - - - - ${project.groupId} - demoiselle-core - ${project.version} - - - - diff --git a/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java b/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java deleted file mode 100644 index 9d3353e..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.security; - -import java.io.IOException; -import org.demoiselle.jee.security.interfaces.SecurityContext; -import java.util.logging.Logger; -import javax.annotation.PostConstruct; -import javax.inject.Inject; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.container.PreMatching; -import javax.ws.rs.ext.Provider; - -/** - * - * @author 70744416353 - */ -@Provider -@PreMatching -public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, ContainerResponseFilter { - - @Inject - private Logger LOG; - - @Inject - private SecurityContext securityContext; - - @PostConstruct - public void init() { - LOG.info("Demoiselle Module - Security"); - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { - responseContext.getHeaders().putSingle("Authorization", "enabled"); - responseContext.getHeaders().putSingle("x-content-type-options", "nosniff"); - responseContext.getHeaders().putSingle("x-frame-options", "SAMEORIGIN"); - responseContext.getHeaders().putSingle("x-xss-protection", "1; mode=block"); - } - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - try { - if (requestContext.getHeaders().containsKey("Authorization")) { - String token = requestContext.getHeaders().get("Authorization").toString().replace("[", "").replace("]", ""); - if (!token.isEmpty()) { - securityContext.setToken(token); - } - } - } catch (Exception e) { - } - - } - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - - } - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - - } - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/LoggedUser.java b/security/src/main/java/org/demoiselle/jee/security/LoggedUser.java deleted file mode 100644 index d7ecb62..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/LoggedUser.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.security; - -import java.io.Serializable; -import java.security.Principal; -import java.util.List; -import java.util.Map; -import javax.enterprise.context.RequestScoped; - -/** - * - * @author 70744416353 - */ -@RequestScoped -public class LoggedUser { - - private String id; - private String username; - private String email; - private Map premissions; - private List roles; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public Map getPremissions() { - return premissions; - } - - public void setPremissions(Map premissions) { - this.premissions = premissions; - } - - public List getRoles() { - return roles; - } - - public void setRoles(List roles) { - this.roles = roles; - } - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/Token.java b/security/src/main/java/org/demoiselle/jee/security/Token.java deleted file mode 100644 index d67d746..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/Token.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.security; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author 70744416353 - */ -@RequestScoped -public class Token { - - private String key; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java b/security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java deleted file mode 100644 index f8380f6..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/annotations/LoggedIn.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ - -package org.demoiselle.jee.security.annotations; - -import javax.interceptor.InterceptorBinding; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - *

- * Indicates that a specific permission is required in order to invocate the annotated method or class. - *

- * - * @author SERPRO - */ - -@Inherited -@InterceptorBinding -@Target({ METHOD, TYPE }) -@Retention(RUNTIME) -public @interface LoggedIn { -} diff --git a/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java b/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java deleted file mode 100644 index 8642348..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredPermission.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.annotations; - -import javax.enterprise.util.Nonbinding; -import javax.interceptor.InterceptorBinding; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * Indicates that a specific permission is required in order to invocate the annotated method or class. - * - * @author SERPRO - */ -@Inherited -@InterceptorBinding -@Target({ METHOD, TYPE }) -@Retention(RUNTIME) -public @interface RequiredPermission { - - @Nonbinding - String resource() default ""; - - @Nonbinding - String operation() default ""; -} diff --git a/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java b/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java deleted file mode 100644 index 7847dc0..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/annotations/RequiredRole.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.annotations; - -import javax.enterprise.util.Nonbinding; -import javax.interceptor.InterceptorBinding; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - *

- * Indicates that the annotated method or class requires the user to have one or more roles associated in order to be - * invocated. - *

- * - * @author SERPRO - */ -@Inherited -@InterceptorBinding -@Target({ METHOD, TYPE }) -@Retention(RUNTIME) -public @interface RequiredRole { - - @Nonbinding - String[] value(); -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java b/security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java deleted file mode 100644 index f02d355..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/AuthenticationException.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.exception; - -/** - *

- * Thrown when the mecanism responsible for the entire authentication lifecycle fails. - *

- * - * @author SERPRO - */ -public class AuthenticationException extends SecurityException { - - private static final long serialVersionUID = 1L; - - /** - *

- * Constructor with message. - *

- * - * @param message exception message - */ - public AuthenticationException(String message) { - super(message); - } - - /** - *

- * Constructor with the cause. - *

- * - * @param cause exception cause - */ - public AuthenticationException(Throwable cause) { - super(cause); - } - - /** - *

- * Constructor with message and cause. - *

- * - * @param message exception message - * @param cause exception cause - */ - public AuthenticationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java b/security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java deleted file mode 100644 index 03261c8..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/AuthorizationException.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.exception; - -/** - *

- * Thrown when a fail on trying to access some resource and/or execute an - * operation without the proper authorization. - *

- * - * @author SERPRO - */ -public class AuthorizationException extends SecurityException { - - private static final long serialVersionUID = 1L; - - /** - *

- * Constructor with message. - *

- * - * @param message exception message - */ - public AuthorizationException(String message) { - super(message); - } - - /** - *

- * Constructor with the cause. - *

- * - * @param cause exception cause - */ - public AuthorizationException(Throwable cause) { - super(cause); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java b/security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java deleted file mode 100644 index f7ab235..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/DemoiselleSecurityException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.security.exception; - -import java.util.HashMap; - -import org.demoiselle.jee.core.exception.DemoiselleException; - -public class DemoiselleSecurityException extends DemoiselleException { - - private static final long serialVersionUID = 519965615171844237L; - - private HashMap messages = new HashMap(); - - private int statusCode; - - public DemoiselleSecurityException(String string) { - super(string); - } - - public int getStatusCode() { - return statusCode; - } - - public void addMessage(String field, String msg) { - this.statusCode = 422; - messages.put(field, msg); - } - - public HashMap getMessages() { - return messages; - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java b/security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java deleted file mode 100644 index 5582096..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/InvalidCredentialsException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.exception; - -import javax.enterprise.inject.spi.CDI; -import org.demoiselle.jee.core.annotation.literal.NameQualifier; -import org.demoiselle.jee.core.util.ResourceBundle; - -/** - *

- * Thrown when the user's credentials are invalid. - *

- * - * @author SERPRO - */ -public class InvalidCredentialsException extends AuthenticationException { - - private static final long serialVersionUID = 1L; - - public InvalidCredentialsException() { - super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); - } - - /** - *

- * Constructs an InvalidCredentialsException with a message. - *

- * - * @param message exception message. - */ - public InvalidCredentialsException(String message) { - super(message); - } - - /** - *

- * Constructor with message and cause. - *

- * - * @param message exception message. - * @param cause exception cause. - */ - public InvalidCredentialsException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java b/security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java deleted file mode 100644 index b2069bf..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/NotLoggedInException.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.exception; - -/** - *

- * Thrown when trying to access some resource or execute an operation that requires authentication. - *

- * - * @author SERPRO - */ -public class NotLoggedInException extends AuthenticationException { - - private static final long serialVersionUID = 1L; - - /** - *

- * Constructs an NotLoggedInException with a message. - *

- * - * @param message exception message - */ - public NotLoggedInException(String message) { - super(message); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java b/security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java deleted file mode 100644 index f995a9c..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/exception/SecurityException.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.exception; - -import org.demoiselle.jee.core.exception.DemoiselleException; - -/** - * SecurityException is the superclass of those exceptions that can - * be thrown due to any security related issue. - * - * @author SERPRO - */ -public class SecurityException extends DemoiselleException { - - private static final long serialVersionUID = 1L; - - /** - * Constructs an SecurityException with the specified detail - * message. - * - * @param message the detail message. - */ - SecurityException(String message) { - super(message); - } - - /** - * Constructor with the cause. - * - * @param cause exception cause - */ - SecurityException(Throwable cause) { - super(cause); - } - - /** - * Constructor with message and cause. - * - * @param message exception message - * @param cause exception cause - */ - SecurityException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java b/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java deleted file mode 100644 index 2bc3e65..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.demoiselle.jee.security.impl; - -import org.demoiselle.jee.security.Token; -import javax.enterprise.context.Dependent; -import java.security.Principal; -import java.util.Map; -import java.util.Set; -import javax.inject.Inject; -import org.demoiselle.jee.core.util.ResourceBundle; -import org.demoiselle.jee.security.LoggedUser; -import org.demoiselle.jee.security.interfaces.SecurityContext; -import org.demoiselle.jee.security.exception.NotLoggedInException; -import org.demoiselle.jee.security.interfaces.TokensManager; - -/** - *

- * This is the default implementation of {@link SecurityContext} interface. - *

- * - * @author SERPRO - */ -@Dependent -public class SecurityContextImpl implements SecurityContext { - - private static final long serialVersionUID = 1L; - - @Inject - private TokensManager tm; - - @Inject - private Token token; - - @Inject - private LoggedUser loggedUser; - - @Inject - private ResourceBundle bundle; - - /** - * @see org.demoiselle.security.SecurityContext#hasPermission(String, - * String) - */ - @Override - public boolean hasPermission(String resource, String operation) { - boolean result = true; - - return result; - } - - /** - * @see org.demoiselle.security.SecurityContext#hasRole(String) - */ - @Override - public boolean hasRole(String role) { - boolean result = true; - - return result; - } - - /** - * @see org.demoiselle.security.SecurityContext#isLoggedIn() - */ - @Override - public boolean isLoggedIn() { - return getUser() != null; - } - - /** - * @see org.demoiselle.security.SecurityContext#getUser() - */ - @Override - public Principal getUser() { -// if (token.getKey() != null && !token.getKey().isEmpty()) { -// return tm.getUser(token.getKey()); -// } - return null;//token.getPrincipal(); - } - - public void checkLoggedIn() throws NotLoggedInException { - if (!isLoggedIn()) { - throw new NotLoggedInException(bundle.getString("user-not-authenticated")); - } - } - - @Override - public void setRoles(Set roles) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void setPermission(Map permissions) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public Set getResources(String operation) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public Set getOperations(String resources) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void setUser(Principal principal) { -// token.setKey(tm.getToken(principal)); -// token.setPrincipal(principal); - } - - @Override - public String getToken() { -// if (token.getKey() != null && token.getKey().isEmpty()) { -// token.setKey(tm.getToken(token.getPrincipal())); -// } - return token.getKey(); - } - - @Override - public void setToken(String chave) { -// token.setPrincipal(tm.getUser(chave)); -// if (token.getPrincipal() == null) { -// throw new NotLoggedInException(bundle.getString("user-not-authenticated")); -// } - token.setKey(chave); - } - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java deleted file mode 100644 index 723f529..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.interceptor; - -import javax.annotation.Priority; -import javax.inject.Inject; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptor; -import javax.interceptor.InvocationContext; -import java.io.Serializable; -import org.demoiselle.jee.security.annotations.LoggedIn; -import org.demoiselle.jee.security.interfaces.SecurityContext; - -/** - *

- * Intercepts calls with {@link LoggedIn} annotations. - *

- * - * @author SERPRO - */ -@LoggedIn -@Interceptor -@Priority(Interceptor.Priority.APPLICATION) -public class LoggedInInterceptor implements Serializable { - - private static final long serialVersionUID = 1L; - - @Inject - private SecurityContext securityContext; - - @AroundInvoke - public Object manage(final InvocationContext ic) throws Exception { - securityContext.checkLoggedIn(); - return ic.proceed(); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java deleted file mode 100644 index 15e9009..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.demoiselle.jee.security.interceptor; - -import org.demoiselle.jee.security.exception.AuthorizationException; - -import javax.annotation.Priority; -import javax.enterprise.inject.spi.CDI; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptor; -import javax.interceptor.InvocationContext; -import java.io.Serializable; -import java.util.logging.Logger; -import javax.inject.Inject; -import static javax.sql.rowset.spi.SyncFactory.getLogger; -import org.demoiselle.jee.core.annotation.Name; -import org.demoiselle.jee.core.util.ResourceBundle; -import org.demoiselle.jee.core.util.Strings; -import org.demoiselle.jee.security.annotations.RequiredPermission; -import org.demoiselle.jee.security.interfaces.SecurityContext; - -/** - *

- * Intercepts calls with {@code @RequiredPermission} annotation. - *

- * - * @author SERPRO - */ -@RequiredPermission -@Interceptor -@Priority(Interceptor.Priority.APPLICATION) -public class RequiredPermissionInterceptor implements Serializable { - - private static final long serialVersionUID = 1L; - - @Inject - private ResourceBundle bundle; - - @Inject - private Logger logger; - - /** - *

- * Gets the values for both resource and operation properties of - * {@code @RequiredPermission}. Delegates to {@code SecurityContext} check - * permissions. If the user has the required permission it executes the - * mehtod, otherwise throws an exception. Returns what is returned from the - * intercepted method. If the method's return type is {@code void} returns - * {@code null}. - *

- * - * @param ic the {@code InvocationContext} in which the method is being - * called. - * @return what is returned from the intercepted method. If the method's - * return type is {@code void} returns {@code null}. - * @throws Exception if there is an error during the permission check or - * during the method's processing. - */ - @AroundInvoke - public Object manage(final InvocationContext ic) throws Exception { - String resource = getResource(ic); - String operation = getOperation(ic); - String username = null; - - if (getSecurityContext().isLoggedIn()) { - username = getSecurityContext().getUser().getName(); - getLogger().finest(bundle.getString("access-checking", username, operation, resource)); - } - - if (!getSecurityContext().hasPermission(resource, operation)) { - getLogger().severe(bundle.getString("access-denied", username, operation, resource)); - throw new AuthorizationException(bundle.getString("access-denied-ui", resource, operation)); - } - - getLogger().fine(bundle.getString("access-allowed", username, operation, resource)); - return ic.proceed(); - } - - /** - *

- * Returns the resource defined in {@code @RequiredPermission} annotation, - * the name defined in {@code @AmbiguousQualifier} annotation or the class - * name itself. - *

- * - * @param ic the {@code InvocationContext} in which the method is being - * called. - * @return the resource defined in {@code @RequiredPermission} annotation, - * the name defined in {@code @AmbiguousQualifier} annotation or the class - * name itself. - */ - private String getResource(InvocationContext ic) { - RequiredPermission requiredPermission; - requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); - - if (requiredPermission == null) { - requiredPermission = ic.getTarget().getClass().getAnnotation(RequiredPermission.class); - } - - if (Strings.isEmpty(requiredPermission.resource())) { - if (ic.getTarget().getClass().getAnnotation(Name.class) == null) { - return ic.getTarget().getClass().getSimpleName(); - } else { - return ic.getTarget().getClass().getAnnotation(Name.class).value(); - } - } else { - return requiredPermission.resource(); - } - } - - /** - *

- * Returns the operation defined in {@code @RequiredPermission} annotation, - * the name defined in {@code @AmbiguousQualifier} annotation or the - * method's name itself. - *

- * - * @param ic the {@code InvocationContext} in which the method is being - * called. - * @return the operation defined in {@code @RequiredPermission} annotation, - * the name defined in {@code @AmbiguousQualifier} annotation or the - * method's name itself. - */ - private String getOperation(InvocationContext ic) { - RequiredPermission requiredPermission; - requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); - - if (requiredPermission == null) { - requiredPermission = ic.getTarget().getClass().getAnnotation(RequiredPermission.class); - } - - if (Strings.isEmpty(requiredPermission.operation())) { - if (ic.getMethod().getAnnotation(Name.class) == null) { - return ic.getMethod().getName(); - } else { - return ic.getMethod().getAnnotation(Name.class).value(); - } - } else { - return requiredPermission.operation(); - } - } - - private SecurityContext getSecurityContext() { - return CDI.current().select(SecurityContext.class).get(); - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java deleted file mode 100644 index 8706173..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.demoiselle.jee.security.interceptor; - -import org.demoiselle.jee.security.exception.AuthorizationException; - -import javax.annotation.Priority; -import javax.enterprise.inject.spi.CDI; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptor; -import javax.interceptor.InvocationContext; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import java.util.logging.Logger; -import javax.inject.Inject; -import org.demoiselle.jee.core.util.ResourceBundle; -import org.demoiselle.jee.security.annotations.RequiredRole; -import org.demoiselle.jee.security.interfaces.SecurityContext; - -/** - *

- * Intercepts calls with {@code @RequiredRole} annotations. - *

- * - * @author SERPRO - */ -@RequiredRole(value = "") -@Interceptor -@Priority(Interceptor.Priority.APPLICATION) -public class RequiredRoleInterceptor implements Serializable { - - private static final long serialVersionUID = 1L; - - @Inject - private ResourceBundle bundle; - - @Inject - private Logger logger; - - /** - *

- * Gets the value property of {@code @RequiredRole}. Delegates to - * {@code SecurityContext} check role. If the user has the required role it - * executes the mehtod, otherwise throws an exception. Returns what is - * returned from the intercepted method. If the method's return type is - * {@code void} returns {@code null}. - *

- * - * @param ic the {@code InvocationContext} in which the method is being - * called. - * @return what is returned from the intercepted method. If the method's - * return type is {@code void} returns {@code null}. - * @throws Exception if there is an error during the role check or during - * the method's processing. - */ - @AroundInvoke - public Object manage(final InvocationContext ic) throws Exception { - List roles = getRoles(ic); - - if (getSecurityContext().isLoggedIn()) { - logger.info( - bundle.getString("has-role-verification", getSecurityContext().getUser().getName(), roles)); - } - - List userRoles = new ArrayList(); - - for (String role : roles) { - if (getSecurityContext().hasRole(role)) { - userRoles.add(role); - } - } - - if (userRoles.isEmpty()) { - logger.severe( - bundle.getString("does-not-have-role", getSecurityContext().getUser().getName(), roles)); - - throw new AuthorizationException(bundle.getString("does-not-have-role-ui", roles)); - } - - logger.fine(bundle.getString("user-has-role", getSecurityContext().getUser().getName(), userRoles)); - - return ic.proceed(); - } - - /** - *

- * Returns the value defined in {@code @RequiredRole} annotation. - *

- * - * @param ic the {@code InvocationContext} in which the method is being - * called. - * @return the value defined in {@code @RequiredRole} annotation. - */ - private List getRoles(InvocationContext ic) { - String[] roles = {}; - - if (ic.getMethod().getAnnotation(RequiredRole.class) == null) { - roles = ic.getTarget().getClass().getAnnotation(RequiredRole.class).value(); - } else { - roles = ic.getMethod().getAnnotation(RequiredRole.class).value(); - } - - return Arrays.asList(roles); - } - - private SecurityContext getSecurityContext() { - return CDI.current().select(SecurityContext.class).get(); - } - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java b/security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java deleted file mode 100644 index 0f5bbe7..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interfaces/LoggedUser.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.interfaces; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; -import javax.enterprise.context.RequestScoped; - -/** - *

- * Structure used to handle both authentication and authorizations mechanisms. - *

- * - * @author SERPRO - */ -@RequestScoped -public interface LoggedUser extends Serializable { - - public String getId(); - - public void setId(String id); - - public Map getPermissions(); - - public void setPermissions(Map premissions); - - public List getRoles(); - - public void setRoles(List roles); - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java b/security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java deleted file mode 100644 index f90ce8e..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interfaces/SecurityContext.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.interfaces; - -import java.io.Serializable; -import java.security.Principal; -import java.util.Map; -import java.util.Set; -import org.demoiselle.jee.security.exception.AuthorizationException; -import org.demoiselle.jee.security.exception.NotLoggedInException; - -/** - *

- * Structure used to handle both authentication and authorizations mechanisms. - *

- * - * @author SERPRO - */ -public interface SecurityContext extends Serializable { - - /** - * Checks if a specific user is logged in. - * - * @return {@code true} if the user is logged in - */ - boolean isLoggedIn(); - - /** - * @throws NotLoggedInException if there is no user logged in a specific - * session - */ - void checkLoggedIn(); - - /** - * Checks if the logged user has permission to execute an specific operation - * on a specific resource. - * - * @param resource resource to be checked - * @param operation operation to be checked - * @return {@code true} if the user has the permission - * @throws AuthorizationException When the permission checking fails, this - * exception is thrown. - * @throws NotLoggedInException if there is no user logged in a specific - * session. - */ - boolean hasPermission(String resource, String operation); - - /** - * Checks if the logged user has an specific role - * - * @param role role to be checked - * @return {@code true} if the user has the role - * @throws AuthorizationException When the permission checking fails, this - * exception is thrown. - * @throws NotLoggedInException if there is no user logged in a specific - * session. - */ - boolean hasRole(String role); - - /** - * Return the user logged in the session. - * - * @return the user logged in a specific authenticated session. If there is - * no active session {@code null} is returned. - */ - Principal getUser(); - - void setUser(Principal principal); - - String getToken(); - - void setToken(String token); - - void setRoles(Set roles); - - void setPermission(Map permissions); - - Set getResources(String operation); - - Set getOperations(String resources); - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java b/security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java deleted file mode 100644 index 667eece..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/interfaces/TokensManager.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package org.demoiselle.jee.security.interfaces; - -import java.io.Serializable; -import java.security.Principal; -import org.demoiselle.jee.security.LoggedUser; -import org.demoiselle.jee.security.Token; - -/** - *

- * Structure used to handle both authentication and authorizations mechanisms. - *

- * - * @author SERPRO - */ -public interface TokensManager extends Serializable { - - public LoggedUser getUser(Token token); - - public String create(LoggedUser user); - -} diff --git a/security/src/main/resources/messages.properties b/security/src/main/resources/messages.properties deleted file mode 100644 index fc646ec..0000000 --- a/security/src/main/resources/messages.properties +++ /dev/null @@ -1,12 +0,0 @@ -adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] -access-checking=Verificando permiss\u00e3o do usu\u00e1rio {0} para executar a a\u00e7\u00e3o {1} no recurso {2} -access-allowed=O usu\u00e1rio {0} acessou o recurso {2} com a a\u00e7\u00e3o {1} -access-denied=O usu\u00e1rio {0} n\u00e3o possui permiss\u00e3o para executar a a\u00e7\u00e3o {1} no recurso {2} -access-denied-ui=Voc\u00ea n\u00e3o est\u00e1 autorizado a executar a a\u00e7\u00e3o {1} no recurso {0} -authorizer-not-defined=Nenhuma regra de resolu\u00e7\u00e3o de permiss\u00f5es foi definida. Para utilizar @{0} \u00e9 preciso definir a propriedade frameworkdemoiselle.security.authorizer.class como regra de resolu\u00e7\u00e3o de permiss\u00f5es desejada no arquivo demoiselle.properties. -user-not-authenticated=Usu\u00e1rio n\u00e3o autenticado -invalid-credentials=Usu\u00e1rio ou senha inv\u00e1lidos -has-role-verification=Verificando se o usu\u00e1rio {0} possui a(s) role(s)\: {1} -does-not-have-role=Usu\u00e1rio {0} n\u00e3o possui a(s) role(s)\: {1} -does-not-have-role-ui=Para acessar este recurso \u00e9 necess\u00e1rio ser {0} -user-has-role=Usu\u00e1rio {0} possui a(s) role(s)\: {1} \ No newline at end of file diff --git a/swagger/.gitignore b/swagger/.gitignore deleted file mode 100644 index ddd6d6d..0000000 --- a/swagger/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/.settings/ -/.classpath -/.project diff --git a/swagger/pom.xml b/swagger/pom.xml deleted file mode 100644 index 4a774b0..0000000 --- a/swagger/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - org.demoiselle - swagger - 3.0.0-SNAPSHOT - jar - - UTF-8 - 1.8 - 1.8 - - - - ${project.groupId} - core - ${project.version} - - - - ${project.groupId} - rest - ${project.version} - - - - io.swagger - swagger-jaxrs - 1.5.10 - - - - io.swagger - swagger-annotations - 1.5.10 - - - - diff --git a/swagger/src/main/java/org/demoiselle/swagger/SwaggerProducer.java b/swagger/src/main/java/org/demoiselle/swagger/SwaggerProducer.java deleted file mode 100644 index 96a6780..0000000 --- a/swagger/src/main/java/org/demoiselle/swagger/SwaggerProducer.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.swagger; - -import java.io.Serializable; - -/** - * - * @author 70744416353 - */ - -public class SwaggerProducer implements Serializable { - -} diff --git a/ws/.gitignore b/ws/.gitignore deleted file mode 100644 index 29109ab..0000000 --- a/ws/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/.settings/ -/.classpath -/.project -/bin/ diff --git a/ws/pom.xml b/ws/pom.xml deleted file mode 100644 index 2e81d97..0000000 --- a/ws/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - org.demoiselle.jee - demoiselle-ws - 3.0.0-SNAPSHOT - jar - - Demoiselle Web Service - - Demoiselle Web Service - - - - UTF-8 - 1.8 - 1.8 - - - - - ${project.groupId} - demoiselle-core - ${project.version} - - - - javax.ws.rs - javax.ws.rs-api - 2.0.1 - - - - javax.json - javax.json-api - 1.0 - - - - diff --git a/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java b/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java deleted file mode 100644 index e1b350d..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.demoiselle.jee.ws; - -import java.util.logging.Logger; -import javax.annotation.PostConstruct; -import javax.inject.Inject; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.container.PreMatching; -import javax.ws.rs.ext.Provider; - -/** - * - * @author 70744416353 - */ -@Provider -@PreMatching -public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, ContainerResponseFilter { - - @Inject - private Logger LOG; - - @Override - public void filter(ClientRequestContext requestContext) { - } - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { - } - - @Override - public void filter(ContainerRequestContext requestContext) { - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) { - response.getHeaders().putSingle("Demoiselle", "3.0.0"); - response.getHeaders().putSingle("Access-Control-Allow-Origin", "*"); - response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE"); - response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type"); - } - - @PostConstruct - public void init() { - LOG.info("Demoiselle Module - Rest"); - } - -} diff --git a/ws/src/main/java/org/demoiselle/jee/ws/crud/package-info.java b/ws/src/main/java/org/demoiselle/jee/ws/crud/package-info.java deleted file mode 100644 index f3e318b..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/crud/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -/** - * Esta pacote tem o objetivo de conter as classes relacionadas aos - * facilitadores de CRUD do framework Demoiselle. - */ -package org.demoiselle.jee.ws.crud; \ No newline at end of file diff --git a/ws/src/main/java/org/demoiselle/jee/ws/exception/DemoiselleRESTException.java b/ws/src/main/java/org/demoiselle/jee/ws/exception/DemoiselleRESTException.java deleted file mode 100644 index 1cb1492..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/exception/DemoiselleRESTException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.ws.exception; - -import java.util.HashMap; - -import org.demoiselle.jee.core.exception.DemoiselleException; - -public class DemoiselleRESTException extends DemoiselleException { - - private static final long serialVersionUID = 519965615171844237L; - - private HashMap messages = new HashMap(); - - private int statusCode; - - public DemoiselleRESTException(String string) { - super(string); - } - - public int getStatusCode() { - return statusCode; - } - - public void addMessage(String field, String msg) { - this.statusCode = 422; - messages.put(field, msg); - } - - public HashMap getMessages() { - return messages; - } -} diff --git a/ws/src/main/java/org/demoiselle/jee/ws/exception/mapper/GenericExceptionMapper.java b/ws/src/main/java/org/demoiselle/jee/ws/exception/mapper/GenericExceptionMapper.java deleted file mode 100644 index 2e76044..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/exception/mapper/GenericExceptionMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.demoiselle.jee.ws.exception.mapper; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.HashMap; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import org.demoiselle.jee.ws.exception.DemoiselleRESTException; - -@Provider -public class GenericExceptionMapper implements ExceptionMapper { - - public Response toResponse(Exception ex) { - - StringWriter errorStackTrace = new StringWriter(); - ex.printStackTrace(new PrintWriter(errorStackTrace)); - - // Verifica se a exception é de validação de PAYLOAD do REST - if (ex.getCause() instanceof DemoiselleRESTException) { - DemoiselleRESTException exDemoiselleREST = (DemoiselleRESTException) ex.getCause(); - if (!exDemoiselleREST.getMessages().isEmpty()) { - return Response.status(exDemoiselleREST.getStatusCode()).entity(exDemoiselleREST.getMessages()) - .type(MediaType.APPLICATION_JSON).build(); - } - } - - HashMap entity = new HashMap(); - - // No caso de existir message ele mostra a MESSAGE da Exception - if (ex.getMessage() != null) { - entity.put("error", ex.getMessage()); - - // Pega toda as mensagens da stacktrace - int level = 1; - while (ex.getCause() != null) { - ex = (Exception) ex.getCause(); - if (!ex.getMessage().isEmpty()) { - entity.put("inner_cause_" + level, ex.getMessage()); - } - level += 1; - } - - // Por padrão retorna SERVER ERROR, mas tenta encontrar o status do RESPONSE se for WebApplicationException - // http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html - int responseCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); - if (ex instanceof WebApplicationException) { - responseCode = ((WebApplicationException)ex).getResponse().getStatus(); - } - - return Response.status(responseCode).entity(entity).type(MediaType.APPLICATION_JSON).build(); - } - - entity.put("error", "Erro interno desconhecido no servidor."); - return Response.status(500).entity(entity).type(MediaType.APPLICATION_JSON).build(); - } - -} diff --git a/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayload.java b/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayload.java deleted file mode 100644 index 39ce8c0..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayload.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.ws.interceptor; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.interceptor.InterceptorBinding; - -@Inherited -@InterceptorBinding -@Target({ METHOD, TYPE }) -@Retention(RUNTIME) -public @interface ValidatePayload { - -} \ No newline at end of file diff --git a/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayloadInterceptor.java b/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayloadInterceptor.java deleted file mode 100644 index c13769b..0000000 --- a/ws/src/main/java/org/demoiselle/jee/ws/interceptor/ValidatePayloadInterceptor.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Demoiselle Framework - * - * License: GNU Lesser General Public License (LGPL), version 3 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.demoiselle.jee.ws.interceptor; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptor; -import javax.interceptor.InvocationContext; -import javax.validation.ConstraintViolation; -import javax.validation.UnexpectedTypeException; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; - -import org.demoiselle.jee.ws.exception.DemoiselleRESTException; - -@Interceptor -@ValidatePayload -public class ValidatePayloadInterceptor implements Serializable { - - private static final long serialVersionUID = 1L; - - @AroundInvoke - public Object manage(final InvocationContext ic) throws Exception { - DemoiselleRESTException ex = new DemoiselleRESTException("Erro de validação de entidade."); - Set> violations = new HashSet>(); - for (Object params : ic.getParameters()) { - if (params != null) { - ValidatorFactory dfv = Validation.buildDefaultValidatorFactory(); - Validator validator = dfv.getValidator(); - try { - violations.addAll(validator.validate(params)); - for (ConstraintViolation violation : violations) { - String field = (violation.getRootBeanClass().getSimpleName() + "_" - + violation.getPropertyPath()).toLowerCase(); - // GPMessage msg = - // GPMessage.INVALID_FIELD_P1.setSufix(violation.getConstraintDescriptor() - // .getAnnotation().annotationType().getSimpleName().toLowerCase()); - - ex.addMessage(field, violation.getMessage()); - } - } catch (UnexpectedTypeException cause) { - // GPMessage msg = GPMessage.GENERAL_ERROR_P1; - // msg.setParam(cause.getMessage()); - throw new DemoiselleRESTException("ERRO GENERICO -> ALTERAR"); - } - } - } - - if (!violations.isEmpty() && !ex.getMessages().isEmpty()) { - throw ex; - } - return ic.proceed(); - } -} \ No newline at end of file -- libgit2 0.21.2