From c5a3fe54fe229fb188fa292c06a135d2bd54cf73 Mon Sep 17 00:00:00 2001 From: Cleverson Sacramento Date: Wed, 16 Nov 2011 10:10:19 -0300 Subject: [PATCH] Migração do repositório para o GitHub --- .gitignore | 5 +++++ archetype/.gitignore | 5 +++++ archetype/jsf-jpa/.gitignore | 5 +++++ archetype/jsf-jpa/pom.xml | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/META-INF/maven/archetype-metadata.xml | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/pom.xml | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/business/BookmarkBC.java | 33 +++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/constant/readme.txt | 0 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/domain/Bookmark.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/exception/readme.txt | 0 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/message/readme.txt | 0 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/persistence/BookmarkDAO.java | 21 +++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/util/readme.txt | 0 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkEditMB.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkListMB.java | 47 +++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml | 11 +++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/persistence.xml | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/ValidationMessages.properties | 28 ++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties | 35 +++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/log4j.properties | 10 ++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/messages.properties | 45 +++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/faces-config.xml | 5 +++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml | 33 +++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_edit.xhtml | 44 ++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_list.xhtml | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/images/logo.png | Bin 0 -> 7381 bytes archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.html | 5 +++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.xhtml | 11 +++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/menu.xhtml | 17 +++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/template/main.xhtml | 40 ++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/business/BookmarkBCTest.java | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/readme.txt | 1 + archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml | 4 ++++ archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/persistence.xml | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/minimal/.gitignore | 5 +++++ archetype/minimal/pom.xml | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/minimal/src/main/resources/META-INF/maven/archetype-metadata.xml | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ archetype/minimal/src/main/resources/archetype-resources/pom.xml | 36 ++++++++++++++++++++++++++++++++++++ archetype/minimal/src/main/resources/archetype-resources/src/main/java/HelloWorld.java | 15 +++++++++++++++ archetype/minimal/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml | 4 ++++ archetype/minimal/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties | 0 archetype/minimal/src/main/resources/archetype-resources/src/test/java/HelloWorldTest.java | 23 +++++++++++++++++++++++ archetype/minimal/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml | 4 ++++ archetype/minimal/src/main/resources/archetype-resources/src/test/resources/log4j.properties | 9 +++++++++ archetype/pom.xml | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/.gitignore | 5 +++++ core/pom.xml | 167 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/DemoiselleException.java | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/annotation/Ignore.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/annotation/Name.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/annotation/Shutdown.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/annotation/Startup.java | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/annotation/ViewScoped.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigType.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/configuration/Configuration.java | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigurationException.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/exception/ApplicationException.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/exception/ExceptionHandler.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrap.java | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ConfigurationBootstrap.java | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrap.java | 138 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrap.java | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java | 301 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfig.java | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfig.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextStore.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/context/Contexts.java | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/CoreBundle.java | 28 ++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticator.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizer.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransaction.java | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImpl.java | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImpl.java | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImpl.java | 184 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImpl.java | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/TransactionInfo.java | 37 +++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptor.java | 177 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptor.java | 176 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptor.java | 152 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptor.java | 152 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AbstractProcessor.java | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AnnotatedMethodProcessor.java | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/Processor.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/ShutdownProcessor.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/StartupProcessor.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducer.java | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducer.java | 16 ++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducer.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducer.java | 135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxy.java | 168 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxy.java | 371 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/message/DefaultMessage.java | 101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/message/Message.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/message/MessageContext.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/message/SeverityType.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/pagination/Pagination.java | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/pagination/PaginationContext.java | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLoginSuccessful.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLogoutSuccessful.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/Authenticator.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/AuthorizationException.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/Authorizer.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/NotLoggedInException.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredPermission.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredRole.java | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityContext.java | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityException.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/security/User.java | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/stereotype/BusinessController.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/stereotype/Controller.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/stereotype/FacadeController.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/stereotype/PersistenceController.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/stereotype/ViewController.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/template/Crud.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/template/DelegateCrud.java | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transaction.java | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/transaction/TransactionException.java | 12 ++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transactional.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/util/Beans.java | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/util/Exceptions.java | 36 ++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/util/Reflections.java | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/util/ResourceBundle.java | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/java/br/gov/frameworkdemoiselle/util/Strings.java | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/resources/META-INF/beans.xml | 47 +++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension | 5 +++++ core/src/main/resources/demoiselle-core-bundle.properties | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrapTest.java | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrapTest.java | 8 ++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/MyStartupAnnotatedClass.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrapTest.java | 217 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrapTest.java | 256 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassExtendsFromClassThanImplementsTransactionInterface.java | 44 ++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassImplementsTransactionInterface.java | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassThanImplementsInterfaceThanExtendsFromTransactionInterface.java | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoaderTest.java | 644 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/InterfaceExtendsFromTransactionInterface.java | 44 ++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfigTest.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfigTest.java | 22 ++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextStoreTest.java | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextsTest.java | 204 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContextTest.java | 231 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticatorTest.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizerTest.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransactionTest.java | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImplTest.java | 229 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImplTest.java | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImplTest.java | 321 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImplTest.java | 354 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptorTest.java | 290 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptorTest.java | 408 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptorTest.java | 308 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptorTest.java | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducerTest.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducerTest.java | 20 ++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducerTest.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducerTest.java | 159 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxyTest.java | 305 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxyTest.java | 560 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/message/DefaultMessageTest.java | 328 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/template/DelegateCrudTest.java | 193 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/util/BeansTest.java | 125 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/util/ExceptionsTest.java | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/util/ReflectionsTest.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/util/ResourceBundleTest.java | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/java/br/gov/frameworkdemoiselle/util/StringsTest.java | 195 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/configuration.properties | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/configuration.xml | 47 +++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/configuration2.properties | 36 ++++++++++++++++++++++++++++++++++++ core/src/test/resources/demoiselle-core-bundle.properties | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/demoiselle-core-bundle_pt_BR.properties | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/demoiselle.properties | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/demoiselle.xml | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/log4j.properties | 42 ++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/messages.properties | 47 +++++++++++++++++++++++++++++++++++++++++++++++ core/src/test/resources/testGetStringMessage.properties | 37 +++++++++++++++++++++++++++++++++++++ core/src/test/resources/testGetStringMessage_en.properties | 36 ++++++++++++++++++++++++++++++++++++ core/src/uml/configuration.ucls | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/controller.ucls | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/exception.ucls | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/injection-bootstrap.ucls | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/injection-producer.ucls | 151 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/lifecycle-shutdown.ucls | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/lifecycle-startup.ucls | 147 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/message.ucls | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/pagination.ucls | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/security-authentication.ucls | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/security-authorization.ucls | 157 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/template.ucls | 30 ++++++++++++++++++++++++++++++ core/src/uml/transaction.ucls | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/uml/util.ucls | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/.gitignore | 5 +++++ extension/jpa/.gitignore | 5 +++++ extension/jpa/pom.xml | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducer.java | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducer.java | 196 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxy.java | 513 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/QueryProxy.java | 179 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/TypedQueryProxy.java | 179 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/JPACrud.java | 253 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/java/br/gov/frameworkdemoiselle/transaction/JPATransaction.java | 146 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/resources/META-INF/beans.xml | 40 ++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/main/resources/demoiselle-jpa-bundle.properties | 44 ++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfigTest.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducerTest.java | 101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducerTest.java | 190 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FakeEntityManager.java | 275 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxyTest.java | 530 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/template/JPACrudTest.java | 408 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/java/br/gov/frameworkdemoiselle/transaction/JPATransactionTest.java | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/META-INF/persistence.xml | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/demoiselle-jpa-bundle.properties | 44 ++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/demoiselle.properties | 36 ++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/empty-persistence.xml | 40 ++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/log4j.properties | 42 ++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/persistence-two-units.xml | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/test/resources/persistence.xml | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/uml/injection-producer.ucls | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/uml/pagination.ucls | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/uml/template.ucls | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jpa/src/uml/transaction.ucls | 44 ++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/.gitignore | 5 +++++ extension/jsf/pom.xml | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/NextView.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/PreviousView.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/Redirect.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ExceptionHandlerConfig.java | 26 ++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/JsfSecurityConfig.java | 42 ++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AbstractExceptionHandler.java | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandler.java | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactory.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandler.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactory.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandler.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactory.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImpl.java | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListener.java | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImpl.java | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandler.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactory.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducer.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducer.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletResponseProducer.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducer.java | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducer.java | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxy.java | 147 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBean.java | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractListPageBean.java | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractPageBean.java | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/EditPageBean.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/ListPageBean.java | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/PageBean.java | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Faces.java | 158 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/FileRenderer.java | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Locales.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/PageNotFoundException.java | 20 ++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Parameter.java | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Redirector.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/resources/META-INF/beans.xml | 44 ++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/resources/META-INF/faces-config.xml | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension | 1 + extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties | 36 ++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/FacesBootstrapTest.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactoryTest.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerTest.java | 171 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactoryTest.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerTest.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactoryTest.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerTest.java | 135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImplTest.java | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListenerTest.java | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImplTest.java | 325 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactoryTest.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerTest.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducerTest.java | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducerTest.java | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducerTest.java | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducerTest.java | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxyTest.java | 126 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBeanTest.java | 323 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractListPageBeanTest.java | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractPageTest.java | 160 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/Contact.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/test/java/br/gov/frameworkdemoiselle/util/FacesTest.java | 216 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/exception.ucls | 141 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/injection-bootstrap.ucls | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/injection-producer.ucls | 141 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/message.ucls | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/security-exception-handler.ucls | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/security-observer.ucls | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/template.ucls | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jsf/src/uml/util.ucls | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jta/.gitignore | 5 +++++ extension/jta/pom.xml | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jta/src/main/java/br/gov/frameworkdemoiselle/transaction/JTATransaction.java | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jta/src/main/resources/META-INF/beans.xml | 40 ++++++++++++++++++++++++++++++++++++++++ extension/jta/src/main/resources/demoiselle-jta-bundle.properties | 34 ++++++++++++++++++++++++++++++++++ extension/jta/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java | 194 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/jta/src/uml/transaction.ucls | 47 +++++++++++++++++++++++++++++++++++++++++++++++ extension/pom.xml | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/se/.gitignore | 5 +++++ extension/se/pom.xml | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ extension/se/src/main/resources/META-INF/beans.xml | 41 +++++++++++++++++++++++++++++++++++++++++ extension/se/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension | 1 + extension/se/src/main/resources/demoiselle-swing-bundle.properties | 35 +++++++++++++++++++++++++++++++++++ extension/se/src/uml/injection-bootstrap.ucls | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/.gitignore | 5 +++++ parent/archetype/.gitignore | 5 +++++ parent/archetype/pom.xml | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/extension/.gitignore | 5 +++++ parent/extension/pom.xml | 119 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/jsf/.gitignore | 5 +++++ parent/jsf/pom.xml | 215 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/minimal/.gitignore | 5 +++++ parent/minimal/pom.xml | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/pom.xml | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/root/.gitignore | 5 +++++ parent/root/pom.xml | 687 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/se/.gitignore | 5 +++++ parent/se/pom.xml | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ parent/web/.gitignore | 5 +++++ parent/web/pom.xml | 151 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 142 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/assembly/bin.xml | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/assembly/src.xml | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/site/apt/core.apt | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/site/apt/documentation.apt | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/site/apt/index.apt | 43 +++++++++++++++++++++++++++++++++++++++++++ src/site/apt/jpa.apt | 42 ++++++++++++++++++++++++++++++++++++++++++ src/site/apt/jsf.apt | 42 ++++++++++++++++++++++++++++++++++++++++++ src/site/apt/jta.apt | 43 +++++++++++++++++++++++++++++++++++++++++++ src/site/apt/release-notes.apt | 188 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/site/apt/se.apt | 41 +++++++++++++++++++++++++++++++++++++++++ src/site/site.xml | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 343 files changed, 32356 insertions(+), 0 deletions(-) create mode 100644 .gitignore create mode 100644 archetype/.gitignore create mode 100644 archetype/jsf-jpa/.gitignore create mode 100755 archetype/jsf-jpa/pom.xml create mode 100755 archetype/jsf-jpa/src/main/resources/META-INF/maven/archetype-metadata.xml create mode 100755 archetype/jsf-jpa/src/main/resources/archetype-resources/pom.xml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/business/BookmarkBC.java create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/constant/readme.txt create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/domain/Bookmark.java create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/exception/readme.txt create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/message/readme.txt create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/persistence/BookmarkDAO.java create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/util/readme.txt create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkEditMB.java create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkListMB.java create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/persistence.xml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/ValidationMessages.properties create mode 100755 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/log4j.properties create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/messages.properties create mode 100755 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/faces-config.xml create mode 100755 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_edit.xhtml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_list.xhtml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/images/logo.png create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.html create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.xhtml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/menu.xhtml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/template/main.xhtml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/business/BookmarkBCTest.java create mode 100755 archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/readme.txt create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml create mode 100644 archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/persistence.xml create mode 100644 archetype/minimal/.gitignore create mode 100755 archetype/minimal/pom.xml create mode 100755 archetype/minimal/src/main/resources/META-INF/maven/archetype-metadata.xml create mode 100755 archetype/minimal/src/main/resources/archetype-resources/pom.xml create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/main/java/HelloWorld.java create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/test/java/HelloWorldTest.java create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml create mode 100644 archetype/minimal/src/main/resources/archetype-resources/src/test/resources/log4j.properties create mode 100644 archetype/pom.xml create mode 100644 core/.gitignore create mode 100644 core/pom.xml create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/DemoiselleException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/annotation/Ignore.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/annotation/Name.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/annotation/Shutdown.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/annotation/Startup.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/annotation/ViewScoped.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigType.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/configuration/Configuration.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigurationException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/exception/ApplicationException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/exception/ExceptionHandler.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrap.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ConfigurationBootstrap.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrap.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrap.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfig.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfig.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextStore.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/context/Contexts.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/CoreBundle.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticator.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransaction.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImpl.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImpl.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImpl.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImpl.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/TransactionInfo.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AbstractProcessor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AnnotatedMethodProcessor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/Processor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/ShutdownProcessor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/StartupProcessor.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxy.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxy.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/message/DefaultMessage.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/message/Message.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/message/MessageContext.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/message/SeverityType.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/pagination/Pagination.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/pagination/PaginationContext.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLoginSuccessful.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLogoutSuccessful.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/Authenticator.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/AuthorizationException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/Authorizer.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/NotLoggedInException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredPermission.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredRole.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityContext.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/security/User.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/stereotype/BusinessController.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/stereotype/Controller.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/stereotype/FacadeController.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/stereotype/PersistenceController.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/stereotype/ViewController.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/template/Crud.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/template/DelegateCrud.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transaction.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/transaction/TransactionException.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transactional.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/util/Beans.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/util/Exceptions.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/util/Reflections.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/util/ResourceBundle.java create mode 100644 core/src/main/java/br/gov/frameworkdemoiselle/util/Strings.java create mode 100644 core/src/main/resources/META-INF/beans.xml create mode 100644 core/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension create mode 100644 core/src/main/resources/demoiselle-core-bundle.properties create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrapTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrapTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/MyStartupAnnotatedClass.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrapTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrapTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassExtendsFromClassThanImplementsTransactionInterface.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassImplementsTransactionInterface.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassThanImplementsInterfaceThanExtendsFromTransactionInterface.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoaderTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/InterfaceExtendsFromTransactionInterface.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfigTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfigTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextStoreTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextsTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContextTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticatorTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizerTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransactionTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImplTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImplTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImplTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImplTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptorTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptorTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptorTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptorTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducerTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducerTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducerTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducerTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxyTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxyTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/message/DefaultMessageTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/template/DelegateCrudTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/util/BeansTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/util/ExceptionsTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/util/ReflectionsTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/util/ResourceBundleTest.java create mode 100644 core/src/test/java/br/gov/frameworkdemoiselle/util/StringsTest.java create mode 100644 core/src/test/resources/configuration.properties create mode 100644 core/src/test/resources/configuration.xml create mode 100644 core/src/test/resources/configuration2.properties create mode 100644 core/src/test/resources/demoiselle-core-bundle.properties create mode 100644 core/src/test/resources/demoiselle-core-bundle_pt_BR.properties create mode 100644 core/src/test/resources/demoiselle.properties create mode 100644 core/src/test/resources/demoiselle.xml create mode 100755 core/src/test/resources/log4j.properties create mode 100644 core/src/test/resources/messages.properties create mode 100644 core/src/test/resources/testGetStringMessage.properties create mode 100644 core/src/test/resources/testGetStringMessage_en.properties create mode 100644 core/src/uml/configuration.ucls create mode 100644 core/src/uml/controller.ucls create mode 100644 core/src/uml/exception.ucls create mode 100644 core/src/uml/injection-bootstrap.ucls create mode 100644 core/src/uml/injection-producer.ucls create mode 100644 core/src/uml/lifecycle-shutdown.ucls create mode 100644 core/src/uml/lifecycle-startup.ucls create mode 100644 core/src/uml/message.ucls create mode 100644 core/src/uml/pagination.ucls create mode 100644 core/src/uml/security-authentication.ucls create mode 100644 core/src/uml/security-authorization.ucls create mode 100644 core/src/uml/template.ucls create mode 100644 core/src/uml/transaction.ucls create mode 100644 core/src/uml/util.ucls create mode 100644 extension/.gitignore create mode 100644 extension/jpa/.gitignore create mode 100644 extension/jpa/pom.xml create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducer.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducer.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxy.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/QueryProxy.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/TypedQueryProxy.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/JPACrud.java create mode 100644 extension/jpa/src/main/java/br/gov/frameworkdemoiselle/transaction/JPATransaction.java create mode 100644 extension/jpa/src/main/resources/META-INF/beans.xml create mode 100644 extension/jpa/src/main/resources/demoiselle-jpa-bundle.properties create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfigTest.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducerTest.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducerTest.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FakeEntityManager.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxyTest.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/template/JPACrudTest.java create mode 100644 extension/jpa/src/test/java/br/gov/frameworkdemoiselle/transaction/JPATransactionTest.java create mode 100644 extension/jpa/src/test/resources/META-INF/persistence.xml create mode 100644 extension/jpa/src/test/resources/demoiselle-jpa-bundle.properties create mode 100644 extension/jpa/src/test/resources/demoiselle.properties create mode 100644 extension/jpa/src/test/resources/empty-persistence.xml create mode 100755 extension/jpa/src/test/resources/log4j.properties create mode 100644 extension/jpa/src/test/resources/persistence-two-units.xml create mode 100644 extension/jpa/src/test/resources/persistence.xml create mode 100644 extension/jpa/src/uml/injection-producer.ucls create mode 100644 extension/jpa/src/uml/pagination.ucls create mode 100644 extension/jpa/src/uml/template.ucls create mode 100644 extension/jpa/src/uml/transaction.ucls create mode 100644 extension/jsf/.gitignore create mode 100644 extension/jsf/pom.xml create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/NextView.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/PreviousView.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/Redirect.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ExceptionHandlerConfig.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/JsfSecurityConfig.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AbstractExceptionHandler.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandler.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactory.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandler.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactory.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandler.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactory.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImpl.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListener.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImpl.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandler.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactory.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletResponseProducer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxy.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractListPageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractPageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/EditPageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/ListPageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/PageBean.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Faces.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/FileRenderer.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Locales.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/PageNotFoundException.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Parameter.java create mode 100644 extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Redirector.java create mode 100644 extension/jsf/src/main/resources/META-INF/beans.xml create mode 100644 extension/jsf/src/main/resources/META-INF/faces-config.xml create mode 100644 extension/jsf/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension create mode 100644 extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/FacesBootstrapTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactoryTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactoryTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactoryTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImplTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListenerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImplTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactoryTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducerTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxyTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBeanTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractListPageBeanTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractPageTest.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/Contact.java create mode 100644 extension/jsf/src/test/java/br/gov/frameworkdemoiselle/util/FacesTest.java create mode 100644 extension/jsf/src/uml/exception.ucls create mode 100644 extension/jsf/src/uml/injection-bootstrap.ucls create mode 100644 extension/jsf/src/uml/injection-producer.ucls create mode 100644 extension/jsf/src/uml/message.ucls create mode 100644 extension/jsf/src/uml/security-exception-handler.ucls create mode 100644 extension/jsf/src/uml/security-observer.ucls create mode 100644 extension/jsf/src/uml/template.ucls create mode 100644 extension/jsf/src/uml/util.ucls create mode 100644 extension/jta/.gitignore create mode 100644 extension/jta/pom.xml create mode 100644 extension/jta/src/main/java/br/gov/frameworkdemoiselle/transaction/JTATransaction.java create mode 100644 extension/jta/src/main/resources/META-INF/beans.xml create mode 100644 extension/jta/src/main/resources/demoiselle-jta-bundle.properties create mode 100644 extension/jta/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java create mode 100644 extension/jta/src/uml/transaction.ucls create mode 100644 extension/pom.xml create mode 100644 extension/se/.gitignore create mode 100644 extension/se/pom.xml create mode 100644 extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java create mode 100644 extension/se/src/main/resources/META-INF/beans.xml create mode 100644 extension/se/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension create mode 100644 extension/se/src/main/resources/demoiselle-swing-bundle.properties create mode 100644 extension/se/src/uml/injection-bootstrap.ucls create mode 100644 parent/.gitignore create mode 100644 parent/archetype/.gitignore create mode 100644 parent/archetype/pom.xml create mode 100644 parent/extension/.gitignore create mode 100644 parent/extension/pom.xml create mode 100644 parent/jsf/.gitignore create mode 100644 parent/jsf/pom.xml create mode 100644 parent/minimal/.gitignore create mode 100644 parent/minimal/pom.xml create mode 100644 parent/pom.xml create mode 100644 parent/root/.gitignore create mode 100644 parent/root/pom.xml create mode 100644 parent/se/.gitignore create mode 100644 parent/se/pom.xml create mode 100644 parent/web/.gitignore create mode 100644 parent/web/pom.xml create mode 100644 pom.xml create mode 100644 src/assembly/bin.xml create mode 100644 src/assembly/src.xml create mode 100644 src/site/apt/core.apt create mode 100644 src/site/apt/documentation.apt create mode 100644 src/site/apt/index.apt create mode 100644 src/site/apt/jpa.apt create mode 100644 src/site/apt/jsf.apt create mode 100644 src/site/apt/jta.apt create mode 100755 src/site/apt/release-notes.apt create mode 100644 src/site/apt/se.apt create mode 100755 src/site/site.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/archetype/.gitignore b/archetype/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/archetype/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/archetype/jsf-jpa/.gitignore b/archetype/jsf-jpa/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/archetype/jsf-jpa/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/archetype/jsf-jpa/pom.xml b/archetype/jsf-jpa/pom.xml new file mode 100755 index 0000000..02a9277 --- /dev/null +++ b/archetype/jsf-jpa/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + br.gov.frameworkdemoiselle.archetypes + demoiselle-jsf-jpa + jar + + + br.gov.frameworkdemoiselle + demoiselle-archetype-parent + 2.2.1-SNAPSHOT + ../../parent/archetype/pom.xml + + + JSF and JPA Archetype + Archetype for web applications (JSF/JPA) + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/archetype/jsf-jpa/src/main/resources/META-INF/maven/archetype-metadata.xml b/archetype/jsf-jpa/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100755 index 0000000..4132c8d --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,79 @@ + + + + + + + + readme.txt + + + + src/main/webapp + + **/*.png + **/*.gif + **/*.jpg + + + + src/main/webapp + + **/*.png + **/*.gif + **/*.jpg + + + + src/main/java + + + src/main/resources + + + src/test/java + + + src/test/resources + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/pom.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/pom.xml new file mode 100755 index 0000000..546a68a --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + war + + + + + + + br.gov.frameworkdemoiselle + demoiselle-jsf-parent + #{parent.version} + + + + + br.gov.frameworkdemoiselle + demoiselle-jpa + compile + + + br.gov.frameworkdemoiselle + demoiselle-jta + compile + + + org.primefaces + primefaces + compile + + + org.powermock + powermock-api-easymock + test + + + + + + demoiselle.sourceforge.net-release + http://demoiselle.sourceforge.net/repository/release + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/business/BookmarkBC.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/business/BookmarkBC.java new file mode 100644 index 0000000..1629905 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/business/BookmarkBC.java @@ -0,0 +1,33 @@ +package ${package}.business; + +import br.gov.frameworkdemoiselle.annotation.Startup; +import br.gov.frameworkdemoiselle.stereotype.BusinessController; +import br.gov.frameworkdemoiselle.template.DelegateCrud; +import br.gov.frameworkdemoiselle.transaction.Transactional; + +import ${package}.domain.Bookmark; +import ${package}.persistence.BookmarkDAO; + +@BusinessController +public class BookmarkBC extends DelegateCrud { + + private static final long serialVersionUID = 1L; + + @Startup + @Transactional + public void load() { + if (findAll().isEmpty()) { + insert(new Bookmark("Demoiselle Portal", "http://www.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Demoiselle SourceForge", "http://sf.net/projects/demoiselle")); + insert(new Bookmark("Twitter", "http://twitter.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Blog", "http://blog.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Wiki", "http://wiki.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Bug Tracking", "http://tracker.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Forum", "http://forum.frameworkdemoiselle.gov.br")); + insert(new Bookmark("SVN", "http://svn.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Maven", "http://repository.frameworkdemoiselle.gov.br")); + insert(new Bookmark("Downloads", "http://download.frameworkdemoiselle.gov.br")); + } + } + +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/constant/readme.txt b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/constant/readme.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/constant/readme.txt diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/domain/Bookmark.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/domain/Bookmark.java new file mode 100644 index 0000000..469e2c0 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/domain/Bookmark.java @@ -0,0 +1,58 @@ +package ${package}.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Bookmark implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + private Long id; + + @Column + private String description; + + @Column + private String link; + + public Bookmark() { + super(); + } + + public Bookmark(String description, String link) { + this.description = description; + this.link = link; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getLink() { + return link; + } + + public void setLink(String link) { + this.link = link; + } + +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/exception/readme.txt b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/exception/readme.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/exception/readme.txt diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/message/readme.txt b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/message/readme.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/message/readme.txt diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/persistence/BookmarkDAO.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/persistence/BookmarkDAO.java new file mode 100644 index 0000000..8a7b522 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/persistence/BookmarkDAO.java @@ -0,0 +1,21 @@ +package ${package}.persistence; + +import javax.inject.Inject; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.stereotype.PersistenceController; +import br.gov.frameworkdemoiselle.template.JPACrud; + +import ${package}.domain.Bookmark; + +@PersistenceController +public class BookmarkDAO extends JPACrud { + + private static final long serialVersionUID = 1L; + + @Inject + @SuppressWarnings("unused") + private Logger logger; + +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/util/readme.txt b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/util/readme.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/util/readme.txt diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkEditMB.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkEditMB.java new file mode 100644 index 0000000..449814e --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkEditMB.java @@ -0,0 +1,48 @@ +package ${package}.view; + +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.annotation.PreviousView; +import br.gov.frameworkdemoiselle.stereotype.ViewController; +import br.gov.frameworkdemoiselle.template.AbstractEditPageBean; +import br.gov.frameworkdemoiselle.transaction.Transactional; + +import ${package}.business.BookmarkBC; +import ${package}.domain.Bookmark; + +@ViewController +@PreviousView("/bookmark_list.xhtml") +public class BookmarkEditMB extends AbstractEditPageBean { + + private static final long serialVersionUID = 1L; + + @Inject + private BookmarkBC bookmarkBC; + + @Override + @Transactional + public String delete() { + this.bookmarkBC.delete(getId()); + return getPreviousView(); + } + + @Override + @Transactional + public String insert() { + this.bookmarkBC.insert(getBean()); + return getPreviousView(); + } + + @Override + @Transactional + public String update() { + this.bookmarkBC.update(getBean()); + return getPreviousView(); + } + + @Override + protected void handleLoad() { + setBean(this.bookmarkBC.load(getId())); + } + +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkListMB.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkListMB.java new file mode 100644 index 0000000..40fb6f1 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/java/view/BookmarkListMB.java @@ -0,0 +1,47 @@ +package ${package}.view; + +import java.util.Iterator; +import java.util.List; + +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.annotation.NextView; +import br.gov.frameworkdemoiselle.annotation.PreviousView; +import br.gov.frameworkdemoiselle.stereotype.ViewController; +import br.gov.frameworkdemoiselle.template.AbstractListPageBean; +import br.gov.frameworkdemoiselle.transaction.Transactional; + +import ${package}.business.BookmarkBC; +import ${package}.domain.Bookmark; + +@ViewController +@NextView("/bookmark_edit.xhtml") +@PreviousView("/bookmark_list.xhtml") +public class BookmarkListMB extends AbstractListPageBean { + + private static final long serialVersionUID = 1L; + + @Inject + private BookmarkBC bc; + + @Override + protected List handleResultList() { + return this.bc.findAll(); + } + + @Transactional + public String deleteSelection() { + boolean delete; + for (Iterator iter = getSelection().keySet().iterator(); iter.hasNext();) { + Long id = iter.next(); + delete = getSelection().get(id); + + if (delete) { + bc.delete(id); + iter.remove(); + } + } + return getPreviousView(); + } + +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..d565263 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml @@ -0,0 +1,11 @@ + + + + br.gov.frameworkdemoiselle.transaction.JPATransaction + + + + diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/persistence.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..855fd84 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,56 @@ + + + + + + + java:/DefaultDS + + ${package}.domain.Bookmark + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/ValidationMessages.properties b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/ValidationMessages.properties new file mode 100644 index 0000000..0d63b4b --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/ValidationMessages.properties @@ -0,0 +1,28 @@ +br.gov.frameworkdemoiselle.pispasep=Informe um PIS/PASEP v\u00E1lido. +br.gov.frameworkdemoiselle.inscricaoestadual=Informe uma Inscri\u00E7\u00E3o Estadual v\u00E1lida. +br.gov.frameworkdemoiselle.cpf=Informe um CPF v\u00E1lido. +br.gov.frameworkdemoiselle.cnpj=Informe um CNPJ v\u00E1lido. +br.gov.frameworkdemoiselle.cep=Informe um CEP v\u00E1lido. + +javax.validation.constraints.AssertFalse.message=Este campo deve conter o valor falso. +javax.validation.constraints.AssertTrue.message=Este campo deve conter o valor verdadeiro. +javax.validation.constraints.DecimalMax.message=O valor deve ser menor ou igual a {value}. +javax.validation.constraints.DecimalMin.message=O valor deve ser maior ou igual a {value}. +javax.validation.constraints.Digits.message=Valor num\u00E9rico incorreto. (<{integer} d\u00EDgitos>.<{fraction} d\u00EDgitos> esperado). +javax.validation.constraints.Future.message=Deve ser uma data no futuro. +javax.validation.constraints.Max.message=O valor deve ser menor ou igual a {value}. +javax.validation.constraints.Min.message=O valor deve ser maior ou igual a {value}. +javax.validation.constraints.NotNull.message=N\u00E3o pode ser nulo. +javax.validation.constraints.Null.message=Deve ser nulo. +javax.validation.constraints.Past.message=Deve ser uma data no passado. +javax.validation.constraints.Pattern.message=O valor deve seguir o padr\u00E3o "{regexp}". +javax.validation.constraints.Size.message=O tamanho deve ser entre {min} e {max}. + +org.hibernate.validator.constraints.Email.message=E-mail inv\u00E1lido. +org.hibernate.validator.constraints.Length.message=O tamanho deve ser entre {min} e {max}. +org.hibernate.validator.constraints.NotBlank.message=N\u00E3o pode ser vazio. +org.hibernate.validator.constraints.NotEmpty.message=N\u00E3o pode ser vazio. +org.hibernate.validator.constraints.Range.message=Deve ser um valor entre {min} e {max}. +org.hibernate.validator.constraints.URL.message=Endere\u00E7o de Internet inv\u00E1lido. +org.hibernate.validator.constraints.CreditCardNumber.message=N\u00FAmero de cart\u00E3o de cr\u00E9dito inv\u00E1lido. +org.hibernate.validator.constraints.ScriptAssert.message=Express\u00E3o de script "{script}" n\u00E3o avaliada como verdadeira. diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties new file mode 100755 index 0000000..2d3d565 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties @@ -0,0 +1,35 @@ +# 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. + diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/log4j.properties b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/log4j.properties new file mode 100644 index 0000000..2bd7e2d --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/log4j.properties @@ -0,0 +1,10 @@ +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=INFO, A1 +log4j.logger.br.gov.demoiselle=DEBUG, A1 + +# A1 is set to be a ConsoleAppender. +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c - %m%n \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/messages.properties b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/messages.properties new file mode 100644 index 0000000..a5bcd2c --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/resources/messages.properties @@ -0,0 +1,45 @@ +menu.bookmark=Bookmarks +bookmark.label=Bookmark + +bookmark-delete-ok=Bookmark exclu\u00EDdo\: {0} +bookmark-insert-ok=Bookmark inserido: {0} +bookmark-update-ok=Bookmark atualizado: {0} + +bookmark.list.table.title=Lista de Links + +bookmark.label.id=ID +bookmark.label.link=Link +bookmark.label.description=Descri\u00E7\u00E3o + +bookmark.alt.id=ID +bookmark.alt.link=Link +bookmark.alt.description=Descri\u00E7\u00E3o + +button.add.new=Incluir Novo +button.back=Voltar +button.delete=Excluir +button.dialog.no=N\u00E3o, desculpe\! +button.dialog.yes=Sim, claro! +button.edit=Editar +button.new=Novo +button.save=Salvar + +label.action=A\u00E7\u00E3o +label.dialog.alert=Alerta +label.dialog.delete=Excluir +label.confirm.delete=Confirma? +label.date.pattern=dd/MM/yyyy + +main.app.title=Bookmarks +main.app.welcome=Bem-vindo \u00E0 aplica\u00E7\u00E3o de exemplo Bookmark. Este \u00E9 o seu ponto de partida, portanto sinta-se \u00E0 vontade para modificar esta aplica\u00E7\u00E3o. +main.change.skin=Mudar Pele +main.skin=Pele +main.footer.text=Aplica\u00E7\u00E3o de exemplo do Demoiselle ${parent.version} + +menu.language=Idioma +menu.menuitem.language-portuguese=Portugu\u00EAs +menu.menuitem.language-english=Ingl\u00EAs +menu.menuitem.contents=Conte\u00FAdo +menu.menuitem.list=Listar +menu.menuitem.new=Novo +menu.menuitem.quit=Sair diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/faces-config.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/faces-config.xml new file mode 100755 index 0000000..dcbddcb --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,5 @@ + + + + diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 0000000..ad4a12c --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + + Faces Servlet + *.jsf + + + + Restrict raw XHTML Documents + + XHTML + *.xhtml + + + + + diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_edit.xhtml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_edit.xhtml new file mode 100644 index 0000000..8f6fa8a --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_edit.xhtml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + +
+
+
\ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_list.xhtml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_list.xhtml new file mode 100644 index 0000000..413e4c3 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/bookmark_list.xhtml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + #{messages['bookmark.list.table.title']} + + + + + #{messages['bookmark.label.id']} + + + + #{messages['bookmark.label.description']} + + + + + + + #{messages['bookmark.label.link']} + + + + + + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/images/logo.png b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/images/logo.png new file mode 100644 index 0000000..5be30b0 Binary files /dev/null and b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/images/logo.png differ diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.html b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.html new file mode 100644 index 0000000..80c5da2 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.html @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.xhtml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.xhtml new file mode 100644 index 0000000..2d68848 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/index.xhtml @@ -0,0 +1,11 @@ + + + + + #{messages['main.app.welcome']} + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/menu.xhtml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/menu.xhtml new file mode 100644 index 0000000..06eeb15 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/menu.xhtml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/template/main.xhtml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/template/main.xhtml new file mode 100644 index 0000000..9efb84d --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/main/webapp/template/main.xhtml @@ -0,0 +1,40 @@ + + + + + + #{messages['main.app.title']} + + + + + + + + + + + + + + + + + + +
#{messages['main.footer.text']}
+ + + + + + + + + + + + +
+ \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/business/BookmarkBCTest.java b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/business/BookmarkBCTest.java new file mode 100644 index 0000000..ef2188d --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/business/BookmarkBCTest.java @@ -0,0 +1,77 @@ +package ${package}.business; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import javax.inject.Inject; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import br.gov.frameworkdemoiselle.junit.DemoiselleRunner; +import ${package}.domain.Bookmark; + +@RunWith(DemoiselleRunner.class) +public class BookmarkBCTest { + + @Inject + private BookmarkBC bookmarkBC; + + @Before + public void before() { + for (Bookmark bookmark : bookmarkBC.findAll()) { + bookmarkBC.delete(bookmark.getId()); + } + } + + @Test + public void testLoad() { + bookmarkBC.load(); + List listaBookmarks = bookmarkBC.findAll(); + assertNotNull(listaBookmarks); + assertEquals(10, listaBookmarks.size()); + } + + @Test + public void testInsert() { + Bookmark bookmark = new Bookmark("Demoiselle Portal", "http://www.frameworkdemoiselle.gov.br"); + bookmarkBC.insert(bookmark); + List listaBookmarks = bookmarkBC.findAll(); + assertNotNull(listaBookmarks); + assertEquals(1, listaBookmarks.size()); + } + + @Test + public void testDelete() { + Bookmark bookmark = new Bookmark("Demoiselle Portal", "http://www.frameworkdemoiselle.gov.br"); + bookmarkBC.insert(bookmark); + + List listaBookmarks = bookmarkBC.findAll(); + assertNotNull(listaBookmarks); + assertEquals(1, listaBookmarks.size()); + + bookmarkBC.delete(bookmark.getId()); + listaBookmarks = bookmarkBC.findAll(); + assertEquals(0, listaBookmarks.size()); + } + @Test + public void testUpdate() { + Bookmark bookmark = new Bookmark("Demoiselle Portal", "http://www.frameworkdemoiselle.gov.br"); + bookmarkBC.insert(bookmark); + + List listaBookmarks = bookmarkBC.findAll(); + Bookmark bookmark2 = (Bookmark)listaBookmarks.get(0); + assertNotNull(listaBookmarks); + assertEquals("Demoiselle Portal", bookmark2.getDescription()); + + bookmark2.setDescription("Demoiselle Portal alterado"); + bookmarkBC.update(bookmark2); + + listaBookmarks = bookmarkBC.findAll(); + Bookmark bookmark3 = (Bookmark)listaBookmarks.get(0); + assertEquals("Demoiselle Portal alterado", bookmark3.getDescription()); + } +} diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/readme.txt b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/readme.txt new file mode 100755 index 0000000..3dcdd73 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/java/readme.txt @@ -0,0 +1 @@ +resource files to test \ No newline at end of file diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000..efbdb57 --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml @@ -0,0 +1,4 @@ + + + diff --git a/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/persistence.xml b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/persistence.xml new file mode 100644 index 0000000..868e32a --- /dev/null +++ b/archetype/jsf-jpa/src/main/resources/archetype-resources/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,60 @@ + + + + + + + + ${package}.domain.Bookmark + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archetype/minimal/.gitignore b/archetype/minimal/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/archetype/minimal/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/archetype/minimal/pom.xml b/archetype/minimal/pom.xml new file mode 100755 index 0000000..c15ae50 --- /dev/null +++ b/archetype/minimal/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + br.gov.frameworkdemoiselle.archetypes + demoiselle-minimal + jar + + + br.gov.frameworkdemoiselle + demoiselle-archetype-parent + 2.2.1-SNAPSHOT + ../../parent/archetype/pom.xml + + + Minimal Archetype + Basic archetype for generic applications + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/archetype/minimal/src/main/resources/META-INF/maven/archetype-metadata.xml b/archetype/minimal/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100755 index 0000000..5572cf2 --- /dev/null +++ b/archetype/minimal/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,63 @@ + + + + + + + + readme.txt + + + + src/main/java + + + src/main/resources + + + src/test/java + + + src/test/resources + + + + \ No newline at end of file diff --git a/archetype/minimal/src/main/resources/archetype-resources/pom.xml b/archetype/minimal/src/main/resources/archetype-resources/pom.xml new file mode 100755 index 0000000..4140647 --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,36 @@ + + + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + jar + + + + + + + br.gov.frameworkdemoiselle + demoiselle-minimal-parent + #{parent.version} + + + + + org.slf4j + slf4j-log4j12 + test + + + + + + demoiselle.sourceforge.net-release + http://demoiselle.sourceforge.net/repository/release + + + \ No newline at end of file diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/main/java/HelloWorld.java b/archetype/minimal/src/main/resources/archetype-resources/src/main/java/HelloWorld.java new file mode 100644 index 0000000..d30ee3c --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/main/java/HelloWorld.java @@ -0,0 +1,15 @@ +package ${package}; + +import javax.inject.Inject; + +import org.slf4j.Logger; + +public class HelloWorld { + + @Inject + private Logger logger; + + public void say() { + logger.info("Saying hello on console"); + } +} diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml b/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..f49f2f2 --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml @@ -0,0 +1,4 @@ + + + diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties b/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/main/resources/demoiselle.properties diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/test/java/HelloWorldTest.java b/archetype/minimal/src/main/resources/archetype-resources/src/test/java/HelloWorldTest.java new file mode 100644 index 0000000..d562e91 --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/test/java/HelloWorldTest.java @@ -0,0 +1,23 @@ +package ${package}; + +import static junit.framework.Assert.assertNotNull; + +import javax.inject.Inject; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import br.gov.frameworkdemoiselle.junit.DemoiselleRunner; + +@RunWith(DemoiselleRunner.class) +public class HelloWorldTest { + + @Inject + private HelloWorld helloWorld; + + @Test + public void say() { + assertNotNull(helloWorld); + helloWorld.say(); + } +} diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml b/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000..f49f2f2 --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml @@ -0,0 +1,4 @@ + + + diff --git a/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/log4j.properties b/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/log4j.properties new file mode 100644 index 0000000..e0a61fa --- /dev/null +++ b/archetype/minimal/src/main/resources/archetype-resources/src/test/resources/log4j.properties @@ -0,0 +1,9 @@ +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=INFO, A1 + +# A1 is set to be a ConsoleAppender. +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c - %m%n \ No newline at end of file diff --git a/archetype/pom.xml b/archetype/pom.xml new file mode 100644 index 0000000..b1639ff --- /dev/null +++ b/archetype/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + demoiselle-archetype-build-aggregator + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../parent/root/pom.xml + + + Archetypes Build Aggregator + + + + + jsf-jpa + minimal + + + + + + org.codehaus.mojo + wagon-maven-plugin + + true + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/core/.gitignore b/core/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/core/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 0000000..2d18a9c --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,167 @@ + + + + 4.0.0 + + demoiselle-core + jar + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../parent/root/pom.xml + + + + Serpro + http://www.serpro.gov.br + + + Core + + Contém funcionalidades comuns a todos os projetos e extensões do framework de forma independente de + camadas de apresentação e persistência. + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-site-plugin + + + org.codehaus.mojo + cobertura-maven-plugin + + + + + + + javax.enterprise + cdi-api + + + validation-api + javax.validation + + + org.slf4j + slf4j-api + + + commons-configuration + commons-configuration + + + commons-digester + commons-digester + + + log4j + log4j + + + servlet-api + javax.servlet + + + logkit + logkit + + + avalon-framework + avalon-framework + + + + + + + junit + junit + test + + + org.easymock + easymock + test + + + org.powermock + powermock-module-junit4 + test + + + org.powermock + powermock-api-easymock + test + + + javax.el + el-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/DemoiselleException.java b/core/src/main/java/br/gov/frameworkdemoiselle/DemoiselleException.java new file mode 100644 index 0000000..76578b4 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/DemoiselleException.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 br.gov.frameworkdemoiselle; + +/** + * 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/br/gov/frameworkdemoiselle/annotation/Ignore.java b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Ignore.java new file mode 100644 index 0000000..498742f --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Ignore.java @@ -0,0 +1,48 @@ +/* + * 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 br.gov.frameworkdemoiselle.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; + +@Target(FIELD) +@Retention(RUNTIME) +public @interface Ignore { +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Name.java b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Name.java new file mode 100644 index 0000000..828edae --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Name.java @@ -0,0 +1,59 @@ +/* + * 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 br.gov.frameworkdemoiselle.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; + +@Inherited +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +public @interface Name { + + @Nonbinding + String value(); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Shutdown.java b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Shutdown.java new file mode 100644 index 0000000..4312bd5 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Shutdown.java @@ -0,0 +1,91 @@ +/* + * 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 br.gov.frameworkdemoiselle.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Identifies a method eligible to be executed automatically during application finalization. + *

+ * Take a look at the following usage sample: + *

+ *

+ * + *
+ * public class Finalizer {
+ * 
+ * 	@Shutdown(priority = 5)
+ *    public void finalize() {
+ *       ...
+ *    }
+ * }
+ * 
+ * 
+ * 
+ * 
+ * + *
+ *

+ * The @Shutdown annotation allows an integer value to be defined, which stands for the method execution + * priority when several finalizer classes are available in the application. + * + * @author SERPRO + */ +@Target(METHOD) +@Retention(RUNTIME) +public @interface Shutdown { + + /** + * Most important priority value. + */ + public static int MAX_PRIORITY = Integer.MIN_VALUE; + + /** + * Less important priority value. + */ + public static int MIN_PRIORITY = Integer.MAX_VALUE; + + /** + * An integer value defines method execution order (i.e., priority). + */ + int priority() default MIN_PRIORITY; + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Startup.java b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Startup.java new file mode 100644 index 0000000..5dc87ed --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/Startup.java @@ -0,0 +1,90 @@ +/* + * 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 br.gov.frameworkdemoiselle.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Identifies a method eligible to be executed automatically during application initialization. + *

+ * Take a look at the following usage sample: + *

+ *

+ * + *
+ * public class Initializer {
+ * 
+ * 	@Startup(priority = 1)
+ *    public void initialize() {
+ *       ...
+ *    }
+ * }
+ * 
+ * 
+ * 
+ * + *
+ *

+ * The @Startup annotation allows an integer value to be defined, which stands for the method execution + * priority when several initializer classes are available in the application. + * + * @author SERPRO + */ +@Target(METHOD) +@Retention(RUNTIME) +public @interface Startup { + + /** + * Most important priority value. + */ + public static int MAX_PRIORITY = Integer.MIN_VALUE; + + /** + * Less important priority value. + */ + public static int MIN_PRIORITY = Integer.MAX_VALUE; + + /** + * An integer value defines method execution order (i.e., priority). + */ + int priority() default MIN_PRIORITY; + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/annotation/ViewScoped.java b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/ViewScoped.java new file mode 100644 index 0000000..965febd --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/annotation/ViewScoped.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 br.gov.frameworkdemoiselle.annotation; + +import static java.lang.annotation.ElementType.FIELD; +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.enterprise.context.NormalScope; + +@Inherited +@Target({ METHOD, TYPE, FIELD }) +@Retention(RUNTIME) +@NormalScope +public @interface ViewScoped { + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigType.java b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigType.java new file mode 100644 index 0000000..648cf91 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigType.java @@ -0,0 +1,61 @@ +/* + * 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 br.gov.frameworkdemoiselle.configuration; + +/** + * Defines configuration types to be loaded. + * + * @author SERPRO + */ +public enum ConfigType { + + /** + * Configuration loaded on {@link System#getProperties()} or {@link System#getenv()}. + */ + SYSTEM, + + /** + * Configuration loaded on XML resources. + */ + XML, + + /** + * Configuration loaded on properties resources. + */ + PROPERTIES; + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/configuration/Configuration.java b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/Configuration.java new file mode 100644 index 0000000..916ce7b --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/Configuration.java @@ -0,0 +1,106 @@ +/* + * 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 br.gov.frameworkdemoiselle.configuration; + +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.inject.Stereotype; +import javax.inject.Singleton; + +/** + * Identifies a configuration class, that is, a structure reserved to store configuration values retrieved from a + * given resource file or system variables. + *

+ * This class is gonna have a single instance throughout the application, as stated by the singleton design + * pattern approach. + *

+ * A Configuration is: + *

    + *
  • defined when annotated with {@code @Configuration}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + */ +@Singleton +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface Configuration { + + public static final 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 + */ + ConfigType type() default ConfigType.PROPERTIES; + + /** + * Defines an optional prefix to be used on every parameter key. + *

+ * For instance, if prefix is set to "frameworkdemoiselle.pagination" and an attribute named + * defaultPageSize is found in the class, the corresponding key + * frameworkdemoiselle.pagination.defaultPageSize is expected to be read in the resource file. + * + * @return String + */ + String prefix() default ""; + + /** + * 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 rather considered. + * + * @return String + */ + String resource() default DEFAULT_RESOURCE; + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigurationException.java b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigurationException.java new file mode 100644 index 0000000..833ea98 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/configuration/ConfigurationException.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 br.gov.frameworkdemoiselle.configuration; + +import br.gov.frameworkdemoiselle.DemoiselleException; + +/** + * Exception class intended to be used by configuration components. + * + * @author SERPRO + */ +public class ConfigurationException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor with message. + * + * @param message + * exception message + */ + 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/core/src/main/java/br/gov/frameworkdemoiselle/exception/ApplicationException.java b/core/src/main/java/br/gov/frameworkdemoiselle/exception/ApplicationException.java new file mode 100644 index 0000000..3609c0f --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/exception/ApplicationException.java @@ -0,0 +1,75 @@ +/* + * 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 br.gov.frameworkdemoiselle.exception; + +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.inject.Stereotype; + +import br.gov.frameworkdemoiselle.message.SeverityType; + +/** + * Annotation to be used in application exceptions. Exceptions marked with this annotation can receive special treatment + * like transaction management and special messages based on severity type attribute. + * + * @author CETEC + */ +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface ApplicationException { + + /** + * When raised, the exception that uses this annotation must cause a rollback in the current transaction? + * + * @return True if current transaction must be rolledback + */ + boolean rollback() default true; + + /** + * Exception Severity. + * + * @return + */ + SeverityType severity() default SeverityType.INFO; +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/exception/ExceptionHandler.java b/core/src/main/java/br/gov/frameworkdemoiselle/exception/ExceptionHandler.java new file mode 100644 index 0000000..14b840d --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/exception/ExceptionHandler.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 br.gov.frameworkdemoiselle.exception; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import br.gov.frameworkdemoiselle.stereotype.BusinessController; +import br.gov.frameworkdemoiselle.stereotype.PersistenceController; +import br.gov.frameworkdemoiselle.stereotype.ViewController; + +/** + *

+ * Should be used exclusively with controller objects, i.e., classes annotated with {@link ViewController}, + * {@link BusinessController}, or {@link PersistenceController}. + *

+ *

+ * Methods that use this annotation will automatically handle all exceptions of a specific type thrown by the method + * owner class. + *

+ * + * @author SERPRO + */ +@Inherited +@Target(METHOD) +@Retention(RUNTIME) +public @interface ExceptionHandler { +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrap.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrap.java new file mode 100644 index 0000000..7d48a00 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrap.java @@ -0,0 +1,77 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.Extension; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.context.Contexts; +import br.gov.frameworkdemoiselle.internal.context.CustomContext; +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +public class AbstractBootstrap implements Extension { + + private static ResourceBundleProducer bundleFactory = new ResourceBundleProducer(); + + protected static ResourceBundle getBundle() { + return getBundle("demoiselle-core-bundle"); + } + + protected static ResourceBundle getBundle(String baseName) { + return bundleFactory.create(baseName); + } + + protected static Logger getLogger() { + return LoggerProducer.create(AbstractBootstrap.class); + } + + protected static void addContext(final CustomContext context, final AfterBeanDiscovery event) { + Contexts.add(context, event); + getLogger() + .trace(getBundle().getString("custom-context-was-registered", context.getScope().getCanonicalName())); + } + + protected static void disableContext(final CustomContext context) { + Contexts.remove(context); + getLogger() + .trace(getBundle().getString("custom-context-was-registered", context.getScope().getCanonicalName())); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ConfigurationBootstrap.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ConfigurationBootstrap.java new file mode 100644 index 0000000..a4c87bf --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ConfigurationBootstrap.java @@ -0,0 +1,95 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.AfterDeploymentValidation; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.configuration.ConfigurationException; +import br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.util.Beans; + +/** + * @author SERPRO + */ +public class ConfigurationBootstrap extends AbstractBootstrap { + + private static List> types = Collections.synchronizedList(new ArrayList>()); + + private static final String MSG_PROCESSING = "bootstrap.configuration.processing"; + + private ThreadLocalContext c1; + + private ThreadLocalContext c2; + + public void detectAnnotation(@Observes final ProcessAnnotatedType event, final BeanManager beanManager) { + if (event.getAnnotatedType().isAnnotationPresent(Configuration.class)) { + types.add(event.getAnnotatedType()); + } + } + + public void loadTempContexts(@Observes final AfterBeanDiscovery event) { + c1 = new ThreadLocalContext(RequestScoped.class); + addContext(c1, event); + c2 = new ThreadLocalContext(SessionScoped.class); + addContext(c2, event); + } + + public void processLoader(@Observes final AfterDeploymentValidation event) + throws ConfigurationException { + ConfigurationLoader configurationLoader = Beans.getReference(ConfigurationLoader.class); + for (AnnotatedType type : types) { + getLogger().debug(getBundle().getString(MSG_PROCESSING, type.toString())); + configurationLoader.load(Beans.getReference(type.getJavaClass())); + } + disableContext(c1); + disableContext(c2); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java new file mode 100644 index 0000000..2937890 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java @@ -0,0 +1,94 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterDeploymentValidation; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.BeforeBeanDiscovery; +import javax.enterprise.inject.spi.BeforeShutdown; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.util.Beans; + +//TODO Inter [NQ]: verificar o melhor nome para todas as classes desta natureza. +public class CoreBootstrap extends AbstractBootstrap { + + private static final Map, AnnotatedType> beans = new HashMap, AnnotatedType>(); + + public static boolean isAnnotatedType(Class type) { + return beans.containsKey(type); + } + + public void engineOn(@Observes final BeforeBeanDiscovery event, BeanManager beanManager) { + String description; + Logger log = getLogger(); + + description = getBundle("demoiselle-core-bundle").getString("engine-on"); + log.info(description); + + Beans.setBeanManager(beanManager); + + description = getBundle("demoiselle-core-bundle").getString("setting-up-bean-manager", + Beans.class.getCanonicalName()); + log.info(description); + } + + protected void detectAnnotation(@Observes final ProcessAnnotatedType event) { + beans.put(event.getAnnotatedType().getJavaClass(), event.getAnnotatedType()); + } + + public static void takeOff(@Observes final AfterDeploymentValidation event) { + String description = getBundle("demoiselle-core-bundle").getString("taking-off"); + + Logger log = getLogger(); + log.info(description); + } + + public static void engineOff(@Observes final BeforeShutdown event) { + String description = getBundle("demoiselle-core-bundle").getString("engine-off"); + + Logger log = getLogger(); + log.info(description); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrap.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrap.java new file mode 100644 index 0000000..7561388 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrap.java @@ -0,0 +1,138 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.enterprise.context.ConversationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.BeforeShutdown; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import br.gov.frameworkdemoiselle.annotation.Shutdown; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.context.CustomContext; +import br.gov.frameworkdemoiselle.internal.processor.ShutdownProcessor; + +/** + * This class run at application shutdown + */ +public class ShutdownBootstrap extends AbstractBootstrap { + + private static final Class annotationClass = Shutdown.class; + + private static final List tempContexts = new ArrayList(); + + @SuppressWarnings("rawtypes") + private static final List processors = Collections + .synchronizedList(new ArrayList()); + + private static AfterBeanDiscovery event; + + /** + * Observes all methods annotated with @Shutdown and create an instance of ShutdownProcessor for them + * + * @param + * @param event + * @param beanManager + */ + public void processAnnotatedType(@Observes final ProcessAnnotatedType event, final BeanManager beanManager) { + final AnnotatedType annotatedType = event.getAnnotatedType(); + for (AnnotatedMethod am : annotatedType.getMethods()) { + if (am.isAnnotationPresent(annotationClass)) { + @SuppressWarnings("unchecked") + AnnotatedMethod annotatedMethod = (AnnotatedMethod) am; + processors.add(new ShutdownProcessor(annotatedMethod, beanManager)); + } + } + } + + public void saveEvent(@Observes final AfterBeanDiscovery event) { + ShutdownBootstrap.event = event; + } + + public static void loadTempContexts(final AfterBeanDiscovery event) { + // Não registrar o contexto de aplicação pq ele já é registrado pela + // implementação do CDI + tempContexts.add(new ThreadLocalContext(ViewScoped.class)); + tempContexts.add(new ThreadLocalContext(SessionScoped.class, false)); + tempContexts.add(new ThreadLocalContext(ConversationScoped.class)); + tempContexts.add(new ThreadLocalContext(RequestScoped.class)); + + for (CustomContext tempContext : tempContexts) { + addContext(tempContext, event); + } + } + + /** + * Before Shutdown it execute the methods annotateds with @Shutdown considering the priority order; + * + * @param event + * @throws Exception + */ + @SuppressWarnings("unchecked") + public static void shuttingDown(@Observes final BeforeShutdown event) throws Throwable { + loadTempContexts(ShutdownBootstrap.event); + + getLogger().debug( + getBundle("demoiselle-core-bundle").getString("executing-all", annotationClass.getSimpleName())); + Collections.sort(processors); + + for (ShutdownProcessor processor : processors) { + processor.process(); + } + + processors.clear(); + unloadTempContexts(); + } + + private static void unloadTempContexts() { + for (CustomContext tempContext : tempContexts) { + disableContext(tempContext); + } + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrap.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrap.java new file mode 100644 index 0000000..0e0e256 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrap.java @@ -0,0 +1,128 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.enterprise.context.ConversationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.AfterDeploymentValidation; +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import br.gov.frameworkdemoiselle.annotation.Startup; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.processor.StartupProcessor; + +/** + * This class is the bootstrap to execute the processes at load time. + */ +public class StartupBootstrap extends AbstractBootstrap { + + private static final Class annotationClass = Startup.class; + + private final List tempContexts = new ArrayList(); + + @SuppressWarnings("rawtypes") + private static final List processors = Collections + .synchronizedList(new ArrayList()); + + /** + * Observes all methods annotated with @Startup and create an instance of StartupAction for them + * + * @param + * @param event + * @param beanManager + */ + public void processAnnotatedType(@Observes final ProcessAnnotatedType event, final BeanManager beanManager) { + final AnnotatedType annotatedType = event.getAnnotatedType(); + for (AnnotatedMethod am : annotatedType.getMethods()) { + if (am.isAnnotationPresent(annotationClass)) { + @SuppressWarnings("unchecked") + AnnotatedMethod annotatedMethod = (AnnotatedMethod) am; + processors.add(new StartupProcessor(annotatedMethod, beanManager)); + } + } + } + + public void loadTempContexts(@Observes final AfterBeanDiscovery event) { + //Não registrar o contexto de aplicação pq ele já é registrado pela implementação do CDI + this.tempContexts.add(new ThreadLocalContext(ViewScoped.class)); + this.tempContexts.add(new ThreadLocalContext(SessionScoped.class)); + this.tempContexts.add(new ThreadLocalContext(ConversationScoped.class)); + this.tempContexts.add(new ThreadLocalContext(RequestScoped.class)); + + for (ThreadLocalContext tempContext : this.tempContexts) { + addContext(tempContext, event); + } + } + + /** + * After the deployment validation it execute the methods annotateds with @Startup considering the priority order; + * + * @param event + * @throws Exception + * @throws StartupException + */ + @SuppressWarnings("unchecked") + public void startup(@Observes final AfterDeploymentValidation event) throws Throwable { + getLogger().debug( + getBundle("demoiselle-core-bundle").getString("executing-all", annotationClass.getSimpleName())); + Collections.sort(processors); + + for (StartupProcessor action : processors) { + action.process(); + } + processors.clear(); + unloadTempContexts(); + } + + private void unloadTempContexts() { + for (ThreadLocalContext tempContext : this.tempContexts) { + disableContext(tempContext); + } + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java new file mode 100644 index 0000000..b633000 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java @@ -0,0 +1,301 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import javax.inject.Inject; +import javax.validation.constraints.NotNull; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.SystemConfiguration; +import org.apache.commons.configuration.XMLConfiguration; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Ignore; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.ConfigType; +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.configuration.ConfigurationException; +import br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap; +import br.gov.frameworkdemoiselle.util.Reflections; +import br.gov.frameworkdemoiselle.util.ResourceBundle; +import br.gov.frameworkdemoiselle.util.Strings; + +/** + * This component loads a config class annotated with {@link Configuration} by filling its attributes with {@link Param} + * according to a {@link ConfigType}. + * + * @author SERPRO + */ +public class ConfigurationLoader { + + @Inject + @Name("demoiselle-core-bundle") + private ResourceBundle bundle; + + @Inject + private Logger logger; + + /** + * Loads a config class filling it with the corresponding values. + * + * @param object + * config object + * @throws ConfigurationException + */ + public void load(Object object) throws ConfigurationException { + Class config = object.getClass(); + + if (!CoreBootstrap.isAnnotatedType(config)) { + config = config.getSuperclass(); + logger.debug(bundle.getString("proxy-detected", config, config.getClass().getSuperclass())); + } + + logger.debug(bundle.getString("loading-configuration-class", config.getName())); + + for (Field field : Reflections.getNonStaticDeclaredFields(config)) { + loadField(field, object, config); + } + } + + private void loadField(Field field, Object object, Class clazz) { + if (!field.isAnnotationPresent(Ignore.class) && clazz.isAnnotationPresent(Configuration.class)) { + String resource = clazz.getAnnotation(Configuration.class).resource(); + ConfigType type = clazz.getAnnotation(Configuration.class).type(); + org.apache.commons.configuration.Configuration config = getConfiguration(resource, type); + + String key = getKey(field, clazz, config); + Object value = getValue(key, field.getType(), config); + + validate(field, key, value, resource); + setValue(field, key, object, value); + } + } + + private void setValue(Field field, String key, Object object, Object value) { + if (value != null) { + Reflections.setFieldValue(field, object, value); + logger.debug(bundle.getString("configuration-field-loaded", key, field.getName(), value)); + } + } + + private void validate(Field field, String key, Object value, String resource) { + if (field.isAnnotationPresent(NotNull.class) && value == null) { + throw new ConfigurationException(bundle.getString("configuration-attribute-is-mandatory", key, resource)); + } + } + + private String getKey(final Field field, final Class clazz, + final org.apache.commons.configuration.Configuration config) { + + final String prefix = getPrefix(field, clazz); + final StringBuffer key = new StringBuffer(); + + key.append(prefix); + + if (field.isAnnotationPresent(Name.class)) { + key.append(getKeyByAnnotation(field)); + } else { + key.append(getKeyByConvention(field, prefix, config)); + } + + return key.toString(); + } + + private String getPrefix(Field field, Class type) { + String prefix = ""; + + Configuration classAnnotation = type.getAnnotation(Configuration.class); + if (!Strings.isEmpty(classAnnotation.prefix())) { + prefix = classAnnotation.prefix() + "."; + } + + return prefix; + } + + private String getKeyByAnnotation(Field field) { + String key = null; + + Name nameAnnotation = field.getAnnotation(Name.class); + if (Strings.isEmpty(nameAnnotation.value())) { + throw new ConfigurationException(bundle.getString("configuration-name-attribute-cant-be-empty")); + } else { + key = nameAnnotation.value(); + } + + return key; + } + + private String getKeyByConvention(Field field, String prefix, org.apache.commons.configuration.Configuration config) { + + Set conventions = new HashSet(); + conventions.add(field.getName()); + conventions.add(Strings.camelCaseToSymbolSeparated(field.getName(), ".")); + conventions.add(Strings.camelCaseToSymbolSeparated(field.getName(), "_")); + conventions.add(field.getName().toLowerCase()); + conventions.add(field.getName().toUpperCase()); + + int matches = 0; + String key = field.getName(); + for (String convention : conventions) { + if (config.containsKey(prefix + convention)) { + key = convention; + matches++; + } + } + + if (matches == 0) { + logger.debug(bundle.getString("configuration-key-not-found", key, conventions)); + } else if (matches > 1) { + throw new ConfigurationException(bundle.getString("ambiguous-key", field.getName(), + field.getDeclaringClass())); + } + + return key; + } + + /** + * Returns the configuration class according to specified resource name and configuration type. + * + * @param resource + * @param type + * @return a configuration + */ + private org.apache.commons.configuration.Configuration getConfiguration(String resource, ConfigType type) { + org.apache.commons.configuration.Configuration config = null; + + try { + switch (type) { + case SYSTEM: + config = new SystemConfiguration(); + break; + + case PROPERTIES: + config = new PropertiesConfiguration(resource + ".properties"); + break; + + case XML: + config = new XMLConfiguration(resource + ".xml"); + break; + + default: + throw new ConfigurationException(bundle.getString("configuration-type-not-implemented-yet", + type.name())); + } + + } catch (Exception cause) { + throw new ConfigurationException(bundle.getString("error-creating-configuration-from-resource", resource), + cause); + } + + return config; + } + + /** + * Returns the value associated with the given configuration class and field type. + * + * @param name + * @param config + * @param fieldClass + * @return the value + */ + @SuppressWarnings("unchecked") + private T getValue(String key, Class fieldClass, org.apache.commons.configuration.Configuration config) { + Object value; + + if (fieldClass.isArray() && fieldClass.getComponentType().equals(String.class)) { + value = config.getStringArray(key); + + } else if (fieldClass.equals(Properties.class)) { + value = getProperty(key, config); + + } else { + value = getBasic(key, fieldClass, config); + } + + return (T) value; + } + + private Object getBasic(String key, Class fieldClass, org.apache.commons.configuration.Configuration config) { + Object value = null; + + try { + Method method; + String methodName = "get" + Strings.firstToUpper(fieldClass.getSimpleName()); + + if (!fieldClass.isPrimitive()) { + method = config.getClass().getMethod(methodName, String.class, fieldClass); + value = method.invoke(config, key, null); + } else if (config.containsKey(key)) { + method = config.getClass().getMethod(methodName, String.class); + value = method.invoke(config, key); + } + + } catch (Throwable cause) { + throw new ConfigurationException(bundle.getString("error-converting-to-type", fieldClass.getName()), cause); + } + + return value; + } + + private Object getProperty(String key, org.apache.commons.configuration.Configuration config) { + Object value = null; + + @SuppressWarnings("unchecked") + Iterator iterator = config.getKeys(key); + if (iterator.hasNext()) { + Properties props = new Properties(); + + while (iterator.hasNext()) { + String fullKey = iterator.next(); + String prefix = key + "."; + String unprefixedKey = fullKey.substring(prefix.length()); + props.put(unprefixedKey, config.getString(fullKey)); + } + + value = props; + } + + return value; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfig.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfig.java new file mode 100644 index 0000000..4c07ee6 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfig.java @@ -0,0 +1,81 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +/** + * The PaginationConfig class provides a pagination context to be used where this type of control is + * needed. For example: in a UI as a data grid or on a search to the database. + * + * @author SERPRO + */ +@Configuration(prefix = "frameworkdemoiselle.pagination") +public class PaginationConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("page.size") + private int pageSize = 10; + + @Name("max.page.links") + private int maxPageLinks = 5; + + /** + * Returns the number of rows that will be shown in a data grid. + * + * @return the value defined for the key frameworkdemoiselle.pagination.page.size in the + * demoiselle.properties file. If there is no value defined, returns the default value 10 + */ + public int getPageSize() { + return pageSize; + } + + /** + * Returns the maximum number of pages that will be shown in a data grid footer + * + * @return the value defined for the key frameworkdemoiselle.pagination.max.page.links in the + * demoiselle.properties file. If there is no value defined, returns the default value 5 + */ + public int getMaxPageLinks() { + return maxPageLinks; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfig.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfig.java new file mode 100644 index 0000000..f0642ec --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfig.java @@ -0,0 +1,68 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +/** + * A SecurityConfig object is responsible for specifying which security configurations should be used for a + * particular application. + * + * @author SERPRO + */ +@Configuration(prefix = "frameworkdemoiselle.security") +public class SecurityConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("enabled") + private boolean enabled = true; + + /** + * Tells whether or not the security is enabled for the current application. This value could be defined in the + * demoiselle.properties file, using the key frameworkdemoiselle.security.enabled. + * + * @return the value defined for the key frameworkdemoiselle.security.enabled in the + * demoiselle.properties file. If there is no value defined, returns the default value true + */ + public boolean isEnabled() { + return enabled; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextStore.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextStore.java new file mode 100644 index 0000000..2055b25 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextStore.java @@ -0,0 +1,58 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import java.util.Map; +import java.util.TreeMap; + +public class ContextStore { + + private Map map = new TreeMap(); + + public boolean contains(final String name) { + return this.map.containsKey(name); + } + + public Object get(final String name) { + return this.map.get(name); + } + + public void put(final String name, final Object instance) { + this.map.put(name, instance); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/Contexts.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/Contexts.java new file mode 100644 index 0000000..ba51b14 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/Contexts.java @@ -0,0 +1,123 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.enterprise.inject.spi.AfterBeanDiscovery; + +public class Contexts { + + private static List activeContexts; + + private static List inactiveContexts; + + public static void add(CustomContext context, AfterBeanDiscovery event) { + Class scope = context.getScope(); + + if (get(scope, getActiveContexts()) != null) { + getInactiveContexts().add(context); + context.setActive(false); + + } else { + getActiveContexts().add(context); + context.setActive(true); + } + + if (event != null) { + event.addContext(context); + } + } + + private static CustomContext get(Class scope, List contexts) { + CustomContext result = null; + + for (CustomContext context : contexts) { + if (scope.equals(context.getScope())) { + result = context; + break; + } + } + + return result; + } + + public static void remove(CustomContext context) { + if (getActiveContexts().contains(context)) { + getActiveContexts().remove(context); + context.setActive(false); + + CustomContext inactive = get(context.getScope(), getInactiveContexts()); + if (inactive != null) { + getActiveContexts().add(inactive); + inactive.setActive(true); + getInactiveContexts().remove(inactive); + } + + } else if (getInactiveContexts().contains(context)) { + getInactiveContexts().remove(context); + } + } + + public static void clear() { + for (CustomContext context : getActiveContexts()) { + context.setActive(false); + } + + activeContexts = null; + inactiveContexts = null; + } + + public static List getActiveContexts() { + if (activeContexts == null) { + activeContexts = Collections.synchronizedList(new ArrayList()); + } + + return activeContexts; + } + + public static List getInactiveContexts() { + if (inactiveContexts == null) { + inactiveContexts = Collections.synchronizedList(new ArrayList()); + } + + return inactiveContexts; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java new file mode 100644 index 0000000..a515b0a --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java @@ -0,0 +1,45 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import javax.enterprise.context.spi.Context; + +public interface CustomContext extends Context { + + void setActive(boolean b); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java new file mode 100644 index 0000000..9ca4f27 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java @@ -0,0 +1,130 @@ +/* + * 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. + */ +/* + * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the + * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE + * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is + * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 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 3 as published by the Free Software Foundation. Demoiselle Framework + * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You + * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see + * . + */ +package br.gov.frameworkdemoiselle.internal.context; + +import java.lang.annotation.Annotation; + +import javax.enterprise.context.ContextNotActiveException; +import javax.enterprise.context.spi.Contextual; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; + +public class ThreadLocalContext implements CustomContext { + + private final ThreadLocal threadLocal = new ThreadLocal(); + + private boolean active; + + private final Class scope; + + public ThreadLocalContext(final Class scope) { + this(scope, true); + } + + public ThreadLocalContext(final Class scope, + boolean active) { + this.scope = scope; + this.active = active; + } + + @Override + public T get(final Contextual contextual) { + return get(contextual, null); + } + + @Override + @SuppressWarnings("unchecked") + public T get(final Contextual contextual, + final CreationalContext creationalContext) { + T instance = null; + + if (!isActive()) { + throw new ContextNotActiveException(); + } + + String id = getId(contextual); + if (getStore().contains(id)) { + instance = (T) getStore().get(id); + + } else if (creationalContext != null) { + instance = contextual.create(creationalContext); + getStore().put(id, instance); + } + + return instance; + } + + private String getId(final Contextual contextual) { + Bean bean = (Bean) contextual; + return bean.getBeanClass().getCanonicalName(); + } + + @Override + public Class getScope() { + return this.scope; + } + + private ContextStore getStore() { + if (this.threadLocal.get() == null) { + this.threadLocal.set(new ContextStore()); + } + + return this.threadLocal.get(); + } + + @Override + public boolean isActive() { + return this.active; + } + + public void setActive(final boolean active) { + this.active = active; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/CoreBundle.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/CoreBundle.java new file mode 100644 index 0000000..15cb590 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/CoreBundle.java @@ -0,0 +1,28 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +public class CoreBundle { + + @Inject + @Name("demoiselle-core-bundle") + private ResourceBundle bundle; + + private static CoreBundle instance; + + private static synchronized CoreBundle getInstance() { + if (instance == null) { + instance = Beans.getReference(CoreBundle.class); + } + + return instance; + } + + public static ResourceBundle get() { + return getInstance().bundle; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticator.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticator.java new file mode 100644 index 0000000..f29f578 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticator.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 br.gov.frameworkdemoiselle.internal.implementation; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.security.Authenticator; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.security.User; + +/** + * Authenticator that actually does nothing but raise exceptions. + * + * @author SERPRO + * @see Authenticator + */ +public class DefaultAuthenticator implements Authenticator { + + private static final long serialVersionUID = 1L; + + /** + * @see br.gov.frameworkdemoiselle.security.Authenticator#authenticate() + */ + @Override + public boolean authenticate() { + throw getException(); + } + + /** + * @see br.gov.frameworkdemoiselle.security.Authenticator#unAuthenticate() + */ + @Override + public void unAuthenticate() { + throw getException(); + } + + /** + * @see br.gov.frameworkdemoiselle.security.Authenticator#getUser() + */ + @Override + public User getUser() { + throw getException(); + } + + private DemoiselleException getException() { + return new DemoiselleException(CoreBundle.get().getString("authenticator-not-defined", + SecurityContext.class.getSimpleName())); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizer.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizer.java new file mode 100644 index 0000000..bc2175c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizer.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 br.gov.frameworkdemoiselle.internal.implementation; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.security.Authorizer; +import br.gov.frameworkdemoiselle.security.RequiredPermission; +import br.gov.frameworkdemoiselle.security.RequiredRole; + +/** + * Authorizator that actually does nothing but raise exceptions. + * + * @author SERPRO + * @see Authorizer + */ +public class DefaultAuthorizer implements Authorizer { + + private static final long serialVersionUID = 1L; + + @Override + public boolean hasRole(String role) { + throw new DemoiselleException(CoreBundle.get().getString("authorizer-not-defined", + RequiredRole.class.getSimpleName())); + } + + @Override + public boolean hasPermission(String resource, String operation) { + throw new DemoiselleException(CoreBundle.get().getString("authorizer-not-defined", + RequiredPermission.class.getSimpleName())); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransaction.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransaction.java new file mode 100644 index 0000000..02f4df0 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransaction.java @@ -0,0 +1,90 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.enterprise.context.SessionScoped; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.transaction.Transaction; +import br.gov.frameworkdemoiselle.transaction.Transactional; + +/** + * Transaction strategy that actually does nothing but raise exceptions. + * + * @author SERPRO + * @see Transaction + */ +@SessionScoped +public class DefaultTransaction implements Transaction { + + private static final long serialVersionUID = 1L; + + @Override + public void begin() { + throw getException(); + } + + @Override + public void commit() { + throw getException(); + } + + @Override + public boolean isActive() { + throw getException(); + } + + @Override + public boolean isMarkedRollback() { + throw getException(); + } + + @Override + public void rollback() { + throw getException(); + } + + @Override + public void setRollbackOnly() { + throw getException(); + } + + private DemoiselleException getException() { + return new DemoiselleException(CoreBundle.get().getString("transaction-not-defined", + Transactional.class.getSimpleName())); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImpl.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImpl.java new file mode 100644 index 0000000..605c273 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImpl.java @@ -0,0 +1,105 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.enterprise.context.SessionScoped; +import javax.inject.Inject; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.message.DefaultMessage; +import br.gov.frameworkdemoiselle.message.Message; +import br.gov.frameworkdemoiselle.message.MessageContext; +import br.gov.frameworkdemoiselle.message.SeverityType; + +/** + * The message store is designed to provide access to messages. It is shared by every application layer. + * + * @see MessageContext + */ +@SessionScoped +//@ConversationScoped +// FIXME colocar o escopo de conversação, para não ter que limpar o contexto manualmente. Ou seria melhor colocar no +// escopo de request para não precisar se preocupar com isso? +public class MessageContextImpl implements Serializable, MessageContext { + + private static final long serialVersionUID = 1L; + + @Inject + private Logger logger; + + private final List messages = new ArrayList(); + + @Override + public void add(final Message message, Object... params) { + Message aux; + + if (params != null) { + aux = new DefaultMessage(message.getText(), message.getSeverity(), params); + } else { + aux = message; + } + + logger.debug(CoreBundle.get().getString("adding-message-to-context", message.toString())); + messages.add(aux); + } + + @Override + public void add(String text, Object... params) { + add(text, null, params); + } + + @Override + public void add(String text, SeverityType severity, Object... params) { + add(new DefaultMessage(text, severity, params)); + } + + @Override + public List getMessages() { + return messages; + } + + @Override + public void clear() { + logger.debug(CoreBundle.get().getString("cleaning-message-context")); + messages.clear(); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImpl.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImpl.java new file mode 100644 index 0000000..cfc6232 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImpl.java @@ -0,0 +1,84 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.internal.configuration.PaginationConfig; +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; + +/** + * Context implementation reserved for pagination purposes. Internally a hash map is used to store pagination data for + * each class type. + * + * @author SERPRO + * @see PaginationContext + */ +@SessionScoped +public class PaginationContextImpl implements Serializable, PaginationContext { + + private static final long serialVersionUID = 1L; + + @Inject + private PaginationConfig config; + + private final Map, Pagination> cache = new HashMap, Pagination>(); + + public Pagination getPagination(final Class clazz) { + return this.getPagination(clazz, false); + } + + public Pagination getPagination(final Class clazz, final boolean create) { + Pagination pagination = cache.get(clazz); + + if (pagination == null && create) { + pagination = new PaginationImpl(); + pagination.setPageSize(config.getPageSize()); + + cache.put(clazz, pagination); + } + + return pagination; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImpl.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImpl.java new file mode 100644 index 0000000..9244378 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImpl.java @@ -0,0 +1,184 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; + +import javax.enterprise.inject.Alternative; + +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.util.Strings; + +/** + * Structure used to handle pagination of data results on both backend (i.e., persistence) and frontend + * (i.e., presentation) layers in the application. + *

+ * Internally, it stores the current page index on {@code currentPage} variable, the amount of records in a single page + * on {@code pageSize}, and the total number of pages in {@code totalPages}. + * + * @author SERPRO + * @see Pagination + */ +@Alternative +public class PaginationImpl implements Serializable, Pagination { + + private static final long serialVersionUID = 1L; + + private int currentPage; + + private int pageSize; + + private int totalResults; + + private int totalPages; + + public PaginationImpl() { + pageSize = 0; + totalResults = 0; + reset(); + } + + private void reset() { + currentPage = 0; + totalPages = 0; + } + + public int getCurrentPage() { + return currentPage; + } + + private void setTotalPages(int totalPages) { + validateNegativeValue(totalPages); + this.totalPages = totalPages; + + if (totalPages == 0) { + reset(); + } else if (getCurrentPage() >= totalPages) { + setCurrentPage(totalPages - 1); + } + } + + private void validateNegativeValue(int input) throws IndexOutOfBoundsException { + if (input < 0) { + throw new IndexOutOfBoundsException("colocar mensagem"); + } + } + + private void validateCurrentPage(int currentPage) throws IndexOutOfBoundsException { + if (currentPage >= this.totalPages) { + if (this.totalPages > 0) { + throw new IndexOutOfBoundsException("colocar mensagem"); + } + } + } + + public void setCurrentPage(int currentPage) { + validateNegativeValue(currentPage); + validateCurrentPage(currentPage); + this.currentPage = currentPage; + } + + public int getPageSize() { + return pageSize; + } + + public int getTotalResults() { + return totalResults; + } + + public void setTotalResults(int totalResults) { + validateNegativeValue(totalResults); + this.totalResults = totalResults; + + if (totalResults > 0) { + setTotalPages(); + } else { + reset(); + } + } + + private void setTotalPages() { + if (totalResults > 0) { + setTotalPages((int) Math.ceil(totalResults * 1d / getPageSize())); + } else { + setTotalPages(0); + } + } + + public int getTotalPages() { + return totalPages; + } + + public int getFirstResult() { + return getCurrentPage() * getPageSize(); + } + + public void setPageSize(int pageSize) { + validateNegativeValue(pageSize); + this.pageSize = pageSize; + + if (pageSize > 0) { + setTotalPages(); + } else { + reset(); + } + } + + private void validateFirstResult(int firstResult) throws IndexOutOfBoundsException { + if (firstResult >= this.totalResults) { + if (this.totalResults > 0) { + throw new IndexOutOfBoundsException("colocar mensagem"); + } + } + } + + public void setFirstResult(int firstResult) { + validateNegativeValue(firstResult); + validateFirstResult(firstResult); + + if (firstResult > 0) { + setCurrentPage(firstResult / pageSize); + } else { + setCurrentPage(0); + } + } + + @Override + public String toString() { + return Strings.toString(this); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImpl.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImpl.java new file mode 100644 index 0000000..51e86f1 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImpl.java @@ -0,0 +1,185 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.enterprise.context.SessionScoped; +import javax.inject.Inject; +import javax.inject.Named; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.internal.configuration.SecurityConfig; +import br.gov.frameworkdemoiselle.security.AfterLoginSuccessful; +import br.gov.frameworkdemoiselle.security.AfterLogoutSuccessful; +import br.gov.frameworkdemoiselle.security.Authenticator; +import br.gov.frameworkdemoiselle.security.Authorizer; +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.security.User; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * This is the default implementation of {@link SecurityContext} interface. + * + * @author SERPRO + */ +@SessionScoped +@Named("securityContext") +public class SecurityContextImpl implements SecurityContext { + + private static final long serialVersionUID = 1L; + + @Inject + @Name("demoiselle-core-bundle") + private ResourceBundle bundle; + + @Inject + private Authenticator authenticator; + + @Inject + private Authorizer authorizer; + + @Inject + private SecurityConfig config; + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#hasPermission(java.lang.String, java.lang.String) + */ + @Override + public boolean hasPermission(String resource, String operation) throws NotLoggedInException { + if (config.isEnabled()) { + checkLoggedIn(); + return authorizer.hasPermission(resource, operation); + + } else { + return true; + } + } + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#hasRole(java.lang.String) + */ + @Override + public boolean hasRole(String role) throws NotLoggedInException { + if (config.isEnabled()) { + checkLoggedIn(); + return authorizer.hasRole(role); + + } else { + return true; + } + } + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#isLoggedIn() + */ + @Override + public boolean isLoggedIn() { + if (config.isEnabled()) { + return getUser() != null; + } else { + return true; + } + } + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#login() + */ + @Override + public void login() { + if (config.isEnabled() && authenticator.authenticate()) { + Beans.getBeanManager().fireEvent(new AfterLoginSuccessful() { + + private static final long serialVersionUID = 1L; + + }); + } + } + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#logout() + */ + @Override + public void logout() throws NotLoggedInException { + if (config.isEnabled()) { + checkLoggedIn(); + authenticator.unAuthenticate(); + + Beans.getBeanManager().fireEvent(new AfterLogoutSuccessful() { + + private static final long serialVersionUID = 1L; + }); + } + } + + /** + * @see br.gov.frameworkdemoiselle.security.SecurityContext#getUser() + */ + @Override + public User getUser() { + User user = authenticator.getUser(); + + if (!config.isEnabled() && user == null) { + user = new User() { + + private static final long serialVersionUID = 1L; + + @Override + public void setAttribute(Object key, Object value) { + } + + @Override + public String getId() { + return "demoiselle"; + } + + @Override + public Object getAttribute(Object key) { + return null; + } + }; + } + + return user; + } + + private void checkLoggedIn() throws NotLoggedInException { + if (!isLoggedIn()) { + throw new NotLoggedInException(bundle.getString("user-not-authenticated")); + } + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/TransactionInfo.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/TransactionInfo.java new file mode 100644 index 0000000..d56211f --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/TransactionInfo.java @@ -0,0 +1,37 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; + +import javax.enterprise.context.RequestScoped; + +//TODO Inter [NQ]: considerar a necessidade da criação de um contexto de transação para manter a coerência com as demais funcionalidades que possuem um contexto. +//Resposta: não foi feito porque só foi identificado uma funcionalidade (getCurrentTransaction). Aguardar novas ideias. +@RequestScoped +public class TransactionInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + private int counter = 0; + + private boolean owner = false; + + public int getCounter() { + return counter; + } + + public void incrementCounter() { + this.counter++; + } + + public void decrementCounter() { + this.counter--; + } + + public void markAsOwner() { + this.owner = true; + } + + public boolean isOwner() { + return owner; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptor.java new file mode 100644 index 0000000..89e187e --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptor.java @@ -0,0 +1,177 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import javax.inject.Inject; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.exception.ExceptionHandler; +import br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap; +import br.gov.frameworkdemoiselle.stereotype.Controller; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@Interceptor +@Controller +public class ExceptionHandlerInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + private final ResourceBundle bundle; + + private final Logger logger; + + @Inject + public ExceptionHandlerInterceptor(Logger logger, @Name("demoiselle-core-bundle") ResourceBundle bundle) { + this.logger = logger; + this.bundle = bundle; + } + + private final Map, Map, Method>> cache = new HashMap, Map, Method>>(); + + private final boolean handleException(final Exception cause, final InvocationContext ic) throws Throwable { + logger.info(bundle.getString("handling-exception", cause.getClass().getCanonicalName())); + + boolean handled = false; + Class type = getType(ic); + + if (!isLoaded(type)) { + loadHandlers(type); + } + + Method handler = getMethod(type, cause); + if (handler != null) { + invoke(handler, ic.getTarget(), cause); + handled = true; + } + + return handled; + } + + private final Class getType(final InvocationContext ic) { + Class type = ic.getTarget().getClass(); + + if (!CoreBootstrap.isAnnotatedType(type)) { + type = type.getSuperclass(); + logger.debug(bundle.getString("proxy-detected", ic.getTarget().getClass(), ic.getTarget().getClass() + .getSuperclass())); + } + + return type; + } + + /** + * If there is an handler in the current class for the expected exception, then this method will be returned; Else + * returns null; + * + * @param type + * @param cause + * @return + */ + private final Method getMethod(final Class type, final Exception cause) { + Method handler = null; + + if (cache.containsKey(type) && cache.get(type).containsKey(cause.getClass())) { + handler = cache.get(type).get(cause.getClass()); + } + + return handler; + } + + /** + * Create an map of Exception Handler for this class and put it on the cache. + * + * @param type + */ + private final void loadHandlers(final Class type) { + Map, Method> mapHandlers = new HashMap, Method>(); + Method[] methods = type.getMethods(); + + for (Method method : methods) { + if (method.isAnnotationPresent(ExceptionHandler.class)) { + validateHandler(method); + mapHandlers.put(method.getParameterTypes()[0], method); + } + } + cache.put(type, mapHandlers); + } + + /** + * Verify the method for compliance with an handler. It must be: public, single parameter, parameter type must be + * assigned from Exception + * + * @param method + */ + private final void validateHandler(final Method method) { + if (method.getParameterTypes().length != 1) { + throw new DemoiselleException(bundle.getString("must-declare-one-single-parameter", + method.toGenericString())); + } + } + + /** + * Indicates if this class is already loaded in cache control. + * + * @param type + * @return + */ + private final boolean isLoaded(final Class type) { + return cache.containsKey(type); + } + + private final void invoke(final Method method, final Object object, final Exception param) throws Throwable { + boolean accessible = method.isAccessible(); + method.setAccessible(true); + + try { + method.invoke(object, param); + } catch (InvocationTargetException cause) { + throw cause.getTargetException(); + } + + method.setAccessible(accessible); + } + + @AroundInvoke + public Object manage(final InvocationContext ic) throws Throwable { + Object result = null; + + try { + result = ic.proceed(); + } catch (Exception cause) { + if (!handleException(cause, ic)) { + throw cause; + } + } + + return result; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptor.java new file mode 100644 index 0000000..b53e4c4 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptor.java @@ -0,0 +1,176 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import java.io.Serializable; + +import javax.enterprise.inject.Instance; +import javax.inject.Inject; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.security.AuthorizationException; +import br.gov.frameworkdemoiselle.security.RequiredPermission; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.security.User; +import br.gov.frameworkdemoiselle.util.ResourceBundle; +import br.gov.frameworkdemoiselle.util.Strings; + +/** + * Intercepts calls with {@code @RequiredPermission} annotations. + * + * @author SERPRO + */ +@Interceptor +@RequiredPermission +public class RequiredPermissionInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Instance securityContext; + + private final ResourceBundle bundle; + + private final Logger logger; + + @Inject + public RequiredPermissionInterceptor(Instance securityContext, + @Name("demoiselle-core-bundle") ResourceBundle bundle, Logger logger) { + this.securityContext = securityContext; + this.bundle = bundle; + this.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 (securityContext.get().isLoggedIn()) { + username = getUsername(); + logger.trace(bundle.getString("access-checking", username, operation, resource)); + } + + if (!securityContext.get().hasPermission(resource, operation)) { + logger.error(bundle.getString("access-denied", username, operation, resource)); + throw new AuthorizationException(bundle.getString("access-denied-ui", resource, operation)); + } + + logger.debug(bundle.getString("access-allowed", username, operation, resource)); + return ic.proceed(); + } + + /** + * Returns the id of the currently logged in user. + * + * @return the id of the currently logged in user + */ + private String getUsername() { + String username = ""; + User user = securityContext.get().getUser(); + + if (user != null && user.getId() != null) { + username = user.getId(); + } + + return username; + } + + /** + * Returns the resource defined in {@code @RequiredPermission} annotation, the name defined in {@code @Name} + * 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 @Name} + * annotation or the class name itself + */ + private String getResource(InvocationContext ic) { + RequiredPermission requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); + + if (requiredPermission == null || 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 @Name} + * 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 @Name} + * annotation or the method's name itself + */ + private String getOperation(InvocationContext ic) { + RequiredPermission requiredPermission = ic.getMethod().getAnnotation(RequiredPermission.class); + + if (requiredPermission == null || 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(); + } + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptor.java new file mode 100644 index 0000000..f4e268d --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptor.java @@ -0,0 +1,152 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.enterprise.inject.Instance; +import javax.inject.Inject; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.security.AuthorizationException; +import br.gov.frameworkdemoiselle.security.RequiredRole; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * Intercepts calls with {@code @RequiredRole} annotations. + * + * @author SERPRO + */ +@Interceptor +@RequiredRole(value = "") +public class RequiredRoleInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Instance securityContext; + + private final ResourceBundle bundle; + + private final Logger logger; + + @Inject + public RequiredRoleInterceptor(Instance securityContext, + @Name("demoiselle-core-bundle") ResourceBundle bundle, Logger logger) { + this.securityContext = securityContext; + this.bundle = bundle; + this.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 (securityContext.get().isLoggedIn()) { + logger.info(bundle.getString("has-role-verification", securityContext.get().getUser().getId(), roles)); + } + + List userRoles = new ArrayList(); + + for (String role : roles) { + if (securityContext.get().hasRole(role)) { + userRoles.add(role); + } + } + + if (userRoles.isEmpty()) { + logger.error(bundle.getString("does-not-have-role", securityContext.get().getUser().getId(), roles)); + + @SuppressWarnings("unused") + AuthorizationException a = new AuthorizationException(null); + throw new AuthorizationException(bundle.getString("does-not-have-role-ui", roles)); + } + + logger.debug(bundle.getString("user-has-role", securityContext.get().getUser().getId(), 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) { + + if (ic.getTarget().getClass().getAnnotation(RequiredRole.class) != null) { + roles = ic.getTarget().getClass().getAnnotation(RequiredRole.class).value(); + } + + } else { + + roles = ic.getMethod().getAnnotation(RequiredRole.class).value(); + + } + + return Arrays.asList(roles); + + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptor.java new file mode 100644 index 0000000..e0c5dda --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptor.java @@ -0,0 +1,152 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import java.io.Serializable; + +import javax.enterprise.inject.Instance; +import javax.inject.Inject; +import javax.interceptor.AroundInvoke; +import javax.interceptor.Interceptor; +import javax.interceptor.InvocationContext; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.exception.ApplicationException; +import br.gov.frameworkdemoiselle.internal.implementation.TransactionInfo; +import br.gov.frameworkdemoiselle.transaction.Transaction; +import br.gov.frameworkdemoiselle.transaction.Transactional; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@Interceptor +@Transactional +public class TransactionalInterceptor implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Instance transaction; + + private final Logger logger; + + private final ResourceBundle bundle; + + private final Instance transactionInfo; + + @Inject + public TransactionalInterceptor(Instance transaction, Instance transactionInfo, + Logger logger, @Name("demoiselle-core-bundle") ResourceBundle bundle) { + this.transaction = transaction; + this.transactionInfo = transactionInfo; + this.logger = logger; + this.bundle = bundle; + + } + + @AroundInvoke + public Object manage(final InvocationContext ic) throws Exception { + initiate(ic); + + Object result = null; + try { + this.logger.debug(bundle.getString("transactional-execution", ic.getMethod().toGenericString())); + transactionInfo.get().incrementCounter(); + + result = ic.proceed(); + + } catch (Exception cause) { + handleException(cause); + throw cause; + + } finally { + transactionInfo.get().decrementCounter(); + complete(ic); + } + + return result; + } + + private void initiate(final InvocationContext ic) { + Transaction tx = this.transaction.get(); + TransactionInfo ctx = this.transactionInfo.get(); + + if (!tx.isActive()) { + tx.begin(); + ctx.markAsOwner(); + this.logger.info(bundle.getString("begin-transaction")); + } + } + + private void handleException(final Exception cause) { + Transaction tx = this.transaction.get(); + + if (!tx.isMarkedRollback()) { + boolean rollback = false; + ApplicationException annotation = cause.getClass().getAnnotation(ApplicationException.class); + + if (annotation == null || annotation.rollback()) { + rollback = true; + } + + if (rollback) { + tx.setRollbackOnly(); + this.logger.info(bundle.getString("transaction-marked-rollback", cause.getMessage())); + } + } + } + + private void complete(final InvocationContext ic) { + Transaction tx = this.transaction.get(); + TransactionInfo ctx = this.transactionInfo.get(); + + if (ctx.getCounter() == 0 && tx.isActive()) { + + if (ctx.isOwner()) { + if (tx.isMarkedRollback()) { + tx.rollback(); + this.logger.info(bundle.getString("transaction-rolledback")); + } else { + tx.commit(); + this.logger.info(bundle.getString("transaction-commited")); + } + } + + } else if (ctx.getCounter() == 0 && !tx.isActive()) { + this.logger.info(bundle.getString("transaction-already-finalized")); + } + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AbstractProcessor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AbstractProcessor.java new file mode 100644 index 0000000..62a73e8 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AbstractProcessor.java @@ -0,0 +1,117 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.processor; + +import javax.enterprise.inject.spi.AnnotatedCallable; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * It abstract the integration between Processor and the context; + * + * @param + * the declaring class + */ +public abstract class AbstractProcessor implements Processor { + + private BeanManager beanManager; + + private AnnotatedCallable annotatedCallable; + + private ResourceBundleProducer bundleFactory = new ResourceBundleProducer(); + + private ResourceBundle bundle; + + protected static final String BUNDLE_BASE_NAME = "demoiselle-core-bundle"; + + public AbstractProcessor(final BeanManager beanManager) { + this.beanManager = beanManager; + } + + public AbstractProcessor(final AnnotatedCallable annotatedCallable, final BeanManager beanManager) { + this.annotatedCallable = annotatedCallable; + this.beanManager = beanManager; + } + + protected AnnotatedCallable getAnnotatedCallable() { + return this.annotatedCallable; + } + + protected BeanManager getBeanManager() { + return this.beanManager; + } + + /** + * Ask the bean manager for the firt instance of the declaring classe for this java member, then returns the current + * reference; + * + * @param + * DeclaringClass + * @return + */ + @SuppressWarnings("unchecked") + protected DC getReferencedBean() { + Class classType = (Class) getAnnotatedCallable().getJavaMember().getDeclaringClass(); + return getReferencedBean(classType); + } + + @SuppressWarnings("unchecked") + protected DC getReferencedBean(final Class type) { + Bean bean = (Bean) beanManager.getBeans(type).iterator().next(); + return (DC) beanManager.getReference(bean, type, beanManager.createCreationalContext(bean)); + } + + protected ResourceBundle getBundle() { + return getBundle(BUNDLE_BASE_NAME); + } + + protected ResourceBundle getBundle(String baseName) { + if (bundle == null) + bundle = bundleFactory.create(baseName); + return bundle; + } + + protected Logger getLogger() { + return LoggerProducer.create(this.getClass()); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AnnotatedMethodProcessor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AnnotatedMethodProcessor.java new file mode 100644 index 0000000..cd04d13 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/AnnotatedMethodProcessor.java @@ -0,0 +1,105 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.processor; + +import java.lang.reflect.InvocationTargetException; + +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.BeanManager; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; +import br.gov.frameworkdemoiselle.message.SeverityType; + +/** + * Represents an annotated method to be processed; + * + * @param + * declaring class owner of the method + */ +public class AnnotatedMethodProcessor extends AbstractProcessor { + + public AnnotatedMethodProcessor(final AnnotatedMethod annotatedMethod, final BeanManager beanManager) { + super(annotatedMethod, beanManager); + } + + protected AnnotatedMethod getAnnotatedMethod() { + return (AnnotatedMethod) getAnnotatedCallable(); + } + + public boolean process(Object... args) throws Throwable { + getLogger().info(getBundle().getString("processing", getAnnotatedMethod().getJavaMember().toGenericString())); + + try { + getAnnotatedMethod().getJavaMember().invoke(getReferencedBean(), args); + + } catch (InvocationTargetException cause) { + handleException(cause.getCause()); + } + + return true; + } + + private void handleException(Throwable cause) throws Throwable { + ApplicationException ann = cause.getClass().getAnnotation(ApplicationException.class); + + if (ann == null || SeverityType.FATAL == ann.severity()) { + throw cause; + + } else { + switch (ann.severity()) { + case INFO: + getLogger().info(cause.getMessage()); + break; + + case WARN: + getLogger().warn(cause.getMessage()); + break; + + default: + getLogger().error(getBundle().getString("processing-fail"), cause); + break; + } + } + } + + @Override + public String toString() { + return getBundle().getString("for", getClass().getSimpleName(), + getAnnotatedMethod().getJavaMember().toGenericString()); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/Processor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/Processor.java new file mode 100644 index 0000000..4147293 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/Processor.java @@ -0,0 +1,45 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.processor; + +/** + * Represents an classe that can be processed. + */ +public interface Processor { + + public boolean process(Object... args) throws Throwable; +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/ShutdownProcessor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/ShutdownProcessor.java new file mode 100644 index 0000000..b249e90 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/ShutdownProcessor.java @@ -0,0 +1,63 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.processor; + +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.BeanManager; + +import br.gov.frameworkdemoiselle.annotation.Shutdown; + +public class ShutdownProcessor extends AnnotatedMethodProcessor implements Comparable> { + + public ShutdownProcessor(AnnotatedMethod annotatedMethod, BeanManager beanManager) { + super(annotatedMethod, beanManager); + } + + @Override + public int compareTo(final ShutdownProcessor other) { + int result = 0; + Shutdown annotationThis = getAnnotatedMethod().getAnnotation(Shutdown.class); + Shutdown annotationOther = other.getAnnotatedMethod().getAnnotation(Shutdown.class); + if (annotationThis != null && annotationThis != null) { + Integer orderThis = annotationThis.priority(); + Integer orderOther = annotationOther.priority(); + result = orderThis.compareTo(orderOther); + } + return result; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/StartupProcessor.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/StartupProcessor.java new file mode 100644 index 0000000..01a5eee --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/processor/StartupProcessor.java @@ -0,0 +1,68 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.processor; + +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.BeanManager; + +import br.gov.frameworkdemoiselle.annotation.Startup; + +/** + * Processor for a {@code @Startup} annotated method, making it comparable. + * + * @param + */ +public class StartupProcessor extends AnnotatedMethodProcessor implements Comparable> { + + public StartupProcessor(final AnnotatedMethod annotatedMethod, final BeanManager beanManager) { + super(annotatedMethod, beanManager); + } + + @Override + public int compareTo(final StartupProcessor other) { + int result = 0; + Startup annotationThis = getAnnotatedMethod().getAnnotation(Startup.class); + Startup annotationOther = other.getAnnotatedMethod().getAnnotation(Startup.class); + if (annotationThis != null && annotationOther != null) { + Integer orderThis = annotationThis.priority(); + Integer orderOther = annotationOther.priority(); + result = orderThis.compareTo(orderOther); + } + return result; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducer.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducer.java new file mode 100644 index 0000000..e2d29be --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducer.java @@ -0,0 +1,84 @@ +/* + * 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. + */ +/* + * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the + * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE + * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is + * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 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 3 as published by the Free Software Foundation. Demoiselle Framework + * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You + * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see + * . + */ +package br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; + +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.internal.proxy.ContextProxy; + +public class ContextProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + // @Inject + // @Name("demoiselle-core-bundle") + // private ResourceBundle bundle; + + @Produces + @Default + public static Context create() { + Context context = null; + + try { + context = new ContextProxy(new InitialContext()); + + } catch (NamingException cause) { + throw new DemoiselleException("Erro ao criar InitialContext", cause); + } + + return context; + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducer.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducer.java new file mode 100644 index 0000000..3a3adb7 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducer.java @@ -0,0 +1,16 @@ +package br.gov.frameworkdemoiselle.internal.producer; + +import java.util.Locale; + +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; + +public class LocaleProducer { + + @Produces + @Default + public Locale create() { + return Locale.getDefault(); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducer.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducer.java new file mode 100644 index 0000000..499350a --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducer.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. + */ +/* + * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the + * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE + * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is + * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 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 3 as published by the Free Software Foundation. Demoiselle Framework + * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You + * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see + * . + */ +package br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; + +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import br.gov.frameworkdemoiselle.internal.proxy.Slf4jLoggerProxy; + +public class LoggerProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + @Produces + @Default + public static Logger create(final InjectionPoint ip) { + Class type; + + if (ip != null) { + type = ip.getMember().getDeclaringClass(); + } else { + type = LoggerProducer.class; + } + + return create(type); + } + + public static Logger create(Class type) { + return new Slf4jLoggerProxy(LoggerFactory.getLogger(type)); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducer.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducer.java new file mode 100644 index 0000000..c77bf7b --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducer.java @@ -0,0 +1,135 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * This factory creates ResourceBundles with the application scopes. + * + * @author SERPRO + */ +@ApplicationScoped +public class ResourceBundleProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + protected Locale locale; + + private final Map map = new HashMap(); + + public ResourceBundleProducer() { + this.locale = Locale.getDefault(); + } + + /** + * This constructor should be used by classes that can not inject ResourceBundle. + * + * @param Locale + * locale + */ + public ResourceBundleProducer(Locale locale) { + this.locale = locale; + } + + /** + * This method should be used by classes that can not inject ResourceBundle, to create the ResourceBundle. + * + * @param String + * baseName + */ + public ResourceBundle create(String baseName) { + return getResourceBundle(baseName); + } + + /** + * This method is the factory default for ResourceBundle. It creates the ResourceBundle based on a file called + * messages.properties. + */ + @Produces + @Default + public ResourceBundle create(InjectionPoint ip, Locale locale) { + this.locale = locale; + String baseName; + + if (ip != null && ip.getAnnotated().isAnnotationPresent(Name.class)) { + baseName = ip.getAnnotated().getAnnotation(Name.class).value(); + } else { + baseName = "messages"; + } + + return create(baseName); + } + + /** + * This method checks if the bundle was created already. If the bundle has not been created, it creates and saves + * the bundle on a Map. + */ + private ResourceBundle getResourceBundle(String baseName) { + ResourceBundle bundle = null; + + if (map.containsKey(baseName + "-" + this.locale)) { + bundle = map.get(baseName + "-" + this.locale); + + } else { + try { + bundle = new ResourceBundle(ResourceBundle.getBundle(baseName, this.locale)); + } catch (MissingResourceException e) { + throw new DemoiselleException("File " + baseName + " not found!"); + } + map.put(baseName + "-" + this.locale, bundle); + } + + return bundle; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxy.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxy.java new file mode 100644 index 0000000..fae2f03 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxy.java @@ -0,0 +1,168 @@ +package br.gov.frameworkdemoiselle.internal.proxy; + +import java.io.Serializable; +import java.util.Hashtable; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +public class ContextProxy implements Context, Serializable { + + private static final long serialVersionUID = 1L; + + private final Context delegate; + + public ContextProxy(Context delegate) { + this.delegate = delegate; + } + + @Override + public Object addToEnvironment(String propName, Object propVal) throws NamingException { + return delegate.addToEnvironment(propName, propVal); + } + + @Override + public void bind(Name name, Object obj) throws NamingException { + delegate.bind(name, obj); + } + + @Override + public void bind(String name, Object obj) throws NamingException { + delegate.bind(name, obj); + } + + @Override + public void close() throws NamingException { + delegate.close(); + } + + @Override + public Name composeName(Name name, Name prefix) throws NamingException { + return delegate.composeName(name, prefix); + } + + @Override + public String composeName(String name, String prefix) throws NamingException { + return delegate.composeName(name, prefix); + } + + @Override + public Context createSubcontext(Name name) throws NamingException { + return delegate.createSubcontext(name); + } + + @Override + public Context createSubcontext(String name) throws NamingException { + return delegate.createSubcontext(name); + } + + @Override + public void destroySubcontext(Name name) throws NamingException { + delegate.destroySubcontext(name); + } + + @Override + public void destroySubcontext(String name) throws NamingException { + delegate.destroySubcontext(name); + } + + @Override + public Hashtable getEnvironment() throws NamingException { + return delegate.getEnvironment(); + } + + @Override + public String getNameInNamespace() throws NamingException { + return delegate.getNameInNamespace(); + } + + @Override + public NameParser getNameParser(Name name) throws NamingException { + return delegate.getNameParser(name); + } + + @Override + public NameParser getNameParser(String name) throws NamingException { + return delegate.getNameParser(name); + } + + @Override + public NamingEnumeration list(Name name) throws NamingException { + return delegate.list(name); + } + + @Override + public NamingEnumeration list(String name) throws NamingException { + return delegate.list(name); + } + + @Override + public NamingEnumeration listBindings(Name name) throws NamingException { + return delegate.listBindings(name); + } + + @Override + public NamingEnumeration listBindings(String name) throws NamingException { + return delegate.listBindings(name); + } + + @Override + public Object lookup(Name name) throws NamingException { + return delegate.lookup(name); + } + + @Override + public Object lookup(String name) throws NamingException { + return delegate.lookup(name); + } + + @Override + public Object lookupLink(Name name) throws NamingException { + return delegate.lookupLink(name); + } + + @Override + public Object lookupLink(String name) throws NamingException { + return delegate.lookupLink(name); + } + + @Override + public void rebind(Name name, Object obj) throws NamingException { + delegate.rebind(name, obj); + } + + @Override + public void rebind(String name, Object obj) throws NamingException { + delegate.rebind(name, obj); + } + + @Override + public Object removeFromEnvironment(String propName) throws NamingException { + return delegate.removeFromEnvironment(propName); + } + + @Override + public void rename(Name oldName, Name newName) throws NamingException { + delegate.rename(oldName, newName); + } + + @Override + public void rename(String oldName, String newName) throws NamingException { + delegate.rename(oldName, newName); + } + + @Override + public void unbind(Name name) throws NamingException { + delegate.unbind(name); + } + + @Override + public void unbind(String name) throws NamingException { + delegate.unbind(name); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxy.java b/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxy.java new file mode 100644 index 0000000..21e7941 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxy.java @@ -0,0 +1,371 @@ +/* + * 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. + */ +/* + * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the + * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE + * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is + * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 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 3 as published by the Free Software Foundation. Demoiselle Framework + * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You + * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see + * . + */ +package br.gov.frameworkdemoiselle.internal.proxy; + +import java.io.Serializable; + +import org.slf4j.Logger; +import org.slf4j.Marker; + +public class Slf4jLoggerProxy implements Logger, Serializable { + + private static final long serialVersionUID = 1L; + + private transient final Logger delegate; + + public Slf4jLoggerProxy(final Logger logger) { + this.delegate = logger; + } + + @Override + public void debug(final Marker marker, final String msg) { + this.delegate.debug(marker, msg); + } + + @Override + public void debug(final Marker marker, final String format, final Object arg) { + this.delegate.debug(marker, format, arg); + } + + @Override + public void debug(final Marker marker, final String format, final Object arg1, final Object arg2) { + this.delegate.debug(marker, format, arg1, arg2); + } + + @Override + public void debug(final Marker marker, final String format, final Object[] argArray) { + this.delegate.debug(marker, format, argArray); + } + + @Override + public void debug(final Marker marker, final String msg, final Throwable t) { + this.delegate.debug(marker, msg, t); + } + + @Override + public void debug(final String msg) { + this.delegate.debug(msg); + } + + @Override + public void debug(final String format, final Object arg) { + this.delegate.debug(format, arg); + } + + @Override + public void debug(final String format, final Object arg1, final Object arg2) { + this.delegate.debug(format, arg1, arg2); + } + + @Override + public void debug(final String format, final Object[] argArray) { + this.delegate.debug(format, argArray); + } + + @Override + public void debug(final String msg, final Throwable t) { + this.delegate.debug(msg, t); + } + + @Override + public void error(final Marker marker, final String msg) { + this.delegate.error(marker, msg); + } + + @Override + public void error(final Marker marker, final String format, final Object arg) { + this.delegate.error(marker, format, arg); + } + + @Override + public void error(final Marker marker, final String format, final Object arg1, final Object arg2) { + this.delegate.error(marker, format, arg1, arg2); + } + + @Override + public void error(final Marker marker, final String format, final Object[] argArray) { + this.delegate.error(marker, format, argArray); + } + + @Override + public void error(final Marker marker, final String msg, final Throwable t) { + this.delegate.error(marker, msg, t); + } + + @Override + public void error(final String msg) { + this.delegate.error(msg); + } + + @Override + public void error(final String format, final Object arg) { + this.delegate.error(format, arg); + } + + @Override + public void error(final String format, final Object arg1, final Object arg2) { + this.delegate.error(format, arg1, arg2); + } + + @Override + public void error(final String format, final Object[] argArray) { + this.delegate.error(format, argArray); + } + + @Override + public void error(final String msg, final Throwable t) { + this.delegate.error(msg, t); + } + + @Override + public String getName() { + return this.delegate.getName(); + } + + @Override + public void info(final Marker marker, final String msg) { + this.delegate.info(marker, msg); + } + + @Override + public void info(final Marker marker, final String format, final Object arg) { + this.delegate.info(marker, format, arg); + } + + @Override + public void info(final Marker marker, final String format, final Object arg1, final Object arg2) { + this.delegate.info(marker, format, arg1, arg2); + } + + @Override + public void info(final Marker marker, final String format, final Object[] argArray) { + this.delegate.info(marker, format, argArray); + } + + @Override + public void info(final Marker marker, final String msg, final Throwable t) { + this.delegate.info(marker, msg, t); + } + + @Override + public void info(final String msg) { + this.delegate.info(msg); + } + + @Override + public void info(final String format, final Object arg) { + this.delegate.info(format, arg); + } + + @Override + public void info(final String format, final Object arg1, final Object arg2) { + this.delegate.info(format, arg1, arg2); + } + + @Override + public void info(final String format, final Object[] argArray) { + this.delegate.info(format, argArray); + } + + @Override + public void info(final String msg, final Throwable t) { + this.delegate.info(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return this.delegate.isDebugEnabled(); + } + + @Override + public boolean isDebugEnabled(final Marker marker) { + return this.delegate.isDebugEnabled(marker); + } + + @Override + public boolean isErrorEnabled() { + return this.delegate.isErrorEnabled(); + } + + @Override + public boolean isErrorEnabled(final Marker marker) { + return this.delegate.isErrorEnabled(marker); + } + + @Override + public boolean isInfoEnabled() { + return this.delegate.isInfoEnabled(); + } + + @Override + public boolean isInfoEnabled(final Marker marker) { + return this.delegate.isInfoEnabled(marker); + } + + @Override + public boolean isTraceEnabled() { + return this.delegate.isTraceEnabled(); + } + + @Override + public boolean isTraceEnabled(final Marker marker) { + return this.delegate.isTraceEnabled(marker); + } + + @Override + public boolean isWarnEnabled() { + return this.delegate.isWarnEnabled(); + } + + @Override + public boolean isWarnEnabled(final Marker marker) { + return this.delegate.isWarnEnabled(marker); + } + + @Override + public void trace(final Marker marker, final String msg) { + this.delegate.trace(marker, msg); + } + + @Override + public void trace(final Marker marker, final String format, final Object arg) { + this.delegate.trace(marker, format, arg); + } + + @Override + public void trace(final Marker marker, final String format, final Object arg1, final Object arg2) { + this.delegate.trace(marker, format, arg1, arg2); + } + + @Override + public void trace(final Marker marker, final String format, final Object[] argArray) { + this.delegate.trace(marker, format, argArray); + } + + @Override + public void trace(final Marker marker, final String msg, final Throwable t) { + this.delegate.trace(marker, msg, t); + } + + @Override + public void trace(final String msg) { + this.delegate.trace(msg); + } + + @Override + public void trace(final String format, final Object arg) { + this.delegate.trace(format, arg); + } + + @Override + public void trace(final String format, final Object arg1, final Object arg2) { + this.delegate.trace(format, arg1, arg2); + } + + @Override + public void trace(final String format, final Object[] argArray) { + this.delegate.trace(format, argArray); + } + + @Override + public void trace(final String msg, final Throwable t) { + this.delegate.trace(msg, t); + } + + @Override + public void warn(final Marker marker, final String msg) { + this.delegate.warn(marker, msg); + } + + @Override + public void warn(final Marker marker, final String format, final Object arg) { + this.delegate.warn(marker, format, arg); + } + + @Override + public void warn(final Marker marker, final String format, final Object arg1, final Object arg2) { + this.delegate.warn(marker, format, arg1, arg2); + } + + @Override + public void warn(final Marker marker, final String format, final Object[] argArray) { + this.delegate.warn(marker, format, argArray); + } + + @Override + public void warn(final Marker marker, final String msg, final Throwable t) { + this.delegate.warn(marker, msg, t); + } + + @Override + public void warn(final String msg) { + this.delegate.warn(msg); + } + + @Override + public void warn(final String format, final Object arg) { + this.delegate.warn(format, arg); + } + + @Override + public void warn(final String format, final Object arg1, final Object arg2) { + this.delegate.warn(format, arg1, arg2); + } + + @Override + public void warn(final String format, final Object[] argArray) { + this.delegate.warn(format, argArray); + } + + @Override + public void warn(final String msg, final Throwable t) { + this.delegate.warn(msg, t); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/message/DefaultMessage.java b/core/src/main/java/br/gov/frameworkdemoiselle/message/DefaultMessage.java new file mode 100644 index 0000000..c75b77d --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/message/DefaultMessage.java @@ -0,0 +1,101 @@ +/* + * 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 br.gov.frameworkdemoiselle.message; + +import javax.enterprise.inject.Alternative; + +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.ResourceBundle; +import br.gov.frameworkdemoiselle.util.Strings; + +/** + * @author SERPRO + */ +@Alternative +public class DefaultMessage implements Message { + + private final String originalText; + + private String parsedText; + + private final SeverityType severity; + + private final Object[] params; + + private final ResourceBundle bundle; + + public static final SeverityType DEFAULT_SEVERITY = SeverityType.INFO; + + public DefaultMessage(String text, SeverityType severity, Object... params) { + this.originalText = text; + this.severity = (severity == null ? DEFAULT_SEVERITY : severity); + this.params = params; + this.bundle = Beans.getReference(ResourceBundle.class); + } + + public DefaultMessage(String text, Object... params) { + this(text, null, (Object[]) params); + } + + public String getText() { + initParsedText(); + return parsedText; + } + + private void initParsedText() { + if (parsedText == null) { + if (Strings.isResourceBundleKeyFormat(originalText)) { + parsedText = bundle.getString(Strings.removeBraces(originalText)); + + } else if (originalText != null) { + parsedText = new String(originalText); + } + + parsedText = Strings.getString(parsedText, params); + } + } + + public SeverityType getSeverity() { + return severity; + } + + @Override + public String toString() { + initParsedText(); + return Strings.toString(this); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/message/Message.java b/core/src/main/java/br/gov/frameworkdemoiselle/message/Message.java new file mode 100644 index 0000000..0a3ed06 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/message/Message.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 br.gov.frameworkdemoiselle.message; + +/** + * Represents the configuration of a single message. + * + * @author SERPRO + */ +public interface Message { + + /** + * Represents the text of the message. + */ + String getText(); + +// void setText(String text); + + /** + * Represents the kind of message. It could be useful for presentation layer. + */ + SeverityType getSeverity(); + +// void setSeverity(SeverityType severity); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/message/MessageContext.java b/core/src/main/java/br/gov/frameworkdemoiselle/message/MessageContext.java new file mode 100644 index 0000000..4675868 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/message/MessageContext.java @@ -0,0 +1,75 @@ +/* + * 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 br.gov.frameworkdemoiselle.message; + +import java.util.List; + +/** + * Context interface reserved for messaging purposes. + *

+ * In order to use this, just add the line below in the code: + *

+ * @Inject MessageContext messageContext; + * + * @author SERPRO + * @see Message + */ +public interface MessageContext { + + /** + * Saves a message into the context. + * + * @param message + */ + + void add(Message message, Object... params); + + void add(String text, Object... params); + + void add(String text, SeverityType severity, Object... params); + + /** + * Returns all messages in the context. + */ + List getMessages(); + + /** + * Clears the list of messages in the context. + */ + void clear(); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/message/SeverityType.java b/core/src/main/java/br/gov/frameworkdemoiselle/message/SeverityType.java new file mode 100644 index 0000000..7b674eb --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/message/SeverityType.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 br.gov.frameworkdemoiselle.message; + +/** + * Defines severity types to be used. + * + * @author SERPRO + */ +public enum SeverityType { + + /** + * Information (less critical) + */ + INFO, + + /** + * Warning + */ + WARN, + + /** + * Error + */ + ERROR, + + /** + * Fatal (most critical) + */ + FATAL + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/pagination/Pagination.java b/core/src/main/java/br/gov/frameworkdemoiselle/pagination/Pagination.java new file mode 100644 index 0000000..a5b36cf --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/pagination/Pagination.java @@ -0,0 +1,92 @@ +/* + * 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 br.gov.frameworkdemoiselle.pagination; + +/** + * Structure used to handle pagination of data results on both backend (i.e., persistence) and frontend + * (i.e., presentation) layers in the application. + * + * @author SERPRO + */ +public interface Pagination { + + /** + * Returns the current page. + */ + int getCurrentPage(); + + /** + * Sets the current page. + */ + void setCurrentPage(int currentPage); + + /** + * Returns the page size. + */ + int getPageSize(); + + /** + * Sets the page size. + */ + void setPageSize(int pageSize); + + /** + * Returns the total number of results. + */ + int getTotalResults(); + + /** + * Sets the total number of results and calculates the number of pages. + */ + void setTotalResults(int totalResults); + + /** + * Returns the total number of pages. + */ + int getTotalPages(); + + /** + * Returns the position for the first record according to current page and page size. + */ + int getFirstResult(); + + /** + * Sets the position for the first record and hence calculates current page according to page size. + */ + void setFirstResult(int firstResult); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/pagination/PaginationContext.java b/core/src/main/java/br/gov/frameworkdemoiselle/pagination/PaginationContext.java new file mode 100644 index 0000000..f6e4519 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/pagination/PaginationContext.java @@ -0,0 +1,69 @@ +/* + * 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 br.gov.frameworkdemoiselle.pagination; + +/** + * Context interface reserved for pagination purposes. + *

+ * In order to use this, just add the line below in the code: + *

+ * @Inject PaginationContext paginationContext; + * + * @author SERPRO + * @see Pagination + */ +public interface PaginationContext { + + /** + * Retrieves the pagination according to the class type specified. + * + * @param clazz a {@code Class} type + * @return Pagination + */ + Pagination getPagination(Class clazz); + + /** + * Retrieves the pagination according to the class type specified. If not existing, creates the pagination whenever + * {@code create} parameter is true. + * + * @param clazz a {@code Class} type + * @param create determines whether pagination must always be returned + * @return Pagination + */ + Pagination getPagination(Class clazz, boolean create); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLoginSuccessful.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLoginSuccessful.java new file mode 100644 index 0000000..69c07c7 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLoginSuccessful.java @@ -0,0 +1,48 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + +/** + * This interface represents an event that is fired when user successfully logs in. + * + * @author SERPRO + */ +public interface AfterLoginSuccessful extends Serializable { + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLogoutSuccessful.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLogoutSuccessful.java new file mode 100644 index 0000000..5b9b43a --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/AfterLogoutSuccessful.java @@ -0,0 +1,48 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + +/** + * This interface represents an event fired just after the user unauthenticates. + * + * @author SERPRO + */ +public interface AfterLogoutSuccessful extends Serializable { + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/Authenticator.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/Authenticator.java new file mode 100644 index 0000000..9ef41e5 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/Authenticator.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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + +/** + * Defines the methods that should be implemented by anyone who wants an authentication mechanism. + * + * @author SERPRO + */ +public interface Authenticator extends Serializable { + + /** + * Executes the necessary steps to authenticate an user. + * + * @return {@code true} if the user was authenticated properly + */ + boolean authenticate(); + + /** + * Executes the necessary steps to unauthenticate an user. + */ + void unAuthenticate(); + + /** + * Returns the currently authenticated user. + * + * @return the user currently authenticated + */ + User getUser(); +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/AuthorizationException.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/AuthorizationException.java new file mode 100644 index 0000000..a7cef9f --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/AuthorizationException.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 br.gov.frameworkdemoiselle.security; + +import br.gov.frameworkdemoiselle.internal.implementation.CoreBundle; + +/** + * Thrown when 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); + } + + public AuthorizationException(String resource, String operation) { + // TODO: remove the CoreBundle call + super(CoreBundle.get().getString("access-denied-ui", resource, operation)); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/Authorizer.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/Authorizer.java new file mode 100644 index 0000000..aab7712 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/Authorizer.java @@ -0,0 +1,68 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + +/** + * Defines the methods that should be implemented by anyone who wants an authorization mechanism. + * + * @author SERPRO + */ +public interface Authorizer extends Serializable { + + /** + * Checks if the logged user has an specific role + * + * @param role + * role to be checked + * @return {@code true} if the user has the role + */ + boolean hasRole(String role); + + /** + * 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 + */ + boolean hasPermission(String resource, String operation); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/NotLoggedInException.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/NotLoggedInException.java new file mode 100644 index 0000000..cda6c3c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/NotLoggedInException.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +/** + * Thrown when trying to access some resource or execute an operation that requires authentication. + * + * @author SERPRO + */ +public class NotLoggedInException extends SecurityException { + + private static final long serialVersionUID = 1L; + + /** + * Constructs an NotLoggedInException with no detail message. + */ + public NotLoggedInException(String message) { + super(message); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredPermission.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredPermission.java new file mode 100644 index 0000000..c2c1f67 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredPermission.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 br.gov.frameworkdemoiselle.security; + +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.enterprise.util.Nonbinding; +import javax.interceptor.InterceptorBinding; + +/** + * 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/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredRole.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredRole.java new file mode 100644 index 0000000..8de538c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/RequiredRole.java @@ -0,0 +1,64 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +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.enterprise.util.Nonbinding; +import javax.interceptor.InterceptorBinding; + +/** + * 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/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityContext.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityContext.java new file mode 100644 index 0000000..82961a9 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityContext.java @@ -0,0 +1,99 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + + +/** + * Structure used to handle both authentication and authorizations mechanisms. + * + * @author SERPRO + */ +public interface SecurityContext extends Serializable { + + /** + * Executes the login of a user to the application. + */ + void login(); + + /** + * Executes the logout of a user. + * + * @throws NotLoggedInException + * if there is no user logged in a specific session + */ + void logout() throws NotLoggedInException; + + /** + * Checks if a specific user is logged in. + * + * @return {@code true} if the user is logged in + */ + boolean isLoggedIn(); + + /** + * 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 NotLoggedInException + * if there is no user logged in a specific session. + */ + boolean hasPermission(String resource, String operation) throws NotLoggedInException; + + /** + * 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 NotLoggedInException + * if there is no user logged in a specific session. + */ + boolean hasRole(String role) throws NotLoggedInException; + + /** + * Return the user logged in the session. + * + * @return the user logged in a specific session. If there is no active session returns {@code null} + */ + User getUser(); +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityException.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityException.java new file mode 100644 index 0000000..24d3dda --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/SecurityException.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 br.gov.frameworkdemoiselle.security; + +import br.gov.frameworkdemoiselle.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. + */ + public SecurityException(String message) { + super(message); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/security/User.java b/core/src/main/java/br/gov/frameworkdemoiselle/security/User.java new file mode 100644 index 0000000..7525600 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/security/User.java @@ -0,0 +1,73 @@ +/* + * 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 br.gov.frameworkdemoiselle.security; + +import java.io.Serializable; + +/** + * @author SERPRO + * + */ +public interface User extends Serializable { + + /** + * Returns the id of the logged user. + * + * @return the id of the logged user + */ + String getId(); + + /** + * Return the value associated with the key being passed. + * + * @param key + * the key whose value should be searched + * @return the value associated with the key being passed + */ + Object getAttribute(Object key); + + /** + * Sets an attribute. + * + * @param key + * the key that identifies the value + * @param value + * the value to be stored + */ + void setAttribute(Object key, Object value); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/BusinessController.java b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/BusinessController.java new file mode 100644 index 0000000..1afe0b9 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/BusinessController.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 br.gov.frameworkdemoiselle.stereotype; + +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.inject.Stereotype; + +/** + * 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/br/gov/frameworkdemoiselle/stereotype/Controller.java b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/Controller.java new file mode 100644 index 0000000..c53347b --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/Controller.java @@ -0,0 +1,59 @@ +/* + * 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 br.gov.frameworkdemoiselle.stereotype; + +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; + +/** + * 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/br/gov/frameworkdemoiselle/stereotype/FacadeController.java b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/FacadeController.java new file mode 100644 index 0000000..262986b --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/FacadeController.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 br.gov.frameworkdemoiselle.stereotype; + +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.inject.Stereotype; + +/** + * 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 @Facade}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + * @see @Controller + */ +@Controller +@Stereotype +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface FacadeController { +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/PersistenceController.java b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/PersistenceController.java new file mode 100644 index 0000000..41bd2f1 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/PersistenceController.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 br.gov.frameworkdemoiselle.stereotype; + +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.inject.Stereotype; + +/** + * 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/br/gov/frameworkdemoiselle/stereotype/ViewController.java b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/ViewController.java new file mode 100644 index 0000000..32bc92c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/ViewController.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 br.gov.frameworkdemoiselle.stereotype; + +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.inject.Stereotype; +import javax.inject.Named; + +import br.gov.frameworkdemoiselle.annotation.ViewScoped; + +/** + * Identifies a view controller class. A view controller class is intend to respond to events initiated in the + * application front-view. It should have attributes and methods intented to populate the view. + *

+ * A View Controller is: + *

    + *
  • defined when annotated with {@code @ViewController}
  • + *
  • automatically injected whenever {@code @Inject} is used
  • + *
+ * + * @author SERPRO + * @see @Controller + */ +@Named +@Controller +@Stereotype +@ViewScoped +@Inherited +@Target(TYPE) +@Retention(RUNTIME) +public @interface ViewController { +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/template/Crud.java b/core/src/main/java/br/gov/frameworkdemoiselle/template/Crud.java new file mode 100644 index 0000000..f0720ef --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/template/Crud.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.io.Serializable; +import java.util.List; + +public interface Crud extends Serializable { + + void delete(I id); + + List findAll(); + + void insert(T bean); + + T load(I id); + + void update(T bean); + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/template/DelegateCrud.java b/core/src/main/java/br/gov/frameworkdemoiselle/template/DelegateCrud.java new file mode 100644 index 0000000..611087c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/template/DelegateCrud.java @@ -0,0 +1,95 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.util.List; + +import br.gov.frameworkdemoiselle.transaction.Transactional; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Reflections; + +public class DelegateCrud> implements Crud { + + private static final long serialVersionUID = 1L; + + private Class delegateClass; + + private C delegate; + + @Override + @Transactional + public void delete(final I id) { + this.getDelegate().delete(id); + } + + @Override + public List findAll() { + return getDelegate().findAll(); + } + + protected C getDelegate() { + if (this.delegate == null) { + this.delegate = Beans.getReference(getDelegateClass()); + } + return this.delegate; + } + + protected Class getDelegateClass() { + if (this.delegateClass == null) { + this.delegateClass = Reflections.getGenericTypeArgument(this.getClass(), 2); + } + return this.delegateClass; + } + + @Override + @Transactional + public void insert(final T bean) { + getDelegate().insert(bean); + } + + @Override + public T load(final I id) { + return getDelegate().load(id); + } + + @Override + @Transactional + public void update(final T bean) { + getDelegate().update(bean); + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transaction.java b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transaction.java new file mode 100644 index 0000000..6a5bdb9 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transaction.java @@ -0,0 +1,86 @@ +/* + * 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 br.gov.frameworkdemoiselle.transaction; + +import java.io.Serializable; + +/** + * This interface improves UserTransaction by defining additional methods to it, allowing an application to explicitly + * manage transaction boundaries. + * + * @author SERPRO + * @see UserTransaction + */ +public interface Transaction extends Serializable { + + /** + * Indicates whether the given transaction is still active. + * + * @return a boolean + */ + boolean isActive(); + + /** + * Indicates whether the given transaction is already marked to be rolled back. + * + * @return a boolean + */ + boolean isMarkedRollback(); + + /** + * Create a new transaction and associate it with the current thread. + */ + void begin(); + + /** + * Complete the transaction associated with the current thread. When this method completes, the thread is no longer + * associated with a transaction. + */ + void commit(); + + /** + * Roll back the transaction associated with the current thread. When this method completes, the thread is no longer + * associated with a transaction. + */ + void rollback(); + + /** + * Modify the transaction associated with the current thread such that the only possible outcome of the transaction + * is to roll back the transaction. + */ + void setRollbackOnly(); +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/transaction/TransactionException.java b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/TransactionException.java new file mode 100644 index 0000000..7eae075 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/TransactionException.java @@ -0,0 +1,12 @@ +package br.gov.frameworkdemoiselle.transaction; + +import br.gov.frameworkdemoiselle.DemoiselleException; + +public class TransactionException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + public TransactionException(Throwable cause) { + super(cause); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transactional.java b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transactional.java new file mode 100644 index 0000000..d0ef0ff --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/transaction/Transactional.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 br.gov.frameworkdemoiselle.transaction; + +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; + +/** + *

+ * Identifies a method to be transactional, i.e., it will be inspected and a transaction automatically managed + * when it is fired. + *

+ * + * @author SERPRO + */ +@Inherited +@InterceptorBinding +@Target({ METHOD, TYPE }) +@Retention(RUNTIME) +public @interface Transactional { +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/util/Beans.java b/core/src/main/java/br/gov/frameworkdemoiselle/util/Beans.java new file mode 100644 index 0000000..c6fba31 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/util/Beans.java @@ -0,0 +1,90 @@ +/* + * 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. + */ +/* + * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the + * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE + * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is + * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 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 3 as published by the Free Software Foundation. Demoiselle Framework + * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You + * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see + * . + */ +package br.gov.frameworkdemoiselle.util; + +import java.lang.annotation.Annotation; + +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; + +public class Beans { + + private static BeanManager manager; + + public static void setBeanManager(BeanManager beanManager) { + manager = beanManager; + } + + public static BeanManager getBeanManager() { + return manager; + } + + @SuppressWarnings("unchecked") + public static T getReference(final Class beanClass, Annotation... qualifiers) { + Bean bean = manager.getBeans(beanClass, qualifiers).iterator().next(); + return (T) getReference(bean); + } + + @SuppressWarnings("unchecked") + public static T getReference(final Class beanClass) { + Bean bean = manager.getBeans(beanClass).iterator().next(); + return (T) getReference(bean); + } + + @SuppressWarnings("unchecked") + public static T getReference(String beanName) { + Bean bean = manager.getBeans(beanName).iterator().next(); + return (T) getReference(bean); + } + + @SuppressWarnings("unchecked") + private static T getReference(Bean bean) { + return (T) manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean)); + } +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/util/Exceptions.java b/core/src/main/java/br/gov/frameworkdemoiselle/util/Exceptions.java new file mode 100644 index 0000000..518bf3b --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/util/Exceptions.java @@ -0,0 +1,36 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; + +public class Exceptions { + + public static boolean isApplicationException(final Throwable throwable) { + return throwable.getClass().isAnnotationPresent(ApplicationException.class); + } + + 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/br/gov/frameworkdemoiselle/util/Reflections.java b/core/src/main/java/br/gov/frameworkdemoiselle/util/Reflections.java new file mode 100644 index 0000000..421ec71 --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/util/Reflections.java @@ -0,0 +1,143 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class Reflections { + + @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) { + paramType = (ParameterizedType) ((Class) type).getGenericSuperclass(); + } + + return (Class) paramType.getActualTypeArguments()[idx]; + } + + @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]; + } + + 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; + } + + @SuppressWarnings("unchecked") + public static Class getGenericTypeArgument(final Method method, final int pos) { + return (Class) method.getGenericParameterTypes()[pos]; + } + + public static Object getFieldValue(Field field, Object object) { + Object result = null; + + try { + boolean acessible = field.isAccessible(); + field.setAccessible(true); + result = field.get(object); + field.setAccessible(acessible); + + } catch (Exception e) { + Exceptions.handleToRuntimeException(e); + } + + return result; + } + + 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); + } + } + + 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]); + } + + public static T instantiate(Class clasz) { + T object = null; + try { + object = clasz.newInstance(); + } catch (InstantiationException e) { + Exceptions.handleToRuntimeException(e); + } catch (IllegalAccessException e) { + Exceptions.handleToRuntimeException(e); + } + return object; + } + +} diff --git a/core/src/main/java/br/gov/frameworkdemoiselle/util/ResourceBundle.java b/core/src/main/java/br/gov/frameworkdemoiselle/util/ResourceBundle.java new file mode 100644 index 0000000..9e15e7c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/util/ResourceBundle.java @@ -0,0 +1,95 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Set; + +public class ResourceBundle extends java.util.ResourceBundle implements Serializable { + + private static final long serialVersionUID = 1L; + + private transient java.util.ResourceBundle delegate; + + public ResourceBundle(java.util.ResourceBundle resourceBundle) { + this.delegate = resourceBundle; + } + + @Override + public boolean containsKey(String key) { + return delegate.containsKey(key); + } + + @Override + public Enumeration getKeys() { + return delegate.getKeys(); + } + + @Override + public Locale getLocale() { + return delegate.getLocale(); + } + + @Override + public Set keySet() { + return delegate.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 = delegate.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/br/gov/frameworkdemoiselle/util/Strings.java b/core/src/main/java/br/gov/frameworkdemoiselle/util/Strings.java new file mode 100644 index 0000000..c1ba99c --- /dev/null +++ b/core/src/main/java/br/gov/frameworkdemoiselle/util/Strings.java @@ -0,0 +1,162 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import br.gov.frameworkdemoiselle.annotation.Ignore; + +public class Strings { + + public static boolean isResourceBundleKeyFormat(final String key) { + return Pattern.matches("^\\{(.+)\\}$", key == null ? "" : key); + } + + public static String removeChars(String string, char... chars) { + if (string != null) { + for (char ch : chars) { + string = string.replace(String.valueOf(ch), ""); + } + } + return string; + } + + public static String insertZeros(String string, int howMuchZeros) { + StringBuffer result = new StringBuffer((string == null ? "" : string).trim()); + int difference = howMuchZeros - string.length(); + + for (int j = 0; j < difference; j++) { + result.insert(0, '0'); + } + + return result.toString(); + } + + 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; + } + + public static boolean isEmpty(String string) { + return string == null || string.trim().isEmpty(); + } + + 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(); + } + + public static String camelCaseToSymbolSeparated(String string, String symbol) { + if (symbol == null) { + symbol = ""; + } + + return string == null ? null : string.replaceAll("\\B([A-Z])", symbol + "$1").toLowerCase(); + } + + 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; + } + + public static String removeBraces(String string) { + String result = string; + + if (isResourceBundleKeyFormat(string)) { + result = string.substring(1, string.length() - 1); + } + + return result; + } + + public static String insertBraces(String string) { + String result = string; + + if (!isEmpty(string)) { + result = "{" + string + "}"; + } + + return result; + } +} diff --git a/core/src/main/resources/META-INF/beans.xml b/core/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..846a7dc --- /dev/null +++ b/core/src/main/resources/META-INF/beans.xml @@ -0,0 +1,47 @@ + + + + + br.gov.frameworkdemoiselle.internal.interceptor.ExceptionHandlerInterceptor + br.gov.frameworkdemoiselle.internal.interceptor.RequiredPermissionInterceptor + br.gov.frameworkdemoiselle.internal.interceptor.RequiredRoleInterceptor + br.gov.frameworkdemoiselle.internal.interceptor.TransactionalInterceptor + + + \ No newline at end of file diff --git a/core/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/core/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000..ab90f6e --- /dev/null +++ b/core/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1,5 @@ +br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap +br.gov.frameworkdemoiselle.internal.bootstrap.ConfigurationBootstrap + +br.gov.frameworkdemoiselle.internal.bootstrap.StartupBootstrap +br.gov.frameworkdemoiselle.internal.bootstrap.ShutdownBootstrap diff --git a/core/src/main/resources/demoiselle-core-bundle.properties b/core/src/main/resources/demoiselle-core-bundle.properties new file mode 100644 index 0000000..17f5791 --- /dev/null +++ b/core/src/main/resources/demoiselle-core-bundle.properties @@ -0,0 +1,95 @@ +# 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. + +engine-on=Ligando os motores do Demoiselle ${project.version} +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} +proxy-detected=Detectado o proxy {0} da classe {1} +ambiguous-key=Existe mais de uma chave declarada no arquivo de configura\u00E7\u00E3o para o campo {0} da classe {1}. Indique qual a chave correta utilizando a anota\u00E7\u00E3o Name +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} + +loading-configuration-class=Carregando a classe de configura\u00E7\u00E3o {0} +configuration-field-loaded=Configura\u00E7\u00E3o {0} atribu\u00EDda \u00E0 {1} com o valor {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-key-not-found=Chave de configura\u00E7\u00E3o "{0}" n\u00E3o encontrada. Conven\u00E7\u00F5es verificadas\: "{1}" + +transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo beans.xml +executing-all=Executando todos os \: {0} +custom-context-was-registered=O contexto {0} foi registrado +custom-context-was-unregistered=O contexto {0} foi removido + +error-creating-configuration-from-resource=Error creating configuration from resource named "{0}" +configuration-type-not-implemented-yet=Configuration type "{0}" is not implemented yet +error-converting-to-type=Error converting to type "{0}" +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} +transaction-class-not-found=A classe de transa\u00E7\u00E3o "{0}" informada n\u00E3o foi encontrada. +transaction-class-must-be-of-type=A classe de transa\u00E7\u00E3o "{0}" informada deve ser do tipo {1} +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}] +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 + +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +cleaning-message-context=Limpando o contexto de mensagens +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 estrat\u00E9gia de resolu\u00E7\u00E3o de permiss\u00F5es desejada no arquivo beans.xml +user-not-authenticated=Usu\u00E1rio n\u00E3o autenticado +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} +authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir o mecanismo de autentica\u00E7\u00E3o desejado no arquivo beans.xml \ No newline at end of file diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrapTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrapTest.java new file mode 100644 index 0000000..fb04440 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractBootstrapTest.java @@ -0,0 +1,132 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.inject.Scope; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.context.Contexts; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ LoggerProducer.class, Contexts.class }) +public class AbstractBootstrapTest { + + private AbstractBootstrap bootstrap; + + @Before + public void setUp() { + bootstrap = new AbstractBootstrap(); + } + + @SuppressWarnings("unchecked") + @Test + public void testAddContext() { + mockStatic(LoggerProducer.class); + mockStatic(Contexts.class); + + Logger logger = PowerMock.createMock(Logger.class); + logger.trace(EasyMock.anyObject(String.class)); + + expect(LoggerProducer.create(EasyMock.anyObject(Class.class))).andReturn(logger); + + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + expect(bundle.getString(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(null); + + ResourceBundleProducer bundleFactory = PowerMock.createMock(ResourceBundleProducer.class); + expect(bundleFactory.create(EasyMock.anyObject(String.class))).andReturn(bundle); + + Whitebox.setInternalState(AbstractBootstrap.class, "bundleFactory", bundleFactory); + + ThreadLocalContext context = new ThreadLocalContext(Scope.class); + Contexts.add(EasyMock.anyObject(ThreadLocalContext.class), EasyMock.anyObject(AfterBeanDiscovery.class)); + replayAll(bundle, bundleFactory, logger, LoggerProducer.class, Contexts.class); + + bootstrap.addContext(context,null); + + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testDisableContext() { + AbstractBootstrap bootstrap = new AbstractBootstrap(); + + mockStatic(LoggerProducer.class); + mockStatic(Contexts.class); + + Logger logger = PowerMock.createMock(Logger.class); + logger.trace(EasyMock.anyObject(String.class)); + expect(LoggerProducer.create(EasyMock.anyObject(Class.class))).andReturn(logger); + + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + expect(bundle.getString(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(null); + + ResourceBundleProducer bundleFactory = PowerMock.createMock(ResourceBundleProducer.class); + expect(bundleFactory.create(EasyMock.anyObject(String.class))).andReturn(bundle); + + Whitebox.setInternalState(AbstractBootstrap.class, "bundleFactory", bundleFactory); + + ThreadLocalContext context = new ThreadLocalContext(Scope.class); + + Contexts.remove(context); + replayAll(bundle, bundleFactory, logger, LoggerProducer.class, Contexts.class); + + bootstrap.disableContext(context); + + verifyAll(); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrapTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrapTest.java new file mode 100644 index 0000000..32f4c8f --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrapTest.java @@ -0,0 +1,8 @@ +package br.gov.frameworkdemoiselle.internal.bootstrap; + +import org.junit.Ignore; + +@Ignore +public class CoreBootstrapTest { + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/MyStartupAnnotatedClass.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/MyStartupAnnotatedClass.java new file mode 100644 index 0000000..210a1f0 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/MyStartupAnnotatedClass.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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import java.util.Stack; + +import br.gov.frameworkdemoiselle.annotation.Startup; + +public class MyStartupAnnotatedClass { + + public static Stack stackOfMethods = new Stack(); + + @Startup(priority=-1) + public void startMethod1(){ + addMethodExecuted("startMethod1"); + } + + @Startup(priority=1) + public void startMethod2(){ + addMethodExecuted("startMethod2"); + } + + @Startup(priority=0) + public void startMethod3(){ + addMethodExecuted("startMethod3"); + } + + private void addMethodExecuted(String name) { + stackOfMethods.push(name); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrapTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrapTest.java new file mode 100644 index 0000000..7e88a4e --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/ShutdownBootstrapTest.java @@ -0,0 +1,217 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import static junit.framework.Assert.assertNull; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Shutdown; +import br.gov.frameworkdemoiselle.internal.context.Contexts; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.processor.ShutdownProcessor; +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Contexts.class, LoggerProducer.class, ResourceBundle.class, ResourceBundleProducer.class }) +@SuppressWarnings("rawtypes") +public class ShutdownBootstrapTest { + + private ProcessAnnotatedType event; + + private BeanManager beanManager; + + private AnnotatedType annotatedType; + + @Before + public void before() { + event = EasyMock.createMock(ProcessAnnotatedType.class); + annotatedType = EasyMock.createMock(AnnotatedType.class); + beanManager = null; + } + + @SuppressWarnings("unchecked") + private List getProcessors(ShutdownBootstrap bootstrap) throws IllegalArgumentException, + IllegalAccessException { + Set fields = Whitebox.getAllStaticFields(ShutdownBootstrap.class); + List list = new ArrayList(); + for (Field field : fields) { + if (field.getName().equals("processors")) { + list = (List) field.get(bootstrap); + } + } + return list; + } + + @SuppressWarnings({ "unchecked" }) + @Test + public void processAnnotatedType() throws IllegalArgumentException, IllegalAccessException { + ShutdownBootstrap bootstrap = new ShutdownBootstrap(); + List list = getProcessors(bootstrap); + + assertTrue(list.isEmpty()); + + AnnotatedMethod am1 = PowerMock.createMock(AnnotatedMethod.class); + AnnotatedMethod am2 = PowerMock.createMock(AnnotatedMethod.class); + AnnotatedMethod am3 = PowerMock.createMock(AnnotatedMethod.class); + + Set set = new HashSet(); + set.add(am1); + set.add(am2); + set.add(am3); + + expect(am1.isAnnotationPresent(Shutdown.class)).andReturn(true); + expect(am2.isAnnotationPresent(Shutdown.class)).andReturn(true); + expect(am3.isAnnotationPresent(Shutdown.class)).andReturn(false); + expect(event.getAnnotatedType()).andReturn(annotatedType); + expect(annotatedType.getMethods()).andReturn(set); + + replay(event, annotatedType, am1, am2, am3); + bootstrap.processAnnotatedType(event, beanManager); + verify(event, annotatedType); + + list = getProcessors(bootstrap); + assertNotNull(list); + assertFalse(list.isEmpty()); + assertTrue(list.size() == 2); + } + + @SuppressWarnings({ "unchecked" }) + @Test + public void testShuttingDown() throws Throwable { + ShutdownBootstrap bootstrap = new ShutdownBootstrap(); + + PowerMock.mockStatic(Contexts.class); + PowerMock.mockStatic(LoggerProducer.class); + + Logger logger = PowerMock.createMock(Logger.class); + ResourceBundleProducer bundleFactory = PowerMock.createMock(ResourceBundleProducer.class); + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + + expect(LoggerProducer.create(EasyMock.anyObject(Class.class))).andReturn(logger).anyTimes(); + expect(bundleFactory.create(EasyMock.anyObject(String.class))).andReturn(bundle).anyTimes(); + expect(bundle.getString(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn("") + .anyTimes(); + + logger.debug(EasyMock.anyObject(String.class)); + logger.trace(EasyMock.anyObject(String.class)); + EasyMock.expectLastCall().anyTimes(); + + Whitebox.setInternalState(AbstractBootstrap.class, ResourceBundleProducer.class, bundleFactory); + + List list = getProcessors(bootstrap); + list.clear(); + + MyShuttingDownProcessor processor = PowerMock.createMock(MyShuttingDownProcessor.class); + list.add(processor); + expect(processor.process()).andReturn(true).times(1); + + Contexts.add(EasyMock.anyObject(ThreadLocalContext.class), EasyMock.anyObject(AfterBeanDiscovery.class)); + EasyMock.expectLastCall().anyTimes(); + + Contexts.remove(EasyMock.anyObject(ThreadLocalContext.class)); + EasyMock.expectLastCall().anyTimes(); + + PowerMock.replayAll(); + bootstrap.shuttingDown(null); + + assertTrue(list.isEmpty()); + PowerMock.verifyAll(); + } + + @Test + public void testSaveEvent() throws Throwable { + + ShutdownBootstrap bootstrap = new ShutdownBootstrap(); + + AfterBeanDiscovery event = Whitebox.getInternalState(ShutdownBootstrap.class, AfterBeanDiscovery.class); + + assertNull(event); + + AfterBeanDiscovery newEvent = EasyMock.createMock(AfterBeanDiscovery.class); + + EasyMock.replay(newEvent); + + bootstrap.saveEvent(newEvent); + + event = Whitebox.getInternalState(ShutdownBootstrap.class, AfterBeanDiscovery.class); + + assertNotNull(event); + } +} + +@SuppressWarnings("rawtypes") +class MyShuttingDownProcessor extends ShutdownProcessor { + + @SuppressWarnings("unchecked") + public MyShuttingDownProcessor(AnnotatedMethod annotatedMethod, BeanManager beanManager) { + super(annotatedMethod, beanManager); + } + + @Override + public int compareTo(final ShutdownProcessor other) { + return 1; + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrapTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrapTest.java new file mode 100644 index 0000000..48267a3 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/StartupBootstrapTest.java @@ -0,0 +1,256 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.enterprise.context.ConversationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.AnnotatedMethod; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.ProcessAnnotatedType; + +import junit.framework.Assert; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Startup; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.internal.context.Contexts; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.processor.StartupProcessor; +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Contexts.class, LoggerProducer.class, ResourceBundle.class, ResourceBundleProducer.class }) +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class StartupBootstrapTest { + + private ProcessAnnotatedType event; + + private BeanManager beanManager; + + private AnnotatedType annotatedType; + + @Before + public void before() { + event = EasyMock.createMock(ProcessAnnotatedType.class); + annotatedType = EasyMock.createMock(AnnotatedType.class); + beanManager = null; + } + + private List getActions(StartupBootstrap bootstrap) throws IllegalArgumentException, + IllegalAccessException { + Set fields = Whitebox.getAllStaticFields(StartupBootstrap.class); + List list = null; + for (Field field : fields) { + if (field.getName().equals("processors")) { + list = (List) field.get(bootstrap); + } + } + return list; + } + + @Test + public void processAnnotatedType() throws IllegalArgumentException, IllegalAccessException { + StartupBootstrap bootstrap = new StartupBootstrap(); + List list = getActions(bootstrap); + + assertNotNull(list); + assertTrue(list.isEmpty()); + + AnnotatedMethod am1 = PowerMock.createMock(AnnotatedMethod.class); + AnnotatedMethod am2 = PowerMock.createMock(AnnotatedMethod.class); + AnnotatedMethod am3 = PowerMock.createMock(AnnotatedMethod.class); + + Set set = new HashSet(); + set.add(am1); + set.add(am2); + set.add(am3); + + expect(am1.isAnnotationPresent(Startup.class)).andReturn(true); + expect(am2.isAnnotationPresent(Startup.class)).andReturn(true); + expect(am3.isAnnotationPresent(Startup.class)).andReturn(false); + expect(event.getAnnotatedType()).andReturn(annotatedType); + expect(annotatedType.getMethods()).andReturn(set); + + replay(event, annotatedType, am1, am2, am3); + bootstrap.processAnnotatedType(event, beanManager); + verify(event, annotatedType); + + list = getActions(bootstrap); + assertNotNull(list); + assertFalse(list.isEmpty()); + assertTrue(list.size() == 2); + } + + @Test + public void testLoadTempContexts() { + StartupBootstrap bootstrap = new StartupBootstrap(); + + Logger logger = PowerMock.createMock(Logger.class); + ResourceBundleProducer bundleFactory = PowerMock.createMock(ResourceBundleProducer.class); + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + + PowerMock.mockStatic(Contexts.class); + PowerMock.mockStatic(LoggerProducer.class); + + List tempContexts = Whitebox.getInternalState(bootstrap, "tempContexts"); + + assertNotNull(tempContexts); + assertTrue(tempContexts.isEmpty()); + + expect(LoggerProducer.create(EasyMock.anyObject(Class.class))).andReturn(logger).anyTimes(); + expect(bundleFactory.create(EasyMock.anyObject(String.class))).andReturn(bundle).anyTimes(); + expect(bundle.getString(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn("") + .anyTimes(); + + logger.trace(EasyMock.anyObject(String.class)); + EasyMock.expectLastCall().anyTimes(); + + Contexts.add(EasyMock.anyObject(ThreadLocalContext.class), EasyMock.anyObject(AfterBeanDiscovery.class)); + EasyMock.expectLastCall().anyTimes(); + + Whitebox.setInternalState(AbstractBootstrap.class, ResourceBundleProducer.class, bundleFactory); + + PowerMock.replayAll(); + bootstrap.loadTempContexts(null); + PowerMock.verifyAll(); + + assertNotNull(tempContexts); + assertEquals(4, tempContexts.size()); + + for (ThreadLocalContext tlc : tempContexts) { + if (!tlc.getScope().equals(SessionScoped.class) && !tlc.getScope().equals(ConversationScoped.class) + && !tlc.getScope().equals(RequestScoped.class) && !tlc.getScope().equals(ViewScoped.class)) { + fail(); + } + } + } + + @Test + public void testStartup() throws Throwable { + StartupBootstrap bootstrap = new StartupBootstrap(); + + PowerMock.mockStatic(Contexts.class); + PowerMock.mockStatic(LoggerProducer.class); + + Logger logger = PowerMock.createMock(Logger.class); + ResourceBundleProducer bundleFactory = PowerMock.createMock(ResourceBundleProducer.class); + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + + expect(LoggerProducer.create(EasyMock.anyObject(Class.class))).andReturn(logger).anyTimes(); + expect(bundleFactory.create(EasyMock.anyObject(String.class))).andReturn(bundle).anyTimes(); + expect(bundle.getString(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn("") + .anyTimes(); + + logger.debug(EasyMock.anyObject(String.class)); + EasyMock.expectLastCall().anyTimes(); + + Whitebox.setInternalState(AbstractBootstrap.class, ResourceBundleProducer.class, bundleFactory); + + List list = getActions(bootstrap); + list.clear(); + + MyProcessor processor = PowerMock.createMock(MyProcessor.class); + list.add(processor); + expect(processor.process()).andReturn(true).times(1); + + PowerMock.replayAll(); + bootstrap.startup(null); + + assertTrue(list.isEmpty()); + PowerMock.verifyAll(); + } + + @Test + public void testLoadTempContextsAndStartup() { + + StartupBootstrap bootstrap = new StartupBootstrap(); + + bootstrap.loadTempContexts(null); + Assert.assertFalse(Contexts.getActiveContexts().isEmpty()); + + try { + bootstrap.startup(null); + Assert.assertTrue(Contexts.getActiveContexts().isEmpty()); + } catch (Throwable e) { + fail(); + } + + } + +} + +@SuppressWarnings("rawtypes") +class MyProcessor extends StartupProcessor { + + @SuppressWarnings("unchecked") + public MyProcessor(AnnotatedMethod annotatedMethod, BeanManager beanManager) { + super(annotatedMethod, beanManager); + } + + @Override + public int compareTo(final StartupProcessor other) { + return 1; + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassExtendsFromClassThanImplementsTransactionInterface.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassExtendsFromClassThanImplementsTransactionInterface.java new file mode 100644 index 0000000..f615ff2 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassExtendsFromClassThanImplementsTransactionInterface.java @@ -0,0 +1,44 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + + +public class ClassExtendsFromClassThanImplementsTransactionInterface extends ClassImplementsTransactionInterface{ + + private static final long serialVersionUID = 1L; + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassImplementsTransactionInterface.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassImplementsTransactionInterface.java new file mode 100644 index 0000000..9c9182c --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassImplementsTransactionInterface.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 br.gov.frameworkdemoiselle.internal.configuration; + +import br.gov.frameworkdemoiselle.transaction.Transaction; + +public class ClassImplementsTransactionInterface implements Transaction { + + private static final long serialVersionUID = 1L; + + @Override + public void begin() { + // TODO Auto-generated method stub + + } + + @Override + public void commit() { + // TODO Auto-generated method stub + + } + + @Override + public void rollback() { + // TODO Auto-generated method stub + + } + + @Override + public void setRollbackOnly() { + // TODO Auto-generated method stub + + } + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isMarkedRollback() { + // TODO Auto-generated method stub + return false; + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassThanImplementsInterfaceThanExtendsFromTransactionInterface.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassThanImplementsInterfaceThanExtendsFromTransactionInterface.java new file mode 100644 index 0000000..0f1d796 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ClassThanImplementsInterfaceThanExtendsFromTransactionInterface.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 br.gov.frameworkdemoiselle.internal.configuration; + +public class ClassThanImplementsInterfaceThanExtendsFromTransactionInterface implements + InterfaceExtendsFromTransactionInterface { + + private static final long serialVersionUID = 1L; + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isMarkedRollback() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void begin() { + // TODO Auto-generated method stub + + } + + @Override + public void commit() { + // TODO Auto-generated method stub + + } + + @Override + public void rollback() { + // TODO Auto-generated method stub + + } + + @Override + public void setRollbackOnly() { + // TODO Auto-generated method stub + + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoaderTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoaderTest.java new file mode 100644 index 0000000..47dedb9 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoaderTest.java @@ -0,0 +1,644 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; + +import javax.validation.constraints.NotNull; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Ignore; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.ConfigType; +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.configuration.ConfigurationException; +import br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBootstrap.class) +public class ConfigurationLoaderTest { + + private ConfigurationLoader configurationLoader; + + @Configuration + public class ConfigurationSuccessfulProperties { + + @Name("frameworkdemoiselle.configurationtest.nameConfiguration") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationSuccessfulProperties2 { + + @Name("frameworkdemoiselle.configurationtest.name") + protected String name; + + } + + @Configuration(resource = "absentFile") + public class ConfigurationPropertiesWithAbsentFile { + + @Name("frameworkdemoiselle.configurationtest.nameConfiguration") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithEmptyName { + + @Name("") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithoutNameAnnotation { + + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithIgnoreAnnotation { + + @Ignore + protected String nameConfiguration; + + } + + @Configuration(prefix = "frameworkdemoiselle.configurationtest") + public class ConfigurationWithPrefix { + + @Name("nameConfiguration") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithKeyNotFoundInProperties { + + protected Integer notExistKey; + } + + @Configuration + public class ConfigurationWithNotNullFieldButValueIsNull { + + @Name("notexistKey") + @NotNull + protected int nameConfiguration; + + } + + @Configuration + public class ConfigurationWithNotNullFieldAndValueIsNotNull { + + @Name("nameConfiguration") + @NotNull + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithNonPrimitiveFieldValueNull { + + @Name("notexistKey") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationWithPrimitiveFieldValueNull { + + @Name("notexistKey") + protected int nameConfiguration = 1; + + } + + @Configuration(type = ConfigType.SYSTEM) + public class ConfigurationWithKeyFromSystem { + + @Name("os.name") + protected String nameConfiguration; + + } + + @Configuration(type = ConfigType.XML) + public class ConfigurationWithKeyFromXML { + + @Name("nameConfiguration") + protected String nameConfiguration; + + } + + @Configuration(type = ConfigType.XML, prefix = "br.gov.frameworkdemoiselle") + public class ConfigurationFromXMLWithPrefix { + + @Name("nameConfiguration") + protected String nameConfiguration; + + } + + @Configuration + public class ConfigurationPropertiesWithTwoAmbiguousKey { + + protected String twoConfiguration; + + } + + @Configuration + public class ConfigurationPropertiesWithThreeAmbiguousKey { + + protected String threeConfiguration; + + } + + @Configuration + public class ConfigurationPropertiesWithFourAmbiguousKey { + + protected String fourConfiguration; + + } + + @Configuration + public class ConfigurationWithConventionUnderline { + + protected String conventionUnderline; + + } + + @Configuration(type = ConfigType.XML) + public class ConfigurationXMLWithConventionUnderline { + + protected String conventionUnderline; + + } + + @Configuration + public class ConfigurationWithConventionDot { + + protected String conventionDot; + + } + + @Configuration(type = ConfigType.XML) + public class ConfigurationXMLWithConventionDot { + + protected String conventionDot; + + } + + @Configuration + public class ConfigurationWithConventionAllUpperCase { + + protected String conventionAllUpperCase; + + } + + @Configuration(type = ConfigType.XML) + public class ConfigurationXMLWithConventionAllUpperCase { + + protected String conventionAllUpperCase; + + } + + @Configuration + public class ConfigurationWithConventionAllLowerCase { + + protected String conventionAllLowerCase; + + } + + @Configuration(type = ConfigType.XML) + public class ConfigurationXMLWithConventionAllLowerCase { + + protected String conventionAllLowerCase; + + } + + @Configuration(prefix = "br.gov.frameworkdemoiselle") + public class ConfigurationPropertiesSuccessWithPrefixNonAmbiguous { + + protected String success; + + } + + @Configuration + public class ConfigurationPropertiesErrorWithComplexObject { + + protected ConfigurationWithConventionAllLowerCase complexObject; + } + + @Before + public void setUp() throws Exception { + Logger logger; + ResourceBundle bundle; + logger = PowerMock.createMock(Logger.class); + bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + configurationLoader = new ConfigurationLoader(); + Whitebox.setInternalState(this.configurationLoader, "bundle", bundle); + Whitebox.setInternalState(this.configurationLoader, "logger", logger); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConfigurationSuccessfulPropertiesPossibleConventions() { + ConfigurationSuccessfulProperties config = new ConfigurationSuccessfulProperties(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + + } + + @Test + public void testConfigurationSuccessfulPropertiesNoConventions() { + ConfigurationSuccessfulProperties2 config = new ConfigurationSuccessfulProperties2(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest2", config.name); + } + + @Test + public void ConfigurationPropertiesWithAbsentFile() { + ConfigurationPropertiesWithAbsentFile config = new ConfigurationPropertiesWithAbsentFile(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + } + } + + @Test + public void testConfigurationProcessorWithNameEmpty() { + ConfigurationWithEmptyName config = new ConfigurationWithEmptyName(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + } + } + + @Test + public void testConfigurationWithoutNameAnnotation() { + ConfigurationWithoutNameAnnotation config = new ConfigurationWithoutNameAnnotation(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + } + + @Test + public void testConfigurationWithIgnoreAnnotation() { + ConfigurationWithIgnoreAnnotation config = new ConfigurationWithIgnoreAnnotation(); + + configurationLoader.load(config); + assertNull(config.nameConfiguration); + } + + @Test + public void testConfigurationWithPrefix() { + ConfigurationWithPrefix config = new ConfigurationWithPrefix(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + } + + @Test + public void testConfigurationWithKeyNotFoundInProperties() { + ConfigurationWithKeyNotFoundInProperties config = new ConfigurationWithKeyNotFoundInProperties(); + + configurationLoader.load(config); + assertNull(config.notExistKey); + } + + @Test + public void testConfigurationWithNotNullFieldButValueIsNull() { + ConfigurationWithNotNullFieldButValueIsNull config = new ConfigurationWithNotNullFieldButValueIsNull(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + assertTrue(true); + } + } + + @Test + public void testConfigurationWithNotNullFieldAndValueIsNotNull() { + ConfigurationWithNotNullFieldAndValueIsNotNull config = new ConfigurationWithNotNullFieldAndValueIsNotNull(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + } + + @Test + public void testConfigurationWithNonPrimitiveFieldValueNull() { + ConfigurationWithNonPrimitiveFieldValueNull config = new ConfigurationWithNonPrimitiveFieldValueNull(); + + configurationLoader.load(config); + assertNull(config.nameConfiguration); + } + + @Test + public void testConfigurationWithPrimitiveFieldValueNull() { + ConfigurationWithPrimitiveFieldValueNull config = new ConfigurationWithPrimitiveFieldValueNull(); + + configurationLoader.load(config); + assertEquals(1, config.nameConfiguration); + } + + @Test + public void testConfigurationWithKeyFromSystem() { + ConfigurationWithKeyFromSystem config = new ConfigurationWithKeyFromSystem(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals(System.getProperty("os.name"), config.nameConfiguration); + } + + @Test + public void testConfigurationWithKeyFromXML() { + ConfigurationWithKeyFromXML config = new ConfigurationWithKeyFromXML(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + } + + @Test + public void testConfigurationWithTwoAmbiguousKey() { + ConfigurationPropertiesWithTwoAmbiguousKey config = new ConfigurationPropertiesWithTwoAmbiguousKey(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + assertTrue(e instanceof ConfigurationException); + } + + } + + @Test + public void testConfigurationWithThreeAmbiguousKey() { + ConfigurationPropertiesWithThreeAmbiguousKey config = new ConfigurationPropertiesWithThreeAmbiguousKey(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + assertTrue(e instanceof ConfigurationException); + } + + } + + @Test + public void testConfigurationWithFourAmbiguousKey() { + ConfigurationPropertiesWithFourAmbiguousKey config = new ConfigurationPropertiesWithFourAmbiguousKey(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + try { + configurationLoader.load(config); + fail(); + } catch (Exception e) { + assertTrue(e instanceof ConfigurationException); + } + + } + + @Test + public void testConfigurationWithPrefixNotAmbiguous() { + ConfigurationPropertiesSuccessWithPrefixNonAmbiguous config = new ConfigurationPropertiesSuccessWithPrefixNonAmbiguous(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("Success", config.success); + } + + @Test + public void testConfigurationWithConventionUnderline() { + ConfigurationWithConventionUnderline config = new ConfigurationWithConventionUnderline(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("Convention Underline", config.conventionUnderline); + } + + @Test + public void testConfigurationWithConventionDot() { + ConfigurationWithConventionDot config = new ConfigurationWithConventionDot(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("Convention Dot", config.conventionDot); + } + + @Test + public void testConfigurationWithConventionAllLowerCase() { + ConfigurationWithConventionAllLowerCase config = new ConfigurationWithConventionAllLowerCase(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("All LowerCase", config.conventionAllLowerCase); + } + + @Test + public void testConfigurationWithConventionAllUpperCase() { + ConfigurationWithConventionAllUpperCase config = new ConfigurationWithConventionAllUpperCase(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ALL UPPERCASE", config.conventionAllUpperCase); + } + + @Test + public void testConfigurationPropertiesErrorWithComplexObject() { + ConfigurationPropertiesErrorWithComplexObject config = new ConfigurationPropertiesErrorWithComplexObject(); + + try { + configurationLoader.load(config); + fail(); + } catch (Throwable throwable) { + } + } + + @Test + public void testConfigurationFromXMLWithPrefix() { + ConfigurationFromXMLWithPrefix config = new ConfigurationFromXMLWithPrefix(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ConfigurationTest", config.nameConfiguration); + } + + @Test + public void testConfigurationXMLWithConventionDot() { + ConfigurationXMLWithConventionDot config = new ConfigurationXMLWithConventionDot(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("convention.dot", config.conventionDot); + } + + @Test + public void testConfigurationXMLWithConventionUnderline() { + ConfigurationXMLWithConventionUnderline config = new ConfigurationXMLWithConventionUnderline(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("Convention_Underline", config.conventionUnderline); + } + + @Test + public void testConfigurationXMLWithConventionAllUpperCase() { + ConfigurationXMLWithConventionAllUpperCase config = new ConfigurationXMLWithConventionAllUpperCase(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("ALL UPPERCASE", config.conventionAllUpperCase); + } + + @Test + public void testConfigurationXMLWithConventionAllLowerCase() { + ConfigurationXMLWithConventionAllLowerCase config = new ConfigurationXMLWithConventionAllLowerCase(); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + assertEquals("All LowerCase", config.conventionAllLowerCase); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/InterfaceExtendsFromTransactionInterface.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/InterfaceExtendsFromTransactionInterface.java new file mode 100644 index 0000000..e7b1d7f --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/InterfaceExtendsFromTransactionInterface.java @@ -0,0 +1,44 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import br.gov.frameworkdemoiselle.transaction.Transaction; + + +public interface InterfaceExtendsFromTransactionInterface extends Transaction{ + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfigTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfigTest.java new file mode 100644 index 0000000..82ac651 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/PaginationConfigTest.java @@ -0,0 +1,63 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class PaginationConfigTest { + + private PaginationConfig config; + + @Before + public void setUp() throws Exception { + this.config = new PaginationConfig(); + } + + @Test + public void testGetMaxPageLinks() { + assertEquals(5, config.getMaxPageLinks()); + } + + @Test + public void testGetPageSize() { + assertEquals(10, config.getPageSize()); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfigTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfigTest.java new file mode 100644 index 0000000..deb56a1 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/SecurityConfigTest.java @@ -0,0 +1,22 @@ +package br.gov.frameworkdemoiselle.internal.configuration; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class SecurityConfigTest { + + private SecurityConfig config; + + @Before + public void setUp() throws Exception { + this.config = new SecurityConfig(); + } + + @Test + public void testIsEnabled() { + assertEquals(true, config.isEnabled()); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextStoreTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextStoreTest.java new file mode 100644 index 0000000..913a2fd --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextStoreTest.java @@ -0,0 +1,89 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import java.util.Map; +import java.util.TreeMap; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.powermock.api.easymock.PowerMock; +import org.powermock.reflect.Whitebox; + +public class ContextStoreTest { + + private ContextStore store; + + private Map map; + + @SuppressWarnings("unchecked") + @Before + public void setUp() { + store = new ContextStore(); + map = PowerMock.createMock(Map.class); + Whitebox.setInternalState(store, "map", map); + } + + @Test + public void testContains() { + EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(true); + EasyMock.replay(map); + + Assert.assertTrue(store.contains("")); + EasyMock.verify(map); + } + + @Test + public void testGet() { + EasyMock.expect(map.get(EasyMock.anyObject(String.class))).andReturn("testing"); + EasyMock.replay(map); + + Assert.assertEquals("testing", store.get("")); + EasyMock.verify(map); + } + + @Test + public void testPut() { + Map map = new TreeMap(); + Whitebox.setInternalState(store, "map", map); + store.put("testing", map); + Assert.assertTrue(map.containsKey("testing")); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextsTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextsTest.java new file mode 100644 index 0000000..e6de724 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ContextsTest.java @@ -0,0 +1,204 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.spi.AfterBeanDiscovery; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import br.gov.frameworkdemoiselle.annotation.ViewScoped; + +public class ContextsTest { + + private AfterBeanDiscovery event; + + @BeforeClass + public static void setUpClass() throws Exception { + // TODO AfterBeanDiscovery event = ??? mock ??? + } + + @Before + public void setUp() throws Exception { + Contexts.clear(); + } + + @Test + public void testRemovingInexistentContext() { + Contexts.remove(new ThreadLocalContext(SessionScoped.class)); + } + + @Test + public void testRemovingLastInactiveContext() { + ThreadLocalContext context1 = new ThreadLocalContext(RequestScoped.class); + ThreadLocalContext context2 = new ThreadLocalContext(RequestScoped.class); + ThreadLocalContext context3 = new ThreadLocalContext(RequestScoped.class); + + Contexts.add(context1, event); + Contexts.add(context2, event); + Contexts.add(context3, event); + Contexts.remove(context3); + assertFalse(Contexts.getInactiveContexts().contains(context3)); + } + + @Test + public void testRemovingActiveContextAndActivatingInactiveContext() { + ThreadLocalContext context1 = new ThreadLocalContext(SessionScoped.class); + ThreadLocalContext context2 = new ThreadLocalContext(SessionScoped.class); + ThreadLocalContext context3 = new ThreadLocalContext(SessionScoped.class); + + Contexts.add(context1, event); + Contexts.add(context2, event); + Contexts.add(context3, event); + assertTrue(context1.isActive()); + assertFalse(context2.isActive()); + assertFalse(context3.isActive()); + + Contexts.remove(context1); + assertTrue(context2.isActive()); + assertFalse(context3.isActive()); + + Contexts.remove(context2); + assertTrue(context3.isActive()); + } + + @Test + public void testRemovingActiveContext() { + ThreadLocalContext context = new ThreadLocalContext(SessionScoped.class); + + Contexts.add(context, event); + Contexts.remove(context); + assertEquals(0, Contexts.getActiveContexts().size()); + } + + @Test + public void testRemovingInactiveContext() { + ThreadLocalContext context = new ThreadLocalContext(SessionScoped.class); + + Contexts.add(new ThreadLocalContext(SessionScoped.class), event); + Contexts.add(context, event); + Contexts.remove(context); + assertEquals(0, Contexts.getInactiveContexts().size()); + } + + @Test + public void testClear() { + List list = new ArrayList(); + + list.add(new ThreadLocalContext(SessionScoped.class)); + list.add(new ThreadLocalContext(SessionScoped.class)); + list.add(new ThreadLocalContext(ApplicationScoped.class)); + + for (ThreadLocalContext context : list) { + Contexts.add(context, event); + } + + Contexts.clear(); + assertEquals(0, Contexts.getActiveContexts().size()); + assertEquals(0, Contexts.getInactiveContexts().size()); + + for (ThreadLocalContext context : list) { + assertFalse(context.isActive()); + } + } + + @Test + public void testAdd() { + Contexts.add(new ThreadLocalContext(SessionScoped.class), event); + assertEquals(1, Contexts.getActiveContexts().size()); + } + + @Test + public void testAddingRepeatedScopeType() { + Contexts.add(new ThreadLocalContext(SessionScoped.class), event); + assertEquals(1, Contexts.getActiveContexts().size()); + assertEquals(0, Contexts.getInactiveContexts().size()); + + Contexts.add(new ThreadLocalContext(SessionScoped.class), event); + assertEquals(1, Contexts.getActiveContexts().size()); + assertEquals(1, Contexts.getInactiveContexts().size()); + } + + @Test + public void testAddingRepeatedScopeInstance() { + ThreadLocalContext context1 = new ThreadLocalContext(SessionScoped.class); + ThreadLocalContext context2 = new ThreadLocalContext(SessionScoped.class); + + Contexts.add(context1, event); + Contexts.add(context2, event); + + assertTrue(context1.isActive()); + assertFalse(context2.isActive()); + + assertEquals(1, Contexts.getActiveContexts().size()); + assertEquals(1, Contexts.getInactiveContexts().size()); + } + + @Test + public void testIsActive() { + ThreadLocalContext context = new ThreadLocalContext(SessionScoped.class); + + Contexts.add(context, event); + assertTrue(context.isActive()); + } + + @Test + public void testIsInactive() { + ThreadLocalContext context = new ThreadLocalContext(ViewScoped.class); + + Contexts.add(new ThreadLocalContext(ViewScoped.class), event); + Contexts.add(context, event); + assertFalse(context.isActive()); + } + + @Test + public void testAddWithEventNotNull() { + event = createMock(AfterBeanDiscovery.class); + ThreadLocalContext context = new ThreadLocalContext(SessionScoped.class); + event.addContext(context); + expectLastCall(); + replay(event); + + Contexts.add(context, event); + assertEquals(1, Contexts.getActiveContexts().size()); + } + + // Only to get 100% on coverage report + @Test + public void testCreateNew() { + Contexts context = new Contexts(); + Assert.assertNotNull(context); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContextTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContextTest.java new file mode 100644 index 0000000..21220e6 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContextTest.java @@ -0,0 +1,231 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.fail; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Set; + +import javax.enterprise.context.ContextNotActiveException; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.inject.Scope; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Bean.class }) +public class ThreadLocalContextTest { + + private ThreadLocalContext context; + + @Before + public void before() { + context = new ThreadLocalContext(Scope.class); + } + + @Test + public void testContextNotActive() { + try { + context.setActive(false); + context.get(null); + fail(); + } catch (ContextNotActiveException exception) { + } + } + + @SuppressWarnings({ "unchecked" }) + @Test + public void testStoreContainsInstance() { + String instance = "instance"; + + ContextStore store = PowerMock.createMock(ContextStore.class); + expect(store.get(EasyMock.anyObject(String.class))).andReturn(instance); + expect(store.contains(EasyMock.anyObject(String.class))).andReturn(true); + + ThreadLocal threadLocal = PowerMock.createMock(ThreadLocal.class); + expect(threadLocal.get()).andReturn(store).times(4); + + Whitebox.setInternalState(context, "threadLocal", threadLocal); + + Bean contextual = new MyBean(); + PowerMock.replayAll(threadLocal, store); + + context.setActive(true); + Assert.assertEquals(instance, context.get(contextual)); + } + + @SuppressWarnings("unchecked") + @Test + public void testStoreDoesNotContainsInstance() { + String instance = "instance"; + + ContextStore store = PowerMock.createMock(ContextStore.class); + expect(store.get(EasyMock.anyObject(String.class))).andReturn(instance); + expect(store.contains(EasyMock.anyObject(String.class))).andReturn(false).times(1); + + ThreadLocal threadLocal = PowerMock.createMock(ThreadLocal.class); + expect(threadLocal.get()).andReturn(store).times(8); + + Whitebox.setInternalState(context, "threadLocal", threadLocal); + + Bean contextual = new MyBean(); + + CreationalContext creationalContext = PowerMock.createMock(CreationalContext.class); + store.put("java.lang.String", instance); + + PowerMock.replayAll(threadLocal, store); + + context.setActive(true); + Assert.assertEquals(instance, context.get(contextual, creationalContext)); + } + + @Test + public void testStoreDoesNotContainsInstanceAndCreationalContextIsNull() { + String instance = "instance"; + + ContextStore store = PowerMock.createMock(ContextStore.class); + expect(store.get(EasyMock.anyObject(String.class))).andReturn(instance); + expect(store.contains(EasyMock.anyObject(String.class))).andReturn(false); + + @SuppressWarnings("unchecked") + ThreadLocal threadLocal = PowerMock.createMock(ThreadLocal.class); + expect(threadLocal.get()).andReturn(store).times(4); + + Whitebox.setInternalState(context, "threadLocal", threadLocal); + + Bean contextual = new MyBean(); + PowerMock.replayAll(threadLocal, store); + + context.setActive(true); + Assert.assertNull(context.get(contextual)); + } + + @Test + public void testContextStoreIsNull() { + String instance = "instance"; + + @SuppressWarnings("unchecked") + ThreadLocal threadLocal = PowerMock.createMock(ThreadLocal.class); + expect(threadLocal.get()).andReturn(null); + threadLocal.set(EasyMock.anyObject(ContextStore.class)); + PowerMock.expectLastCall(); + + ContextStore store = PowerMock.createMock(ContextStore.class); + expect(store.get(EasyMock.anyObject(String.class))).andReturn(instance); + expect(threadLocal.get()).andReturn(store).times(4); + expect(store.contains(EasyMock.anyObject(String.class))).andReturn(true); + + Whitebox.setInternalState(context, "threadLocal", threadLocal); + + Bean contextual = new MyBean(); + PowerMock.replayAll(threadLocal, store); + + context.setActive(true); + Assert.assertEquals(instance, context.get(contextual)); + } + + class MyBean implements Bean { + + @Override + public String create(CreationalContext creationalContext) { + return "instance"; + } + + @Override + public void destroy(String instance, CreationalContext creationalContext) { + } + + @Override + public Set getTypes() { + return null; + } + + @Override + public Set getQualifiers() { + return null; + } + + @Override + public Class getScope() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public Set> getStereotypes() { + return null; + } + + @Override + public Class getBeanClass() { + return String.class; + } + + @Override + public boolean isAlternative() { + return false; + } + + @Override + public boolean isNullable() { + return false; + } + + @Override + public Set getInjectionPoints() { + return null; + } + + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticatorTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticatorTest.java new file mode 100644 index 0000000..50733c3 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthenticatorTest.java @@ -0,0 +1,72 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * @author SERPRO + * @see DefaultAuthenticator + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBundle.class) +public class DefaultAuthenticatorTest { + + private DefaultAuthenticator authenticator; + + @Before + public void setUp() throws Exception { + authenticator = new DefaultAuthenticator(); + + mockStatic(CoreBundle.class); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + expect(CoreBundle.get()).andReturn(bundle); + + replay(CoreBundle.class); + } + + @After + public void tearDown() { + authenticator = null; + } + + @Test + public void testAuthenticate() { + try { + authenticator.authenticate(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testUnAuthenticate() { + try { + authenticator.unAuthenticate(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testGetUser() { + try { + authenticator.getUser(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizerTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizerTest.java new file mode 100644 index 0000000..6177ff8 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultAuthorizerTest.java @@ -0,0 +1,63 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * @author SERPRO + * @see DefaultAuthorizer + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBundle.class) +public class DefaultAuthorizerTest { + + private DefaultAuthorizer authorizer; + + @Before + public void setUp() throws Exception { + authorizer = new DefaultAuthorizer(); + + mockStatic(CoreBundle.class); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + expect(CoreBundle.get()).andReturn(bundle); + + replay(CoreBundle.class); + } + + @After + public void tearDown() { + authorizer = null; + } + + @Test + public void testHasRole() { + try { + authorizer.hasRole(null); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testHasPermission() { + try { + authorizer.hasPermission(null, null); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransactionTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransactionTest.java new file mode 100644 index 0000000..30dcda2 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/DefaultTransactionTest.java @@ -0,0 +1,134 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * @author SERPRO + * @see DefaultTransaction + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBundle.class) +public class DefaultTransactionTest { + + private DefaultTransaction tx; + + @Before + public void setUp() throws Exception { + tx = new DefaultTransaction(); + + mockStatic(CoreBundle.class); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + expect(CoreBundle.get()).andReturn(bundle); + + replay(CoreBundle.class); + } + + @After + public void tearDown() { + tx = null; + } + + @Test + public void testBegin() { + try { + tx.begin(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testCommit() { + try { + tx.commit(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testIsActive() { + try { + tx.isActive(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testIsMarkedRollback() { + try { + tx.isMarkedRollback(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testRollback() { + try { + tx.rollback(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testSetRollbackOnly() { + try { + tx.setRollbackOnly(); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImplTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImplTest.java new file mode 100644 index 0000000..fda3ff6 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessageContextImplTest.java @@ -0,0 +1,229 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; +// +//import java.util.Locale; +// +//import junit.framework.Assert; +// +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.powermock.api.easymock.PowerMock; +//import org.powermock.modules.junit4.PowerMockRunner; +//import org.powermock.reflect.Whitebox; +//import org.slf4j.Logger; +// +//import br.gov.frameworkdemoiselle.message.Message; +//import br.gov.frameworkdemoiselle.message.MessageContext; +//import br.gov.frameworkdemoiselle.message.SeverityType; +//import br.gov.frameworkdemoiselle.util.ResourceBundle; +// +//@RunWith(PowerMockRunner.class) +//public class MessageContextImplTest { +// +// MessageContext messageContext; +// +// Message m1; +// +// @SuppressWarnings("unused") +// @Before +// public void before() { +// messageContext = new MessageContextImpl(); +// +// Logger logger = PowerMock.createMock(Logger.class); +// ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); +// +// Whitebox.setInternalState(messageContext, "logger", logger); +// Whitebox.setInternalState(messageContext, "bundle", bundle); +// +// m1 = new Message() { +// +// private String key = "m1.message"; +// +// private String resourceName = "messages"; +// +// private Locale locale = Locale.getDefault(); +// +// private SeverityType severityType = SeverityType.INFO; +// +// private Object[] parameters = {}; +// +// public String getText() { +// return key; +// } +// +// public void setKey(String key) { +// this.key = key; +// } +// +// public String getResourceName() { +// return resourceName; +// } +// +// public void setResourceName(String resourceName) { +// this.resourceName = resourceName; +// } +// +// public Locale getLocale() { +// return locale; +// } +// +// public void setLocale(Locale locale) { +// this.locale = locale; +// } +// +// public SeverityType getSeverity() { +// return severityType; +// } +// +// public void setSeverityType(SeverityType severityType) { +// this.severityType = severityType; +// } +// +// public Object[] getParameters() { +// return parameters; +// } +// +// public Message setParameters(Object[] parameters) { +// this.parameters = parameters; +// return this; +// } +// +// public String getStringMessage() { +// return "stringMessage"; +// } +// }; +// } +// +// @Test +// public void testAddMessage() { +// messageContext.add(m1); +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().contains(m1)); +// +// } +// +// @Test +// public void testAddMessageObjectArray() { +// Object[] param = { "1", "2" }; +// messageContext.add(m1, param); +// +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().contains(m1)); +// Assert.assertNotNull(messageContext.getMessages().get(0).getParameters()); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[0] == param[0]); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[1] == param[1]); +// +// } +// +// @Test +// public void testAddStringObjectArray() { +// String key = "my.key"; +// Object[] param = { "1", "2" }; +// messageContext.add(key, param); +// +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().get(0).getText().equals(key)); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[0] == param[0]); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[1] == param[1]); +// } +// +// @Test +// public void testAddStringLocaleObjectArray() { +// String key = "my.key"; +// Object[] param = { "1", "2" }; +// Locale locale = Locale.CANADA_FRENCH; +// messageContext.add(key, locale, param); +// +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().get(0).getText().equals(key)); +// Assert.assertTrue(messageContext.getMessages().get(0).getLocale().equals(locale)); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[0] == param[0]); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[1] == param[1]); +// } +// +// @Test +// public void testAddStringLocaleSeverityTypeObjectArray() { +// String key = "my.key"; +// Object[] param = { "1", "2" }; +// Locale locale = Locale.CANADA_FRENCH; +// SeverityType severity = SeverityType.ERROR; +// messageContext.add(key, locale, severity, param); +// +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().get(0).getText().equals(key)); +// Assert.assertTrue(messageContext.getMessages().get(0).getLocale().equals(locale)); +// Assert.assertTrue(messageContext.getMessages().get(0).getSeverity().equals(severity)); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[0] == param[0]); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[1] == param[1]); +// } +// +// @Test +// public void testAddStringLocaleSeverityTypeStringObjectArray() { +// String key = "my.key"; +// Object[] param = { "1", "2" }; +// Locale locale = Locale.CANADA_FRENCH; +// SeverityType severity = SeverityType.ERROR; +// String resource = "myresourcename"; +// messageContext.add(key, locale, severity, resource, param); +// +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// Assert.assertTrue(messageContext.getMessages().get(0).getText().equals(key)); +// Assert.assertTrue(messageContext.getMessages().get(0).getLocale().equals(locale)); +// Assert.assertTrue(messageContext.getMessages().get(0).getSeverity().equals(severity)); +// Assert.assertTrue(messageContext.getMessages().get(0).getResourceName().equals(resource)); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[0] == param[0]); +// Assert.assertTrue(messageContext.getMessages().get(0).getParameters()[1] == param[1]); +// } +// +// @Test +// public void testGetMessages() { +// Assert.assertNotNull(messageContext.getMessages()); +// Assert.assertTrue(messageContext.getMessages().isEmpty()); +// +// messageContext.add("key1"); +// Assert.assertTrue(messageContext.getMessages().size() == 1); +// +// messageContext.add("key2"); +// Assert.assertTrue(messageContext.getMessages().size() == 2); +// +// Assert.assertTrue(messageContext.getMessages().get(0).getText().equals("key1")); +// Assert.assertTrue(messageContext.getMessages().get(1).getText().equals("key2")); +// } +// +//} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImplTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImplTest.java new file mode 100644 index 0000000..2d53ab4 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationContextImplTest.java @@ -0,0 +1,108 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashMap; +import java.util.Map; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.internal.configuration.PaginationConfig; +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; + +@RunWith(PowerMockRunner.class) +public class PaginationContextImplTest { + + private PaginationContext context; + + private Pagination pagination; + + @Before + public void setUp() { + context = new PaginationContextImpl(); + + PaginationConfig config = PowerMock.createMock(PaginationConfig.class); + EasyMock.expect(config.getPageSize()).andReturn(10).anyTimes(); + EasyMock.replay(config); + + Whitebox.setInternalState(context, "config", config); + Whitebox.setInternalState(context, "cache", getInitialMap()); + } + + @After + public void tearDown() { + context = null; + } + + private Map, Pagination> getInitialMap() { + Map, Pagination> map = new HashMap, Pagination>(); + pagination = new PaginationImpl(); + map.put(getClass(), pagination); + + return map; + } + + @Test + public void testGetPaginationWithoutCreateParameter() { + assertEquals(pagination, context.getPagination(getClass())); + assertNull(context.getPagination(Object.class)); + } + + @Test + public void testGetPaginationWithCreateParameterTrueValued() { + assertEquals(pagination, context.getPagination(getClass(), true)); + assertNotNull(context.getPagination(Object.class, true)); + } + + @Test + public void testGetPaginationWithCreateParameterFalseValued() { + assertEquals(pagination, context.getPagination(getClass(), false)); + assertNull(context.getPagination(Object.class, false)); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImplTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImplTest.java new file mode 100644 index 0000000..bdfbaa9 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/PaginationImplTest.java @@ -0,0 +1,321 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.util.Strings; + +/** + * @author SERPRO + */ +public class PaginationImplTest { + + private Pagination pagination; + + @Before + public void setUp() { + pagination = new PaginationImpl(); + } + + @After + public void tearDown() { + pagination = null; + } + + @Test + public void testConstructor() { + assertEquals(0, pagination.getCurrentPage()); + assertEquals(0, pagination.getTotalResults()); + assertEquals(0, pagination.getTotalPages()); + assertEquals(0, pagination.getFirstResult()); + } + + @Test + public void testCurrentPageProperty() { + pagination.setCurrentPage(0); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setCurrentPage(1); + assertEquals(1, pagination.getCurrentPage()); + } + + @Test + public void testPageSizeProperty() { + pagination.setPageSize(0); + assertEquals(0, pagination.getPageSize()); + + pagination.setPageSize(1); + assertEquals(1, pagination.getPageSize()); + } + + @Test + public void testTotalResultsProperty() { + pagination.setTotalResults(0); + assertEquals(0, pagination.getTotalResults()); + + pagination.setTotalResults(1); + assertEquals(1, pagination.getTotalResults()); + } + + @Test + public void testTotalPagesWhenTotalResultsChanges() { + pagination.setPageSize(10); + + pagination.setTotalResults(0); + assertEquals(0, pagination.getTotalPages()); + + pagination.setTotalResults(9); + assertEquals(1, pagination.getTotalPages()); + + pagination.setTotalResults(10); + assertEquals(1, pagination.getTotalPages()); + + pagination.setTotalResults(11); + assertEquals(2, pagination.getTotalPages()); + } + + @Test + public void testIndexOutOfBoundsException() { + try { + pagination.setCurrentPage(-1); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setFirstResult(-1); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setPageSize(-1); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setTotalResults(-1); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setTotalResults(1); + pagination.setFirstResult(1); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setTotalResults(1); + pagination.setFirstResult(2); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setPageSize(2); + pagination.setTotalResults(3); + pagination.setCurrentPage(2); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setPageSize(2); + pagination.setTotalResults(3); + pagination.setCurrentPage(3); + fail(); + } catch (IndexOutOfBoundsException cause) { + } + + try { + pagination.setTotalResults(0); + pagination.setFirstResult(0); + } catch (IndexOutOfBoundsException cause) { + fail(); + } + } + + @Test + public void testTotalPagesWhenPageSizeChanges() { + pagination.setTotalResults(10); + + pagination.setPageSize(0); + assertEquals(0, pagination.getTotalPages()); + + pagination.setPageSize(9); + assertEquals(2, pagination.getTotalPages()); + + pagination.setPageSize(10); + assertEquals(1, pagination.getTotalPages()); + + pagination.setPageSize(11); + assertEquals(1, pagination.getTotalPages()); + } + + @Test + public void testCurrentPageWhenPageSizeChanges() { + pagination.setTotalResults(10); + + pagination.setPageSize(5); + pagination.setCurrentPage(1); + pagination.setPageSize(0); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setPageSize(5); + pagination.setCurrentPage(1); + pagination.setPageSize(9); + assertEquals(1, pagination.getCurrentPage()); + + pagination.setPageSize(5); + pagination.setCurrentPage(1); + pagination.setPageSize(10); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setPageSize(5); + pagination.setCurrentPage(0); + pagination.setPageSize(11); + assertEquals(0, pagination.getCurrentPage()); + } + + @Test + public void testCurrentPageWhenTotalResultsChanges() { + pagination.setPageSize(10); + + pagination.setTotalResults(11); + pagination.setCurrentPage(1); + pagination.setTotalResults(0); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setTotalResults(11); + pagination.setCurrentPage(1); + pagination.setTotalResults(9); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setTotalResults(11); + pagination.setCurrentPage(1); + pagination.setTotalResults(10); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setTotalResults(12); + pagination.setCurrentPage(1); + pagination.setTotalResults(11); + assertEquals(1, pagination.getCurrentPage()); + } + + @Test + public void testCurrentPageWhenFirstResultChanges() { + pagination.setPageSize(10); + pagination.setTotalResults(100); + + pagination.setFirstResult(0); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setFirstResult(1); + assertEquals(0, pagination.getCurrentPage()); + + pagination.setFirstResult(98); + assertEquals(9, pagination.getCurrentPage()); + + pagination.setFirstResult(99); + assertEquals(9, pagination.getCurrentPage()); + } + + @Test + public void testFirstResultWhenPageSizeChanges() { + pagination.setTotalResults(10); + + pagination.setPageSize(10); + pagination.setFirstResult(5); + pagination.setPageSize(0); + assertEquals(0, pagination.getFirstResult()); + + pagination.setPageSize(10); + pagination.setFirstResult(9); + pagination.setPageSize(1); + assertEquals(0, pagination.getFirstResult()); + } + + @Test + public void testFirstResultWhenTotalResultsChanges() { + pagination.setPageSize(10); + + pagination.setTotalResults(50); + pagination.setFirstResult(49); + pagination.setTotalResults(0); + assertEquals(0, pagination.getFirstResult()); + + pagination.setTotalResults(50); + pagination.setFirstResult(49); + pagination.setTotalResults(1); + assertEquals(0, pagination.getFirstResult()); + + pagination.setTotalResults(50); + pagination.setFirstResult(49); + pagination.setTotalResults(49); + assertEquals(40, pagination.getFirstResult()); + } + + @Test + public void testFirstResultWhenCurrentPageChanges() { + pagination.setPageSize(10); + pagination.setTotalResults(100); + + pagination.setCurrentPage(0); + assertEquals(0, pagination.getFirstResult()); + + pagination.setCurrentPage(1); + assertEquals(10, pagination.getFirstResult()); + + pagination.setCurrentPage(9); + assertEquals(90, pagination.getFirstResult()); + } + + @Test + public void testToStringFormat() { + assertEquals(Strings.toString(pagination), pagination.toString()); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImplTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImplTest.java new file mode 100644 index 0000000..a44baa4 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityContextImplTest.java @@ -0,0 +1,354 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.reflect.Whitebox.setInternalState; + +import javax.enterprise.inject.spi.BeanManager; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.internal.configuration.SecurityConfig; +import br.gov.frameworkdemoiselle.security.Authenticator; +import br.gov.frameworkdemoiselle.security.Authorizer; +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.security.User; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ CoreBundle.class, Beans.class }) +public class SecurityContextImplTest { + + private SecurityContextImpl context; + + private SecurityConfig config; + + @Before + public void setUp() { + context = new SecurityContextImpl(); + + config = createMock(SecurityConfig.class); + setInternalState(context, "config", config); + } + + @Test + public void testHasPermissionWithSecurityDisabled() { + + expect(config.isEnabled()).andReturn(false); + + replay(config); + + try { + assertTrue(context.hasPermission(null, null)); + } catch (NotLoggedInException e) { + fail(); + } + + } + + @Test + public void testHasPermissionWithSecurityEnabledAndNotLoggedIn() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + setInternalState(context, "bundle", bundle); + setInternalState(context, "authenticator", authenticator); + + expect(config.isEnabled()).andReturn(true).anyTimes(); + replay(config, authenticator); + + try { + context.hasPermission(null, null); + fail(); + } catch (NotLoggedInException e) { + assertTrue(e.getMessage().equals(bundle.getString("user-not-authenticated"))); + } + + } + + @Test + public void testHasPermissionWithSecurityEnabledAndLoggedIn() { + expect(config.isEnabled()).andReturn(true).anyTimes(); + replay(config); + + loginSuccessfully(); + + Authorizer authorizer = createMock(Authorizer.class); + expect(authorizer.hasPermission(null, null)).andReturn(true); + + setInternalState(context, "authorizer", authorizer); + + replay(authorizer); + + try { + assertTrue(context.hasPermission(null, null)); + } catch (NotLoggedInException e) { + fail(); + } + + } + + private void loginSuccessfully() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.authenticate()).andReturn(true); + + BeanManager manager = createMock(BeanManager.class); + mockStatic(Beans.class); + expect(Beans.getBeanManager()).andReturn(manager); + manager.fireEvent(EasyMock.anyObject(Class.class)); + PowerMock.expectLastCall(); + + User user = createMock(User.class); + expect(authenticator.getUser()).andReturn(user).anyTimes(); + + setInternalState(context, "authenticator", authenticator); + + replayAll(authenticator, user, Beans.class, manager); + + context.login(); + assertTrue(context.isLoggedIn()); + } + + @Test + public void testHasRoleWithSecurityDisabled() { + + expect(config.isEnabled()).andReturn(false); + + replay(config); + + try { + assertTrue(context.hasRole(null)); + } catch (NotLoggedInException e) { + fail(); + } + + } + + @Test + public void testHasRoleWithSecurityEnabledAndNotLoggedIn() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + setInternalState(context, "bundle", bundle); + expect(config.isEnabled()).andReturn(true).anyTimes(); + + setInternalState(context, "authenticator", authenticator); + + replay(config, authenticator); + + try { + context.hasRole(null); + fail(); + } catch (NotLoggedInException e) { + assertTrue(e.getMessage().equals(bundle.getString("user-not-authenticated"))); + } + + } + + @Test + public void testHasRoleWithSecurityEnabledAndLoggedIn() { + expect(config.isEnabled()).andReturn(true).anyTimes(); + replay(config); + + loginSuccessfully(); + + Authorizer authorizer = createMock(Authorizer.class); + expect(authorizer.hasRole(null)).andReturn(true); + + setInternalState(context, "authorizer", authorizer); + + replay(authorizer); + + try { + assertTrue(context.hasRole(null)); + } catch (NotLoggedInException e) { + fail(); + } + + } + + @Test + public void testIsLoggedInWithSecurityEnabled() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + expect(config.isEnabled()).andReturn(true).anyTimes(); + + setInternalState(context, "authenticator", authenticator); + + replay(config, authenticator); + + assertFalse(context.isLoggedIn()); + } + + @Test + public void testIsLoggedInWithSecurityDisabled() { + + expect(config.isEnabled()).andReturn(false); + + replay(config); + + assertTrue(context.isLoggedIn()); + + } + + @Test + public void testLoginWithSecurityDisabled() { + + expect(config.isEnabled()).andReturn(false).times(2); + + replay(config); + + context.login(); + + assertTrue(context.isLoggedIn()); + + } + + @Test + public void testLoginWithAuthenticationFail() { + + expect(config.isEnabled()).andReturn(true).anyTimes(); + + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.authenticate()).andReturn(false); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + setInternalState(context, "authenticator", authenticator); + + replayAll(authenticator, config); + + context.login(); + + assertFalse(context.isLoggedIn()); + } + + @Test + public void testLogOutWithSecurityDisabled() { + + expect(config.isEnabled()).andReturn(false).times(2); + + replay(config); + + try { + context.logout(); + assertTrue(context.isLoggedIn()); + } catch (NotLoggedInException e) { + fail(); + } + } + + @Test + public void testLogOutWithoutPreviousLogin() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + setInternalState(context, "bundle", bundle); + + expect(config.isEnabled()).andReturn(true).anyTimes(); + + setInternalState(context, "authenticator", authenticator); + + replay(config, authenticator); + + try { + context.logout(); + fail(); + } catch (NotLoggedInException e) { + assertTrue(e.getMessage().equals(bundle.getString("user-not-authenticated"))); + } + } + + @Test + public void testLogOutAfterSuccessfulLogin() { + mockStatic(Beans.class); + + expect(config.isEnabled()).andReturn(true).anyTimes(); + + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.authenticate()).andReturn(true); + authenticator.unAuthenticate(); + PowerMock.expectLastCall(); + + User user = createMock(User.class); + expect(authenticator.getUser()).andReturn(user); + expect(authenticator.getUser()).andReturn(null); + + BeanManager manager = createMock(BeanManager.class); + expect(Beans.getBeanManager()).andReturn(manager).times(2); + manager.fireEvent(EasyMock.anyObject(Class.class)); + PowerMock.expectLastCall().times(2); + + setInternalState(context, "authenticator", authenticator); + + replayAll(Beans.class, authenticator, user, manager, config); + + context.login(); + context.logout(); + + assertFalse(context.isLoggedIn()); + } + + @Test + public void testGetUserWhenSecurityIsDisabled() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + expect(config.isEnabled()).andReturn(false).anyTimes(); + replay(config, authenticator, Beans.class); + + setInternalState(context, "authenticator", authenticator); + + assertNotNull(context.getUser()); + assertNotNull(context.getUser().getId()); + assertNull(context.getUser().getAttribute(null)); + context.getUser().setAttribute(null, null); + } + + @Test + public void testGetUserWhenSecurityIsEnabled() { + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(null).anyTimes(); + + expect(config.isEnabled()).andReturn(true); + replay(config, authenticator, Beans.class); + + setInternalState(context, "authenticator", authenticator); + + assertNull(context.getUser()); + } + + @Test + public void testGetUserWhenSecurityIsEnabledAndUserIsNotNull() { + User user = createMock(User.class); + + Authenticator authenticator = createMock(Authenticator.class); + expect(authenticator.getUser()).andReturn(user).anyTimes(); + + expect(config.isEnabled()).andReturn(true).anyTimes(); + replay(config, user, authenticator, Beans.class); + + setInternalState(context, "authenticator", authenticator); + + assertEquals(context.getUser(), user); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptorTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptorTest.java new file mode 100644 index 0000000..f2fca4c --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/ExceptionHandlerInterceptorTest.java @@ -0,0 +1,290 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.interceptor.InvocationContext; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.exception.ExceptionHandler; +import br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBootstrap.class) +public class ExceptionHandlerInterceptorTest { + + private ExceptionHandlerInterceptor interceptor; + + private InvocationContext context; + + private Logger logger; + + private ResourceBundle bundle; + + class TesteException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + public TesteException(String message) { + super(message); + } + } + + class ClassWithMethodsAnnotatedWithExceptionHandler { + + int times = 0; + + @ExceptionHandler + public void methodWithExceptionHandlerAnotation(DemoiselleException cause) { + times++; + } + + @ExceptionHandler + public void methodWithExceptionHandlerAnotationAndGenericException(Exception cause) { + times++; + } + + } + + class ClassWithoutMethodsAnnotatedWithExceptionHandler { + + public void methodWithoutExceptionHandlerAnotation(DemoiselleException cause) { + } + } + + class ClassWithMethodsAnnotatedWithExceptionHandlerAndThrowException { + + int times = 0; + + @ExceptionHandler + public void methodWithExceptionHandlerAnotation(DemoiselleException cause) { + times++; + throw new RuntimeException(); + } + } + + class ClassWithMethodWithoutParameterAnnotatedWithExceptionHandler { + + @ExceptionHandler + public void methodWithExceptionHandlerAnotation() { + } + + } + + @Before + public void setUp() throws Exception { + this.logger = PowerMock.createMock(Logger.class); + this.bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + this.logger.info(EasyMock.anyObject(String.class)); + PowerMock.expectLastCall().anyTimes(); + replay(this.logger); + this.interceptor = new ExceptionHandlerInterceptor(this.logger, this.bundle); + this.context = PowerMock.createMock(InvocationContext.class); + mockStatic(CoreBootstrap.class); + } + + @Test + public void testManageSucessyfull() throws Throwable { + expect(this.context.proceed()).andReturn(null); + replay(); + assertEquals(null, this.interceptor.manage(this.context)); + verify(); + } + + @Test + public void testManageWithClassThatDoNotContainMethodAnnotatedWithHandleException() throws Throwable { + ClassWithoutMethodsAnnotatedWithExceptionHandler classWithoutException = new ClassWithoutMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithoutException); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithoutMethodsAnnotatedWithExceptionHandler.class)).andReturn(true); + replayAll(this.context, ClassWithoutMethodsAnnotatedWithExceptionHandler.class); + + try { + this.interceptor.manage(this.context); + fail(); + } catch (DemoiselleException e) { + assertTrue(true); + } + + verifyAll(); + } + + @Test + public void testManageWithClassThatContainMethodAnnotatedWithHandleException() throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandler classWithException = new ClassWithMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodsAnnotatedWithExceptionHandler.class)).andReturn(true); + replayAll(this.context, CoreBootstrap.class); + + assertNull(this.interceptor.manage(this.context)); + assertEquals(1, classWithException.times); + verifyAll(); + } + + @Test + public void testManageWithClassThatContainTwoMethodsAnnotatedWithHandleExceptionButOnlyOneIsCalled() + throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandler classWithException = new ClassWithMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodsAnnotatedWithExceptionHandler.class)).andReturn(true); + replayAll(this.context, CoreBootstrap.class); + + assertNull(this.interceptor.manage(this.context)); + assertEquals(1, classWithException.times); + verifyAll(); + } + + @Test + public void testManageWithClassThatContainMethodAnnotatedWithHandleParentException() throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandler classWithException = new ClassWithMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodsAnnotatedWithExceptionHandler.class)).andReturn(true); + replayAll(this.context, CoreBootstrap.class); + + assertNull(this.interceptor.manage(this.context)); + assertEquals(1, classWithException.times); + verifyAll(); + } + + @Test + public void testManageWithClassThatContainMethodAnnotatedWithHandleExceptionButCauseIsDiferent() throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandler classWithException = new ClassWithMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new TesteException("")); + replay(this.context); + this.logger = PowerMock.createMock(Logger.class); + this.logger.info(EasyMock.anyObject(String.class)); + this.logger.debug(EasyMock.anyObject(String.class)); + replay(this.logger); + + this.interceptor = new ExceptionHandlerInterceptor(this.logger, this.bundle); + + try { + this.interceptor.manage(this.context); + fail(); + } catch (TesteException e) { + assertTrue(true); + assertEquals(0, classWithException.times); + } + verify(); + } + + @Test + public void testManageWithClassThatContainMethodAnnotatedWithHandleExceptionButMethodCouldNotBeCalled() + throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandlerAndThrowException classWithException = new ClassWithMethodsAnnotatedWithExceptionHandlerAndThrowException(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodsAnnotatedWithExceptionHandlerAndThrowException.class)) + .andReturn(true); + replayAll(this.context, CoreBootstrap.class); + + try { + this.interceptor.manage(this.context); + fail(); + } catch (Exception e) { + assertEquals(1, classWithException.times); + assertTrue(true); + } + + verifyAll(); + } + + @Test + public void testManageWithClassThatContainMethodsAnnotatedWithHandleExceptionAndIsInvokedTwice() throws Throwable { + ClassWithMethodsAnnotatedWithExceptionHandler classWithException = new ClassWithMethodsAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodsAnnotatedWithExceptionHandler.class)).andReturn(true).anyTimes(); + replayAll(this.context, CoreBootstrap.class); + + assertNull(this.interceptor.manage(this.context)); + assertEquals(1, classWithException.times); + + this.context = PowerMock.createMock(InvocationContext.class); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new Exception("")); + replayAll(this.context, CoreBootstrap.class); + + assertNull(this.interceptor.manage(this.context)); + assertEquals(2, classWithException.times); + verifyAll(); + + } + + @Test + public void testManageWithClassThatContainMethodAnnotatedWithHandleExceptionWithoutParameter() throws Throwable { + ClassWithMethodWithoutParameterAnnotatedWithExceptionHandler classWithException = new ClassWithMethodWithoutParameterAnnotatedWithExceptionHandler(); + expect(this.context.getTarget()).andReturn(classWithException).anyTimes(); + expect(this.context.proceed()).andThrow(new DemoiselleException("")); + expect(CoreBootstrap.isAnnotatedType(ClassWithMethodWithoutParameterAnnotatedWithExceptionHandler.class)).andReturn(true); + replayAll(this.context, CoreBootstrap.class); + + try { + this.interceptor.manage(this.context); + fail(); + } catch (DemoiselleException e) { + assertTrue(true); + } + + verifyAll(); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptorTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptorTest.java new file mode 100644 index 0000000..2e1217f --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredPermissionInterceptorTest.java @@ -0,0 +1,408 @@ +package br.gov.frameworkdemoiselle.internal.interceptor; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; + +import javax.enterprise.inject.Instance; +import javax.interceptor.InvocationContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.internal.implementation.CoreBundle; +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.security.RequiredPermission; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.security.SecurityException; +import br.gov.frameworkdemoiselle.security.User; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBundle.class) +public class RequiredPermissionInterceptorTest { + + private RequiredPermissionInterceptor interceptor; + + private InvocationContext ic; + + private SecurityContext securityContext; + + class UnnamedClass { + + @RequiredPermission + public void requiredPermissionWithoutDeclaredResourceAndOperation() { + } + + @RequiredPermission(operation = "insert") + public void requiredPermissionWithDeclaredOperation() { + } + + @RequiredPermission(resource = "contact") + public void requiredPermissionWithDeclaredResource() { + } + + @RequiredPermission(resource = "contact", operation = "insert") + public void requiredPermissionWithDeclaredResourceAndOperation() { + } + } + + @Name("contact2") + class NamedClass { + + @RequiredPermission + public void requiredPermissionWithoutDeclaredResourceAndOperation() { + } + + @RequiredPermission(operation = "insert") + public void requiredPermissionWithDeclaredOperation() { + } + + @RequiredPermission(resource = "contact") + public void requiredPermissionWithDeclaredResource() { + } + + @RequiredPermission(resource = "contact", operation = "insert") + public void requiredPermissionWithDeclaredResourceAndOperation() { + } + } + + @Name("contact2") + class NamedClassWithNamedMethods { + + @Name("delete") + @RequiredPermission + public void requiredPermissionWithoutDeclaredResourceAndOperation() { + } + + @Name("delete") + @RequiredPermission(operation = "insert") + public void requiredPermissionWithDeclaredOperation() { + } + + @Name("delete") + @RequiredPermission(resource = "contact") + public void requiredPermissionWithDeclaredResource() { + } + + @Name("delete") + @RequiredPermission(resource = "contact", operation = "insert") + public void requiredPermissionWithDeclaredResourceAndOperation() { + } + } + + @RequiredPermission + class ClassAnnotedWithRequiredPermission { + + public void withoutRequiredPermissionAnnotation() { + } + + @RequiredPermission(operation = "insert") + public void requiredPermissionWithDeclaredOperation() { + } + } + + @Before + public void setUp() throws Exception { + @SuppressWarnings("unchecked") + Instance securityContextInstance = createMock(Instance.class); + Logger logger = createMock(Logger.class); + + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + User user = createMock(User.class); + + mockStatic(CoreBundle.class); + expect(CoreBundle.get()).andReturn(bundle); + + this.securityContext = createMock(SecurityContext.class); + this.ic = createMock(InvocationContext.class); + + expect(user.getId()).andReturn("UserName").anyTimes(); + expect(this.securityContext.getUser()).andReturn(user).anyTimes(); + expect(securityContextInstance.get()).andReturn(securityContext).anyTimes(); + expect(this.ic.proceed()).andReturn(null); + replay(securityContextInstance, user, CoreBundle.class); + + this.interceptor = new RequiredPermissionInterceptor(securityContextInstance, bundle, logger); + } + + private void prepareMock(Object target, String methodName, String expectedResource, String expectedOperation, + boolean hasPermission, boolean isLoggedUser) throws Exception { + + expect(this.securityContext.isLoggedIn()).andReturn(isLoggedUser).anyTimes(); + + this.securityContext.hasPermission(expectedResource, expectedOperation); + + if (isLoggedUser) { + expectLastCall().andReturn(hasPermission); + } else { + expectLastCall().andThrow(new NotLoggedInException("")); + } + + expect(this.ic.getTarget()).andReturn(target).anyTimes(); + expect(this.ic.getMethod()).andReturn(target.getClass().getMethod(methodName)).anyTimes(); + replay(this.ic, this.securityContext); + } + + /* Testing UnnamedClass */ + + @Test + public void testManageUnnamedClassAtRequiredPermissionWithoutDeclaredResourceAndOperationMethod() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithoutDeclaredResourceAndOperation"; + String expectedResource = target.getClass().getSimpleName(); + String expectedOperation = methodName; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageUnnamedClassAtRequiredPermissionWithDeclaredOperationMethod() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithDeclaredOperation"; + String expectedResource = target.getClass().getSimpleName(); + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageUnnamedClassAtRequiredPermissionWithDeclaredResourceMethod() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithDeclaredResource"; + String expectedResource = "contact"; + String expectedOperation = methodName; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageUnnamedClassAtRequiredPermissionWithDeclaredResourceAndOperation() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithDeclaredResourceAndOperation"; + String expectedResource = "contact"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + /* Testing NamedClass */ + + @Test + public void testManageNamedClassAtRequiredPermissionWithoutDeclaredResourceAndOperationMethod() throws Exception { + try { + Object target = new NamedClass(); + String methodName = "requiredPermissionWithoutDeclaredResourceAndOperation"; + String expectedResource = "contact2"; + String expectedOperation = methodName; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassAtRequiredPermissionWithDeclaredOperationMethod() throws Exception { + try { + Object target = new NamedClass(); + String methodName = "requiredPermissionWithDeclaredOperation"; + String expectedResource = "contact2"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassAtRequiredPermissionWithDeclaredResourceMethod() throws Exception { + try { + Object target = new NamedClass(); + String methodName = "requiredPermissionWithDeclaredResource"; + String expectedResource = "contact"; + String expectedOperation = methodName; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassAtRequiredPermissionWithDeclaredResourceAndOperation() throws Exception { + try { + Object target = new NamedClass(); + String methodName = "requiredPermissionWithDeclaredResourceAndOperation"; + String expectedResource = "contact"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + /* Testing NamedClassWithNamedMethods */ + + @Test + public void testManageNamedClassWithNamedMethodsAtRequiredPermissionWithoutDeclaredResourceAndOperationMethod() + throws Exception { + try { + Object target = new NamedClassWithNamedMethods(); + String methodName = "requiredPermissionWithoutDeclaredResourceAndOperation"; + String expectedResource = "contact2"; + String expectedOperation = "delete"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassWithNamedMethodsAtRequiredPermissionWithDeclaredOperationMethod() throws Exception { + try { + Object target = new NamedClassWithNamedMethods(); + String methodName = "requiredPermissionWithDeclaredOperation"; + String expectedResource = "contact2"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassWithNamedMethodsAtRequiredPermissionWithDeclaredResourceMethod() throws Exception { + try { + Object target = new NamedClassWithNamedMethods(); + String methodName = "requiredPermissionWithDeclaredResource"; + String expectedResource = "contact"; + String expectedOperation = "delete"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageNamedClassWithNamedMethodsAtRequiredPermissionWithDeclaredResourceAndOperation() + throws Exception { + try { + Object target = new NamedClassWithNamedMethods(); + String methodName = "requiredPermissionWithDeclaredResourceAndOperation"; + String expectedResource = "contact"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + /* Testing ClassAnnotedWithRequiredPermission */ + + @Test + public void testManageClassAnnotedWithRequiredPermissionAtWithoutRequiredPermissionAnnotation() throws Exception { + try { + Object target = new ClassAnnotedWithRequiredPermission(); + String methodName = "withoutRequiredPermissionAnnotation"; + String expectedResource = target.getClass().getSimpleName(); + String expectedOperation = methodName; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + @Test + public void testManageClassAnnotedWithRequiredPermissionAtRequiredPermissionWithDeclaredOperation() + throws Exception { + try { + Object target = new ClassAnnotedWithRequiredPermission(); + String methodName = "requiredPermissionWithDeclaredOperation"; + String expectedResource = target.getClass().getSimpleName(); + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, true); + + interceptor.manage(this.ic); + } catch (SecurityException cause) { + fail(); + } + } + + /* Other tests */ + + @Test + public void testManagePermissionNotAllowed() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithDeclaredResourceAndOperation"; + String expectedResource = "contact"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (SecurityException cause) { + } + } + + @Test + public void testUserNotLoggedIn() throws Exception { + try { + Object target = new UnnamedClass(); + String methodName = "requiredPermissionWithDeclaredResourceAndOperation"; + String expectedResource = "contact"; + String expectedOperation = "insert"; + prepareMock(target, methodName, expectedResource, expectedOperation, true, false); + + interceptor.manage(this.ic); + fail(); + } catch (SecurityException cause) { + } + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptorTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptorTest.java new file mode 100644 index 0000000..0213821 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/RequiredRoleInterceptorTest.java @@ -0,0 +1,308 @@ +package br.gov.frameworkdemoiselle.internal.interceptor; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; + +import javax.enterprise.inject.Instance; +import javax.interceptor.InvocationContext; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.implementation.CoreBundle; +import br.gov.frameworkdemoiselle.security.AuthorizationException; +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.security.RequiredRole; +import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.security.User; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBundle.class) +public class RequiredRoleInterceptorTest { + + private RequiredRoleInterceptor interceptor; + + private InvocationContext ic; + + private SecurityContext securityContext; + + class ClassNotAnnoted { + + @RequiredRole("simpleRoleName") + public void requiredRoleWithSingleRole() { + } + + @RequiredRole({ "firstRole", "secondRole", "thirdRole", "fourthRole", "fifthRole" }) + public void requiredRoleWithArrayOfRoles() { + } + + @RequiredRole({ "firstRole, secondRole" }) + public void requiredRoleWithArrayOfSingleRoleComma() { + } + + @RequiredRole("firstRole, secondRole") + public void requiredRoleWithSingleRoleComma() { + } + + @RequiredRole("") + public void requiredRoleWithEmptyValue() { + } + + @RequiredRole({}) + public void requiredRoleWithEmptyArray() { + } + + @RequiredRole({ "" }) + public void requiredRoleWithArrayOfEmptyString() { + } + + public void methodNotAnnoted() { + } + } + + @RequiredRole("classRole") + class ClassAnnotedWithRequiredRole { + + public void withoutRole() { + } + + @RequiredRole("simpleRoleName") + public void requiredRoleWithSingleRole() { + } + } + + @Before + public void setUp() throws Exception { + + @SuppressWarnings("unchecked") + Instance securityContextInstance = EasyMock.createMock(Instance.class); + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + Logger logger = EasyMock.createMock(Logger.class); + User user = EasyMock.createMock(User.class); + + this.securityContext = EasyMock.createMock(SecurityContext.class); + this.ic = EasyMock.createMock(InvocationContext.class); + + mockStatic(CoreBundle.class); + expect(CoreBundle.get()).andReturn(bundle); + + expect(user.getId()).andReturn("UserName").anyTimes(); + expect(this.securityContext.getUser()).andReturn(user).anyTimes(); + expect(securityContextInstance.get()).andReturn(securityContext).anyTimes(); + expect(this.ic.proceed()).andReturn(null); + replay(securityContextInstance, user, CoreBundle.class); + + this.interceptor = new RequiredRoleInterceptor(securityContextInstance, bundle, logger); + } + + private void prepareMock(Object target, String methodName, String[] expectedRoles, boolean hasHole, + boolean isLoggedUser) throws Exception { + + expect(this.securityContext.isLoggedIn()).andReturn(isLoggedUser).anyTimes(); + + for (String role : expectedRoles) { + this.securityContext.hasRole(role); + if (isLoggedUser) { + EasyMock.expectLastCall().andReturn(hasHole); + } else { + EasyMock.expectLastCall().andThrow(new NotLoggedInException("")); + } + } + + expect(this.ic.getTarget()).andReturn(target).anyTimes(); + expect(this.ic.getMethod()).andReturn(target.getClass().getMethod(methodName)).anyTimes(); + replay(this.ic, this.securityContext); + } + + /* + * Testing ClassNotAnnoted + */ + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithSingleRole() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithSingleRole"; + String[] expectedRoles = { "simpleRoleName" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithArrayOfRoles() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithArrayOfRoles"; + String[] expectedRoles = { "firstRole", "secondRole", "thirdRole", "fourthRole", "fifthRole" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithArrayOfSingleRoleComma() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithArrayOfSingleRoleComma"; + String[] expectedRoles = { "firstRole, secondRole" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithSingleRoleComma() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithSingleRoleComma"; + String[] expectedRoles = { "firstRole, secondRole" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithEmptyValue() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithEmptyValue"; + String[] expectedRoles = { "" }; + prepareMock(target, methodName, expectedRoles, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (AuthorizationException cause) { + } + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithEmptyArray() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithEmptyArray"; + String[] expectedRoles = { "" }; + prepareMock(target, methodName, expectedRoles, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (AuthorizationException cause) { + } + } + + @Test + public void testManageClassNotAnnotedAtRequiredRoleWithArrayOfEmptyString() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithArrayOfEmptyString"; + String[] expectedRoles = { "" }; + prepareMock(target, methodName, expectedRoles, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (AuthorizationException cause) { + } + } + + @Test + public void testManageClassNotAnnotedAtMethodNotAnnoted() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "methodNotAnnoted"; + String[] expectedRoles = { "" }; + prepareMock(target, methodName, expectedRoles, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (AuthorizationException cause) { + } + } + + /* + * Testing ClassAnnoted + */ + @Test + public void testManageClassAnnotedWithRequiredRoleAtWithoutRole() throws Exception { + Object target = new ClassAnnotedWithRequiredRole(); + String methodName = "withoutRole"; + String[] expectedRoles = { "classRole" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testManageClassAnnotedWithRequiredRoleAtRequiredRoleWithSingleRole() throws Exception { + Object target = new ClassAnnotedWithRequiredRole(); + String methodName = "requiredRoleWithSingleRole"; + String[] expectedRoles = { "simpleRoleName" }; + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + /* + * Other tests + */ + + @Test + public void testDoesNotHaveSingleRole() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithSingleRole"; + String[] expectedRoles = { "simpleRoleName" }; + prepareMock(target, methodName, expectedRoles, false, true); + + interceptor.manage(this.ic); + fail(); + } catch (AuthorizationException cause) { + } + } + + @Test + public void testUserNotLoggedIn() throws Exception { + try { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithSingleRole"; + String[] expectedRoles = { "simpleRoleName" }; + prepareMock(target, methodName, expectedRoles, true, false); + + interceptor.manage(this.ic); + fail(); + } catch (NotLoggedInException cause) { + } + } + + @Test + public void testDoesNotHaveOneOrMoreRolesOfArray() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithArrayOfRoles"; + String[] expectedRoles = { "thirdRole", "fourthRole", "fifthRole" }; + + expect(this.securityContext.hasRole("firstRole")).andReturn(false); + expect(this.securityContext.hasRole("secondRole")).andReturn(false); + + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + + @Test + public void testHasMoreRolesThenArray() throws Exception { + Object target = new ClassNotAnnoted(); + String methodName = "requiredRoleWithArrayOfRoles"; + String[] expectedRoles = { "thirdRole", "fourthRole", "fifthRole" }; + + expect(this.securityContext.hasRole("firstRole")).andReturn(false); + expect(this.securityContext.hasRole("secondRole")).andReturn(false); + expect(this.securityContext.hasRole("sixthRole")).andReturn(true); + + prepareMock(target, methodName, expectedRoles, true, true); + + interceptor.manage(this.ic); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptorTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptorTest.java new file mode 100644 index 0000000..bd31b42 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/interceptor/TransactionalInterceptorTest.java @@ -0,0 +1,182 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.interceptor; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import javax.enterprise.inject.Instance; +import javax.interceptor.InvocationContext; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.internal.implementation.TransactionInfo; +import br.gov.frameworkdemoiselle.transaction.Transaction; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +public class TransactionalInterceptorTest { + + private TransactionalInterceptor interceptor; + + private InvocationContext ic; + + private Transaction transaction; + + class ClassWithMethod { + + public void method() { + System.out.println("test method"); + } + } + + @Before + @SuppressWarnings("unchecked") + public void setUp() throws Exception { + Instance transactionInstance = EasyMock.createMock(Instance.class); + Instance transactionContextInstance = EasyMock.createMock(Instance.class); + + Logger logger = EasyMock.createMock(Logger.class); + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + transaction = EasyMock.createMock(Transaction.class); + TransactionInfo context = new TransactionInfo(); + + this.interceptor = new TransactionalInterceptor(transactionInstance, transactionContextInstance, logger, bundle); + this.ic = EasyMock.createMock(InvocationContext.class); + + expect(transactionInstance.get()).andReturn(transaction).anyTimes(); + expect(transactionContextInstance.get()).andReturn(context).anyTimes(); + expect(this.ic.proceed()).andReturn(null); + expect(this.ic.getMethod()).andReturn(ClassWithMethod.class.getMethod("method")); + replay(this.ic, transactionInstance, transactionContextInstance); + } + + @Test + public void testManageWithInativeTransactionAndTransactionInterceptorBeginAndDoNotIsMarkedRollback() + throws Exception { + expect(this.transaction.isActive()).andReturn(false).times(1); + expect(this.transaction.isActive()).andReturn(true).times(2); + expect(this.transaction.isMarkedRollback()).andReturn(false).anyTimes(); + this.transaction.begin(); + this.transaction.commit(); + replay(this.transaction); + + assertEquals(null, this.interceptor.manage(this.ic)); + verify(); + } + + @Test + public void testManageWithInativeTransactionAndTransactionInterceptorBeginAndIsMarkedRollback() throws Exception { + expect(this.transaction.isActive()).andReturn(false).times(1); + expect(this.transaction.isActive()).andReturn(true).times(2); + expect(this.transaction.isMarkedRollback()).andReturn(true).anyTimes(); + this.transaction.begin(); + this.transaction.rollback(); + replay(this.transaction); + + assertEquals(null, this.interceptor.manage(this.ic)); + verify(); + } + + @Test + public void testManageWithAtiveTransaction() throws Exception { + expect(this.transaction.isActive()).andReturn(true).anyTimes(); + replay(this.transaction); + + assertEquals(null, this.interceptor.manage(this.ic)); + verify(); + } + + @Test + public void testManageWithAtiveTransactionButTheTransactionWasInative() throws Exception { + expect(this.transaction.isActive()).andReturn(true).times(1); + expect(this.transaction.isActive()).andReturn(false).times(2); + replay(this.transaction); + + assertEquals(null, this.interceptor.manage(this.ic)); + verify(); + } + + @Test + public void testManageWithAtiveTransactionAndMethodThrowExceptionAndDoNotIsMarkedRollback() throws Exception { + expect(this.transaction.isActive()).andReturn(true).anyTimes(); + expect(this.transaction.isMarkedRollback()).andReturn(false).anyTimes(); + this.transaction.setRollbackOnly(); + replay(this.transaction); + + this.ic = EasyMock.createMock(InvocationContext.class); + expect(this.ic.proceed()).andThrow(new DemoiselleException("")); + expect(this.ic.getMethod()).andReturn(ClassWithMethod.class.getMethod("method")); + replay(this.ic); + + try { + this.interceptor.manage(this.ic); + fail(); + } catch (DemoiselleException cause) { + assertTrue(true); + } + verify(); + } + + @Test + public void testManageWithAtiveTransactionAndMethodThrowExceptionAndIsMarkedRollback() throws Exception { + expect(this.transaction.isActive()).andReturn(true).anyTimes(); + expect(this.transaction.isMarkedRollback()).andReturn(true).anyTimes(); + this.transaction.setRollbackOnly(); + replay(this.transaction); + + this.ic = EasyMock.createMock(InvocationContext.class); + expect(this.ic.proceed()).andThrow(new DemoiselleException("")); + expect(this.ic.getMethod()).andReturn(ClassWithMethod.class.getMethod("method")); + replay(this.ic); + + try { + this.interceptor.manage(this.ic); + fail(); + } catch (DemoiselleException cause) { + assertTrue(true); + } + verify(); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducerTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducerTest.java new file mode 100644 index 0000000..8dc04e1 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ContextProducerTest.java @@ -0,0 +1,66 @@ +package br.gov.frameworkdemoiselle.internal.producer; + +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.mockStatic; + +import javax.naming.Context; +import javax.naming.NamingException; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.DemoiselleException; + +import com.sun.naming.internal.ResourceManager; + +@SuppressWarnings("restriction") +@RunWith(PowerMockRunner.class) +@PrepareForTest(ResourceManager.class) +public class ContextProducerTest { + + @Test + public void testCreate() { + + Context context = ContextProducer.create(); + + Assert.assertNotNull(context); + + } + + @Test + public void testCreateThrowingException() { + + Context context = null; + + try { + + mockStatic(ResourceManager.class); + expect(ResourceManager.getInitialEnvironment(null)).andThrow(new NamingException()); + PowerMock.replay(ResourceManager.class); + + context = ContextProducer.create(); + fail(); + + } catch (Exception e) { + assertNull(context); + assertTrue(e instanceof DemoiselleException); + } + + } + + // This test exists only to get 100% on conbertura. + @Test + public void testInstantiateContextProducer() { + @SuppressWarnings("unused") + ContextProducer contextProducer = new ContextProducer(); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducerTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducerTest.java new file mode 100644 index 0000000..d854106 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LocaleProducerTest.java @@ -0,0 +1,20 @@ +package br.gov.frameworkdemoiselle.internal.producer; + +import java.util.Locale; + +import junit.framework.Assert; + +import org.junit.Test; + +public class LocaleProducerTest { + + @Test + public void testCreate() { + + Locale locale = (new LocaleProducer()).create(); + + Assert.assertNotNull(locale); + + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducerTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducerTest.java new file mode 100644 index 0000000..6038e41 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/LoggerProducerTest.java @@ -0,0 +1,91 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.junit.Assert.assertNotNull; + +import java.lang.reflect.Member; + +import javax.enterprise.inject.spi.InjectionPoint; + +import org.junit.Test; +import org.slf4j.Logger; + +public class LoggerProducerTest { + + private Logger logger; + + @Test + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void testCreateInjectionPoint() { + + Member member = createMock(Member.class); + expect(member.getDeclaringClass()).andReturn((Class) this.getClass()); + replay(member); + + InjectionPoint injectionPoint = createMock(InjectionPoint.class); + expect(injectionPoint.getMember()).andReturn(member); + replay(injectionPoint); + + logger = LoggerProducer.create(injectionPoint); + assertNotNull(logger); + } + + @Test + public void testCreateWithNullInjectionPoint() { + logger = LoggerProducer.create((InjectionPoint) null); + assertNotNull(logger); + } + + @Test + public void testCreateClass() { + logger = LoggerProducer.create(this.getClass()); + assertNotNull(logger); + } + + // We don't need to instantiate LoggerProducer class. But if we don't get in this way, we'll not get 100% on + // cobertura. + @Test + public void testLoggerFactoryDiferentNull() { + @SuppressWarnings("unused") + LoggerProducer loggerProducer = new LoggerProducer(); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducerTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducerTest.java new file mode 100644 index 0000000..eb1b8d4 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/producer/ResourceBundleProducerTest.java @@ -0,0 +1,159 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.junit.Assert.assertTrue; + +import java.util.Locale; + +import javax.enterprise.inject.spi.Annotated; +import javax.enterprise.inject.spi.InjectionPoint; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +public class ResourceBundleProducerTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testResourceBundleFactory() { + ResourceBundleProducer factory = new ResourceBundleProducer(); + Assert.assertNotNull(factory); + } + + @Test + public void testResourceBundleFactoryLocale() { + ResourceBundleProducer factory = new ResourceBundleProducer(Locale.getDefault()); + Assert.assertNotNull(factory); + } + + @Test + public void testCreateString() { + ResourceBundleProducer factory = new ResourceBundleProducer(Locale.getDefault()); + Assert.assertNotNull(factory.create("demoiselle-core-bundle")); + } + + @Test + public void testCreateStringWithoutLocale() { + ResourceBundleProducer factory = new ResourceBundleProducer(); + Assert.assertNotNull(factory.create("demoiselle-core-bundle")); + } + + @Test + public void testCreateWithNonExistentFile() { + ResourceBundleProducer factory = new ResourceBundleProducer(Locale.getDefault()); + try { + factory.create("arquivo_inexistente"); + } catch (Exception e) { + assertTrue(e instanceof DemoiselleException); + } + } + + @Test + public void testCreateNullInjectionPoint() { + ResourceBundleProducer factory = new ResourceBundleProducer(); + Assert.assertNotNull(factory.create((InjectionPoint) null, Locale.getDefault())); + } + + @Test + public void testCreateInjectionPointNameAnnoted() { + Name name = EasyMock.createMock(Name.class); + expect(name.value()).andReturn("demoiselle-core-bundle"); + replay(name); + + Annotated annotated = EasyMock.createMock(Annotated.class); + expect(annotated.getAnnotation(Name.class)).andReturn(name).anyTimes(); + expect(annotated.isAnnotationPresent(Name.class)).andReturn(true).anyTimes(); + replay(annotated); + + InjectionPoint ip = EasyMock.createMock(InjectionPoint.class); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + replay(ip); + + ResourceBundleProducer factory = new ResourceBundleProducer(); + Assert.assertNotNull(factory.create(ip, Locale.getDefault())); + } + + @Test + public void testCreateInjectionPointNameUnannoted() { + Annotated annotated = EasyMock.createMock(Annotated.class); + expect(annotated.isAnnotationPresent(Name.class)).andReturn(false).anyTimes(); + replay(annotated); + + InjectionPoint ip = EasyMock.createMock(InjectionPoint.class); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + replay(ip); + + ResourceBundleProducer factory = new ResourceBundleProducer(); + Assert.assertNotNull(factory.create(ip, Locale.getDefault())); + } + + @Test + public void testCreateTwice() { + ResourceBundleProducer factory = new ResourceBundleProducer(Locale.getDefault()); + ResourceBundle bundle = factory.create("demoiselle-core-bundle"); + + Assert.assertNotNull(bundle); + Assert.assertEquals(bundle, factory.create("demoiselle-core-bundle")); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxyTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxyTest.java new file mode 100644 index 0000000..f141c32 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/ContextProxyTest.java @@ -0,0 +1,305 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingException; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; + +public class ContextProxyTest { + + private Context context; + private ContextProxy contextProxy; + + @Before + public void setUp() throws Exception { + this.context = EasyMock.createMock(Context.class); + this.contextProxy = new ContextProxy(this.context); + } + + @Test + public void testAddToEnvironment() throws NamingException { + expect(this.context.addToEnvironment("", null)).andReturn(null); + replay(this.context); + this.contextProxy.addToEnvironment("", null); + verify(this.context); + } + + @Test + public void testBindWithNameAndObject() throws NamingException { + Name name = null; + this.context.bind(name, null); + replay(this.context); + this.contextProxy.bind(name, null); + verify(this.context); + } + + @Test + public void testBindWithStringAndObject() throws NamingException { + this.context.bind("", null); + replay(this.context); + this.contextProxy.bind("", null); + verify(this.context); + } + + @Test + public void testClose() throws NamingException { + this.context.close(); + replay(this.context); + this.contextProxy.close(); + verify(this.context); + } + + @Test + public void testComposeNameWithTwoNames() throws NamingException { + Name n1=null, n2=null; + expect(this.context.composeName(n1,n2)).andReturn(null); + replay(this.context); + this.contextProxy.composeName(n1,n2); + verify(this.context); + } + + @Test + public void testComposeNameWithTwoStrings() throws NamingException { + expect(this.context.composeName("","")).andReturn(null); + replay(this.context); + this.contextProxy.composeName("",""); + verify(this.context); + } + + @Test + public void testCreateSubcontextWithName() throws NamingException { + Name n1 = null; + expect(this.context.createSubcontext(n1)).andReturn(null); + replay(this.context); + this.contextProxy.createSubcontext(n1); + verify(this.context); + } + + @Test + public void testCreateSubcontextWithString() throws NamingException { + expect(this.context.createSubcontext("")).andReturn(null); + replay(this.context); + this.contextProxy.createSubcontext(""); + verify(this.context); + } + + @Test + public void testDestroySubcontextWithName() throws NamingException { + Name n1=null; + context.destroySubcontext(n1); + replay(this.context); + this.contextProxy.destroySubcontext(n1); + verify(this.context); + } + + @Test + public void testDestroySubcontextWithString() throws NamingException { + context.destroySubcontext(""); + replay(this.context); + this.contextProxy.destroySubcontext(""); + verify(this.context); + } + + @Test + public void testGetNameInNamespace() throws NamingException { + expect(this.context.getNameInNamespace()).andReturn(null); + replay(this.context); + this.contextProxy.getNameInNamespace(); + verify(this.context); + } + + @Test + public void testGetNameParserWithName() throws NamingException { + Name n1=null; + expect(this.context.getNameParser(n1)).andReturn(null); + replay(this.context); + this.contextProxy.getNameParser(n1); + verify(this.context); + } + + @Test + public void testGetNameParserWithString() throws NamingException { + expect(this.context.getNameParser("")).andReturn(null); + replay(this.context); + this.contextProxy.getNameParser(""); + verify(this.context); + } + + @Test + public void testListWithName() throws NamingException { + Name n1=null; + expect(this.context.list(n1)).andReturn(null); + replay(this.context); + this.contextProxy.list(n1); + verify(this.context); + } + + @Test + public void testListWithString() throws NamingException { + expect(this.context.list("")).andReturn(null); + replay(this.context); + this.contextProxy.list(""); + verify(this.context); + } + + @Test + public void testListBindingsWithName() throws NamingException { + Name n1=null; + expect(this.context.listBindings(n1)).andReturn(null); + replay(this.context); + this.contextProxy.listBindings(n1); + verify(this.context); + } + + @Test + public void testListBindingsWithString() throws NamingException { + expect(this.context.listBindings("")).andReturn(null); + replay(this.context); + this.contextProxy.listBindings(""); + verify(this.context); + } + + @Test + public void testLookupBindingsWithString() throws NamingException { + Name n1 = null; + expect(this.context.lookup(n1)).andReturn(null); + replay(this.context); + this.contextProxy.lookup(n1); + verify(this.context); + } + + @Test + public void testLookupWithString() throws NamingException { + expect(this.context.lookup("")).andReturn(null); + replay(this.context); + this.contextProxy.lookup(""); + verify(this.context); + } + + @Test + public void testLookupLinkBindingsWithString() throws NamingException { + Name n1 = null; + expect(this.context.lookupLink(n1)).andReturn(null); + replay(this.context); + this.contextProxy.lookupLink(n1); + verify(this.context); + } + + @Test + public void testLookupLinkWithString() throws NamingException { + expect(this.context.lookupLink("")).andReturn(null); + replay(this.context); + this.contextProxy.lookupLink(""); + verify(this.context); + } + + @Test + public void testRebindWithNameAndObject() throws NamingException { + Name n1 = null; + this.context.rebind(n1,null); + replay(this.context); + this.contextProxy.rebind(n1,null); + verify(this.context); + } + + @Test + public void testRebindWithStringAndObject() throws NamingException { + this.context.rebind("",null); + replay(this.context); + this.contextProxy.rebind("",null); + verify(this.context); + } + + @Test + public void testRemoveFromEnvironmentWithString() throws NamingException { + expect(this.context.removeFromEnvironment("")).andReturn(null); + replay(this.context); + this.contextProxy.removeFromEnvironment(""); + verify(this.context); + } + + @Test + public void testRenameWithTwoNames() throws NamingException { + Name n1 = null, n2=null; + this.context.rename(n1,n2); + replay(this.context); + this.contextProxy.rename(n1,n2); + verify(this.context); + } + + @Test + public void testRenameWithTwoStrings() throws NamingException{ + this.context.rename("",""); + replay(this.context); + this.contextProxy.rename("",""); + verify(this.context); + } + + @Test + public void testUnbind() throws NamingException { + Name n1 = null; + this.context.unbind(n1); + replay(this.context); + this.contextProxy.unbind(n1); + verify(this.context); + } + + @Test + public void testUnbindWithString() throws NamingException { + this.context.unbind(""); + replay(this.context); + this.contextProxy.unbind(""); + verify(this.context); + } + + @Test + public void testGetEnvironment() throws NamingException { + expect(this.context.getEnvironment()).andReturn(null); + replay(this.context); + this.contextProxy.getEnvironment(); + verify(this.context); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxyTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxyTest.java new file mode 100644 index 0000000..e14a117 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/Slf4jLoggerProxyTest.java @@ -0,0 +1,560 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.Marker; + + +public class Slf4jLoggerProxyTest { + + private Logger logger; + private Slf4jLoggerProxy slf4jLoggerProxy; + + @Before + public void setUp() throws Exception { + this.logger = EasyMock.createMock(Logger.class); + this.slf4jLoggerProxy = new Slf4jLoggerProxy(this.logger); + } + + @Test + public void testDebugWithMarkerAndString() { + Marker marker = null; + this.logger.debug(marker,""); + replay(this.logger); + this.slf4jLoggerProxy.debug(marker,""); + verify(this.logger); + } + @Test + public void testDebugWithMarkerStringAndOneObject() { + Marker marker = null; + Object obj = null; + this.logger.debug(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.debug(marker,"",obj); + verify(this.logger); + } + @Test + public void testDebugWithMarkerStringAndTwoObjects() { + Marker marker = null; + Object obj1 = null, obj2 = null; + this.logger.debug(marker,"",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.debug(marker,"",obj1,obj2); + verify(this.logger); + } + @Test + public void testDebugWithMarkerStringAndObjectArray() { + Marker marker = null; + Object[] obj = null; + this.logger.debug(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.debug(marker,"",obj); + verify(this.logger); + } + + @Test + public void testDebugWithMarkerStringAndThrowable() { + Marker marker = null; + Throwable t = null; + this.logger.debug(marker,"",t); + replay(this.logger); + this.slf4jLoggerProxy.debug(marker,"",t); + verify(this.logger); + } + @Test + public void testDebugWithString() { + this.logger.debug(""); + replay(this.logger); + this.slf4jLoggerProxy.debug(""); + verify(this.logger); + } + @Test + public void testDebugWithStringAndOneObject() { + Object obj = null; + this.logger.debug("",obj); + replay(this.logger); + this.slf4jLoggerProxy.debug("",obj); + verify(this.logger); + } + @Test + public void testDebugWithStringAndTwoObjects() { + Object obj1 = null, obj2 = null; + this.logger.debug("",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.debug("",obj1,obj2); + verify(this.logger); + } + @Test + public void testDebugWithStringAndObjectArray() { + Object[] obj = null; + this.logger.debug("",obj); + replay(this.logger); + this.slf4jLoggerProxy.debug("",obj); + verify(this.logger); + } + @Test + public void testDebugWithStringAndThrowable() { + Throwable t = null; + this.logger.debug("",t); + replay(this.logger); + this.slf4jLoggerProxy.debug("",t); + verify(this.logger); + } + @Test + public void testErrorWithMarkerAndString() { + Marker marker = null; + this.logger.error(marker,""); + replay(this.logger); + this.slf4jLoggerProxy.error(marker,""); + verify(this.logger); + } + @Test + public void testErrorWithMarkerStringAndOneObject() { + Marker marker = null; + Object obj = null; + this.logger.error(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.error(marker,"",obj); + verify(this.logger); + } + @Test + public void testErrorWithMarkerStringAndTwoObjects() { + Marker marker = null; + Object obj1 = null, obj2 = null; + this.logger.error(marker,"",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.error(marker,"",obj1,obj2); + verify(this.logger); + } + @Test + public void testErrorWithMarkerStringAndObjectArray() { + Marker marker = null; + Object[] obj1 = null; + this.logger.error(marker,"",obj1); + replay(this.logger); + this.slf4jLoggerProxy.error(marker,"",obj1); + verify(this.logger); + } + @Test + public void testErrorWithMarkerStringAndThrowable() { + Marker marker = null; + Throwable t = null; + this.logger.error(marker,"",t); + replay(this.logger); + this.slf4jLoggerProxy.error(marker,"",t); + verify(this.logger); + } + @Test + public void testErrorWithString() { + this.logger.error(""); + replay(this.logger); + this.slf4jLoggerProxy.error(""); + verify(this.logger); + } + @Test + public void testErrorWithStringAndOneObject() { + Object obj = null; + this.logger.error("",obj); + replay(this.logger); + this.slf4jLoggerProxy.error("",obj); + verify(this.logger); + } + @Test + public void testErrorWithStringAndTwoObjects() { + Object obj1 = null,obj2 = null; + this.logger.error("",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.error("",obj1,obj2); + verify(this.logger); + } + @Test + public void testErrorWithStringAndObjectArray() { + Object[] obj = null; + this.logger.error("",obj); + replay(this.logger); + this.slf4jLoggerProxy.error("",obj); + verify(this.logger); + } + @Test + public void testErrorWithStringAndThrowable() { + Throwable t = null; + this.logger.error("",t); + replay(this.logger); + this.slf4jLoggerProxy.error("",t); + verify(this.logger); + } + @Test + public void testGetName() { + expect(this.logger.getName()).andReturn("xxx"); + replay(this.logger); + assertEquals("xxx", this.slf4jLoggerProxy.getName()); + verify(this.logger); + } + @Test + public void testInfoWithMarkerAndString() { + Marker marker = null; + this.logger.info(marker,""); + replay(this.logger); + this.slf4jLoggerProxy.info(marker,""); + verify(this.logger); + } + @Test + public void testInfoWithMarkerStringAndOneObject() { + Marker marker = null; + Object obj = null; + this.logger.info(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.info(marker,"",obj); + verify(this.logger); + } + @Test + public void testInfoWithMarkerStringAndTwoObjects() { + Marker marker = null; + Object obj1 = null, obj2 = null; + this.logger.info(marker,"",obj1, obj2); + replay(this.logger); + this.slf4jLoggerProxy.info(marker,"",obj1,obj2); + verify(this.logger); + } + @Test + public void testInfoWithMarkerStringAndObjectArray() { + Marker marker = null; + Object[] obj = null; + this.logger.info(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.info(marker,"",obj); + verify(this.logger); + } + @Test + public void testInfoWithMarkerStringAndThrowable() { + Marker marker = null; + Throwable t = null; + this.logger.info(marker,"",t); + replay(this.logger); + this.slf4jLoggerProxy.info(marker,"",t); + verify(this.logger); + } + @Test + public void testInfoWithString() { + this.logger.info(""); + replay(this.logger); + this.slf4jLoggerProxy.info(""); + verify(this.logger); + } + @Test + public void testInfoWithStringAndOneObject() { + Object obj = null; + this.logger.info("",obj); + replay(this.logger); + this.slf4jLoggerProxy.info("",obj); + verify(this.logger); + } + @Test + public void testInfoWithStringAndTwoObjects() { + Object obj1 = null, obj2 = null; + this.logger.info("",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.info("",obj1,obj2); + verify(this.logger); + } + @Test + public void testInfoWithStringAndObjectArray() { + Object[] obj = null; + this.logger.info("",obj); + replay(this.logger); + this.slf4jLoggerProxy.info("",obj); + verify(this.logger); + } + @Test + public void testInfoWithStringAndThrowable() { + Throwable t = null; + this.logger.info("",t); + replay(this.logger); + this.slf4jLoggerProxy.info("",t); + verify(this.logger); + } + @Test + public void testIsDebugEnabled() { + expect(this.logger.isDebugEnabled()).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isDebugEnabled()); + verify(this.logger); + } + @Test + public void testIsDebugEnabledWithMarker() { + Marker marker = null; + expect(this.logger.isDebugEnabled(marker)).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isDebugEnabled(marker)); + verify(this.logger); + } + @Test + public void testIsErrorEnabled() { + expect(this.logger.isErrorEnabled()).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isErrorEnabled()); + verify(this.logger); + } + @Test + public void testIsErrorEnabledWithMarker() { + Marker marker = null; + expect(this.logger.isErrorEnabled(marker)).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isErrorEnabled(marker)); + verify(this.logger); + } + @Test + public void testIsInfoEnabled() { + expect(this.logger.isInfoEnabled()).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isInfoEnabled()); + verify(this.logger); + } + @Test + public void testIsInfoEnabledWithMarker() { + Marker marker = null; + expect(this.logger.isInfoEnabled(marker)).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isInfoEnabled(marker)); + verify(this.logger); + } + @Test + public void testIsTRaceEnabled() { + expect(this.logger.isTraceEnabled()).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isTraceEnabled()); + verify(this.logger); + } + @Test + public void testIsTraceEnabledWithMarker() { + Marker marker = null; + expect(this.logger.isTraceEnabled(marker)).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isTraceEnabled(marker)); + verify(this.logger); + } + @Test + public void testIsWarnEnabled() { + expect(this.logger.isWarnEnabled()).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isWarnEnabled()); + verify(this.logger); + } + @Test + public void testIsWarnEnabledWithMarker() { + Marker marker = null; + expect(this.logger.isWarnEnabled(marker)).andReturn(true); + replay(this.logger); + assertEquals(true, this.slf4jLoggerProxy.isWarnEnabled(marker)); + verify(this.logger); + } + @Test + public void testTraceWithMarkerAndString() { + Marker marker = null; + this.logger.trace(marker,""); + replay(this.logger); + this.slf4jLoggerProxy.trace(marker,""); + verify(this.logger); + } + @Test + public void testTraceWithMarkerStringAndOneObject() { + Marker marker = null; + Object obj = null; + this.logger.trace(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.trace(marker,"",obj); + verify(this.logger); + } + @Test + public void testTraceWithMarkerStringAndTwoObjects() { + Marker marker = null; + Object obj1 = null, obj2 = null; + this.logger.trace(marker,"",obj1, obj2); + replay(this.logger); + this.slf4jLoggerProxy.trace(marker,"",obj1,obj2); + verify(this.logger); + } + @Test + public void testTraceWithMarkerStringAndObjectArray() { + Marker marker = null; + Object[] obj = null; + this.logger.trace(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.trace(marker,"",obj); + verify(this.logger); + } + @Test + public void testTraceWithMarkerStringAndThrowable() { + Marker marker = null; + Throwable t = null; + this.logger.trace(marker,"",t); + replay(this.logger); + this.slf4jLoggerProxy.trace(marker,"",t); + verify(this.logger); + } + @Test + public void testTraceWithString() { + this.logger.trace(""); + replay(this.logger); + this.slf4jLoggerProxy.trace(""); + verify(this.logger); + } + @Test + public void testTraceWithStringAndOneObject() { + Object obj = null; + this.logger.trace("",obj); + replay(this.logger); + this.slf4jLoggerProxy.trace("",obj); + verify(this.logger); + } + @Test + public void testTraceWithStringAndTwoObjects() { + Object obj1 = null, obj2 = null; + this.logger.trace("",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.trace("",obj1,obj2); + verify(this.logger); + } + @Test + public void testTraceWithStringAndObjectArray() { + Object[] obj = null; + this.logger.trace("",obj); + replay(this.logger); + this.slf4jLoggerProxy.trace("",obj); + verify(this.logger); + } + @Test + public void testTraceWithStringAndThrowable() { + Throwable t = null; + this.logger.trace("",t); + replay(this.logger); + this.slf4jLoggerProxy.trace("",t); + verify(this.logger); + } + @Test + public void testWarnWithMarkerAndString() { + Marker marker = null; + this.logger.warn(marker,""); + replay(this.logger); + this.slf4jLoggerProxy.warn(marker,""); + verify(this.logger); + } + @Test + public void testWarnWithMarkerStringAndOneObject() { + Marker marker = null; + Object obj = null; + this.logger.warn(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.warn(marker,"",obj); + verify(this.logger); + } + @Test + public void testWarnWithMarkerStringAndTwoObjects() { + Marker marker = null; + Object obj1 = null, obj2 = null; + this.logger.warn(marker,"",obj1, obj2); + replay(this.logger); + this.slf4jLoggerProxy.warn(marker,"",obj1,obj2); + verify(this.logger); + } + @Test + public void testWarnWithMarkerStringAndObjectArray() { + Marker marker = null; + Object[] obj = null; + this.logger.warn(marker,"",obj); + replay(this.logger); + this.slf4jLoggerProxy.warn(marker,"",obj); + verify(this.logger); + } + @Test + public void testWarnWithMarkerStringAndThrowable() { + Marker marker = null; + Throwable t = null; + this.logger.warn(marker,"",t); + replay(this.logger); + this.slf4jLoggerProxy.warn(marker,"",t); + verify(this.logger); + } + @Test + public void testWarnWithString() { + this.logger.warn(""); + replay(this.logger); + this.slf4jLoggerProxy.warn(""); + verify(this.logger); + } + @Test + public void testWarnWithStringAndOneObject() { + Object obj = null; + this.logger.warn("",obj); + replay(this.logger); + this.slf4jLoggerProxy.warn("",obj); + verify(this.logger); + } + @Test + public void testWarnWithStringAndTwoObjects() { + Object obj1 = null, obj2 = null; + this.logger.warn("",obj1,obj2); + replay(this.logger); + this.slf4jLoggerProxy.warn("",obj1,obj2); + verify(this.logger); + } + @Test + public void testWarnWithStringAndObjectArray() { + Object[] obj = null; + this.logger.warn("",obj); + replay(this.logger); + this.slf4jLoggerProxy.warn("",obj); + verify(this.logger); + } + @Test + public void testWarnWithStringAndThrowable() { + Throwable t = null; + this.logger.warn("",t); + replay(this.logger); + this.slf4jLoggerProxy.warn("",t); + verify(this.logger); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/message/DefaultMessageTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/message/DefaultMessageTest.java new file mode 100644 index 0000000..be2f686 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/message/DefaultMessageTest.java @@ -0,0 +1,328 @@ +/* + * 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 br.gov.frameworkdemoiselle.message; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.Arrays; +import java.util.ResourceBundle; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Strings; + +@Ignore +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class, ResourceBundle.class }) +public class DefaultMessageTest { + + private Message message; + + private String MOCK_RESOURCE_BUNDLE_KEY = "{key}"; + + private String MOCK_RESOURCE_BUNDLE_VALUE = "param {0} and param {1}"; + + private ResourceBundle bundle; + + @Before + public void setUp() throws Exception { + bundle = PowerMock.createMock(ResourceBundle.class); + expect(bundle.getString(MOCK_RESOURCE_BUNDLE_KEY)).andReturn(MOCK_RESOURCE_BUNDLE_VALUE).anyTimes(); + expectPrivate(bundle, "handleGetObject", EasyMock.anyObject(String.class)) + .andReturn(MOCK_RESOURCE_BUNDLE_VALUE).anyTimes(); + + mockStatic(Beans.class); + expect(Beans.getReference(ResourceBundle.class)).andReturn(bundle).anyTimes(); + replayAll(bundle, Beans.class); + } + + @After + public void tearDown() throws Exception { + verifyAll(); + } + + @Test + public void testConstructorWithTextOnly() { + message = new DefaultMessage(""); + assertEquals("", message.getText()); + + message = new DefaultMessage("a"); + assertEquals("a", message.getText()); + + message = new DefaultMessage(null); + assertEquals(null, message.getText()); + + message = new DefaultMessage(MOCK_RESOURCE_BUNDLE_KEY); + assertEquals(MOCK_RESOURCE_BUNDLE_VALUE, message.getText()); + } + + @Test + public void testCachedText() { + message = new DefaultMessage(MOCK_RESOURCE_BUNDLE_KEY); + assertSame(message.getText(), message.getText()); + } + + @Test + public void testDefaultSeverity() { + + message = new DefaultMessage(null); + assertEquals(SeverityType.INFO, message.getSeverity()); + + assertEquals(DefaultMessage.DEFAULT_SEVERITY, message.getSeverity()); + + message = new DefaultMessage(null, null, new Object[] {}); + assertEquals(DefaultMessage.DEFAULT_SEVERITY, message.getSeverity()); + } + + @Test + public void testConstructorWithParametrizedText() { + String text; + Object[] params; + + text = ""; + params = new Object[] { "1", "2" }; + message = new DefaultMessage(text, params); + assertEquals(Strings.getString(text, params), message.getText()); + + text = "params: {0}, {1}"; + params = new Object[] { "1", "2" }; + message = new DefaultMessage(text, params); + assertEquals(Strings.getString(text, params), message.getText()); + + text = null; + params = new Object[] { "1" }; + message = new DefaultMessage(text, params); + assertEquals(Strings.getString(text, params), message.getText()); + + text = MOCK_RESOURCE_BUNDLE_KEY; + params = new Object[] { "1", "2" }; + message = new DefaultMessage(text, params); + assertEquals(Strings.getString(bundle.getString(text), params), message.getText()); + } + + @Test + public void testToString() throws SecurityException, NoSuchFieldException { + String text; + Object[] params; + + text = "text"; + message = new DefaultMessage(text); + assertEquals("DefaultMessage [originalText=" + text + ", parsedText=" + text + ", severity=INFO, params=[]]", + message.toString()); + + text = MOCK_RESOURCE_BUNDLE_KEY; + params = new Object[] { "1", "2" }; + message = new DefaultMessage(text, SeverityType.FATAL, params); + assertEquals( + "DefaultMessage [originalText=" + text + ", parsedText=" + + Strings.getString(bundle.getString(text), params) + ", severity=FATAL, params=" + + Arrays.toString(params) + "]", message.toString()); + } + + @Test + public void testConstructorWithParametrizedTextAndSeverityType() { + message = new DefaultMessage("", SeverityType.FATAL, ""); + assertEquals("", message.getText()); + assertEquals(SeverityType.FATAL, message.getSeverity()); + + message = new DefaultMessage("text", SeverityType.WARN, "param"); + assertEquals("text", message.getText()); + assertEquals(SeverityType.WARN, message.getSeverity()); + } + + enum MessagesEnum implements Message { + + FIRST_KEY("first-key"), SECOND_KEY("second-key", SeverityType.WARN), THIRD_KEY, FOURTH_KEY(SeverityType.FATAL), LITERAL_TEXT( + "This is a literal text"); + + private final DefaultMessage msg; + + MessagesEnum() { + msg = new DefaultMessage(this.name()); + } + + MessagesEnum(String name) { + msg = new DefaultMessage(name); + } + + MessagesEnum(SeverityType severity) { + msg = new DefaultMessage(this.name(), severity); + } + + MessagesEnum(String name, SeverityType severity) { + msg = new DefaultMessage(name, severity); + } + + @Override + public String getText() { + return msg.getText(); + } + + @Override + public SeverityType getSeverity() { + return msg.getSeverity(); + } + + } + + // @Test + public void testMessagesEnum() { + + // bundle = PowerMock.createMock(ResourceBundle.class); + // expect(bundle.getString("first-key")).andReturn("First message text"); + // expect(bundle.getString("second-key")).andReturn("Second message text"); + // expect(bundle.getString("THIRD_KEY")).andReturn("Third message text"); + // expect(bundle.getString("FOURTH_KEY")).andReturn("Fourth message text"); + // replayAll(bundle); + + message = MessagesEnum.FIRST_KEY; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("First message text", message.getText()); + + message = MessagesEnum.SECOND_KEY; + assertEquals(SeverityType.WARN, message.getSeverity()); + assertEquals("Second message text", message.getText()); + + message = MessagesEnum.THIRD_KEY; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("Third message text", message.getText()); + + message = MessagesEnum.FOURTH_KEY; + assertEquals(SeverityType.FATAL, message.getSeverity()); + assertEquals("Fourth message text", message.getText()); + + message = MessagesEnum.LITERAL_TEXT; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("This is a literal text", message.getText()); + } + + enum ErrorMessages implements Message { + + FIRST_ERROR_KEY, SECOND_ERROR_KEY("second-error-key"), LITERAL_ERROR_TEXT("This is a literal error text"); + + private final DefaultMessage msg; + + ErrorMessages() { + msg = new DefaultMessage(this.name(), SeverityType.ERROR); + } + + ErrorMessages(String name) { + msg = new DefaultMessage(name, SeverityType.ERROR); + } + + @Override + public String getText() { + return msg.getText(); + } + + @Override + public SeverityType getSeverity() { + return msg.getSeverity(); + } + + } + + // @Test + public void testErrorMessagesEnum() { + + message = ErrorMessages.FIRST_ERROR_KEY; + assertEquals(SeverityType.ERROR, message.getSeverity()); + assertEquals("First error message text", message.getText()); + + message = ErrorMessages.SECOND_ERROR_KEY; + assertEquals(SeverityType.ERROR, message.getSeverity()); + assertEquals("Second error message text", message.getText()); + + message = ErrorMessages.LITERAL_ERROR_TEXT; + assertEquals(SeverityType.ERROR, message.getSeverity()); + assertEquals("This is a literal error text", message.getText()); + } + + interface MessagesInterface { + + final Message FIRST_KEY = new DefaultMessage("first-key"); + + final Message SECOND_KEY = new DefaultMessage("second-key", SeverityType.WARN); + + final Message THIRD_KEY = new DefaultMessage("THIRD_KEY"); + + final Message FOURTH_KEY = new DefaultMessage("FOURTH_KEY", SeverityType.FATAL); + + final Message LITERAL_TEXT = new DefaultMessage("This is a literal text"); + + } + + // @Test + public void testMessagesInterface() { + + message = MessagesInterface.FIRST_KEY; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("First message text", message.getText()); + + message = MessagesInterface.SECOND_KEY; + assertEquals(SeverityType.WARN, message.getSeverity()); + assertEquals("Second message text", message.getText()); + + message = MessagesInterface.THIRD_KEY; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("Third message text", message.getText()); + + message = MessagesInterface.FOURTH_KEY; + assertEquals(SeverityType.FATAL, message.getSeverity()); + assertEquals("Fourth message text", message.getText()); + + message = MessagesInterface.LITERAL_TEXT; + assertEquals(SeverityType.INFO, message.getSeverity()); + assertEquals("This is a literal text", message.getText()); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/template/DelegateCrudTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/template/DelegateCrudTest.java new file mode 100644 index 0000000..9d11765 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/template/DelegateCrudTest.java @@ -0,0 +1,193 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.List; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Reflections; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Crud.class, Beans.class, Reflections.class }) +public class DelegateCrudTest { + + private DelegateCrud delegateCrud; + + private Crud mockCrud; + + @SuppressWarnings("unchecked") + @Before + public void before() { + delegateCrud = new DelegateCrud(); + mockCrud = PowerMock.createMock(Crud.class); + } + + @SuppressWarnings("unchecked") + @Test + public void testDelete() { + mockStatic(Beans.class); + mockStatic(Reflections.class); + + expect(Reflections.getGenericTypeArgument(EasyMock.anyObject(Class.class), EasyMock.anyInt())).andReturn(null); + expect(Beans.getReference(EasyMock.anyObject(Class.class))).andReturn(mockCrud); + + mockCrud.delete(1L); + replayAll(Reflections.class, Beans.class, mockCrud); + + delegateCrud.delete(1L); + + verifyAll(); + } + + @Test + public void testUpdate() { + Whitebox.setInternalState(delegateCrud, "delegate", mockCrud); + + Contact update = new Contact(); + mockCrud.update(update); + replayAll(mockCrud); + + delegateCrud.update(update); + + verifyAll(); + } + + @Test + public void testInsert() { + Whitebox.setInternalState(delegateCrud, "delegate", mockCrud); + + Contact insert = new Contact(); + mockCrud.insert(insert); + replayAll(mockCrud); + + delegateCrud.insert(insert); + + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testFindAll() { + mockStatic(Beans.class); + mockStatic(Reflections.class); + + expect(Reflections.getGenericTypeArgument(EasyMock.anyObject(Class.class), EasyMock.anyInt())).andReturn(null); + expect(Beans.getReference(EasyMock.anyObject(Class.class))).andReturn(mockCrud); + + List returned = new ArrayList(); + expect(mockCrud.findAll()).andReturn(returned); + replayAll(Reflections.class, Beans.class, mockCrud); + + assertEquals(returned, delegateCrud.findAll()); + + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testLoad() { + mockStatic(Beans.class); + + expect(Beans.getReference(EasyMock.anyObject(Class.class))).andReturn(mockCrud); + + Contact contact = new Contact(); + expect(mockCrud.load(1L)).andReturn(contact); + replayAll(Beans.class, mockCrud); + + Whitebox.setInternalState(delegateCrud, "delegateClass", delegateCrud.getClass(), delegateCrud.getClass()); + + assertEquals(contact, delegateCrud.load(1L)); + verifyAll(); + } + + class Contact { + + private Long id; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } + + @SuppressWarnings("serial") + class Delegated implements Crud { + + @Override + public void delete(Long id) { + } + + @Override + public List findAll() { + return null; + } + + @Override + public void insert(Contact bean) { + } + + @Override + public Contact load(Long id) { + return null; + } + + @Override + public void update(Contact bean) { + } + + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java new file mode 100644 index 0000000..5fd1968 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java @@ -0,0 +1,185 @@ +///* +// * 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 br.gov.frameworkdemoiselle.transaction; +// +//import static junit.framework.Assert.assertEquals; +//import static junit.framework.Assert.assertFalse; +//import static junit.framework.Assert.assertTrue; +//import static junit.framework.Assert.fail; +//import static org.easymock.EasyMock.expect; +//import static org.easymock.EasyMock.replay; +//import static org.easymock.EasyMock.verify; +//import static org.powermock.reflect.Whitebox.setInternalState; +// +//import javax.naming.Context; +//import javax.naming.NamingException; +//import javax.transaction.HeuristicMixedException; +//import javax.transaction.HeuristicRollbackException; +//import javax.transaction.NotSupportedException; +//import javax.transaction.RollbackException; +//import javax.transaction.Status; +//import javax.transaction.SystemException; +//import javax.transaction.UserTransaction; +// +//import org.easymock.EasyMock; +//import org.junit.Before; +//import org.junit.Test; +//import org.powermock.api.easymock.PowerMock; +// +//import br.gov.frameworkdemoiselle.exception.DemoiselleException; +//import br.gov.frameworkdemoiselle.util.ResourceBundle; +// +//public class JTATransactionTest { +// +// private UserTransaction userTransaction; +// private JTATransaction jtaTransaction; +// private Context context; +// private ResourceBundle bundle; +// +// @Before +// public void setUp() throws Exception { +// this.jtaTransaction = new JTATransaction(); +// +// this.userTransaction = EasyMock.createMock(UserTransaction.class); +// +// this.context = EasyMock.createMock(Context.class); +// expect(this.context.lookup("UserTransaction")).andReturn(this.userTransaction); +// replay(this.context); +// setInternalState(this.jtaTransaction, "context", this.context); +// } +// +// @Test +// public void testNamingException() throws Exception{ +// +// this.context = EasyMock.createMock(Context.class); +// expect(this.context.lookup("UserTransaction")).andThrow(new NamingException()); +// replay(this.context); +// setInternalState(this.jtaTransaction, "context", this.context); +// +// this.bundle = PowerMock.createMock(ResourceBundle.class); +// EasyMock.expect(this.bundle.getString("user-transaction-lookup-fail","UserTransaction")).andReturn("teste"); +// PowerMock.replay(this.bundle); +// setInternalState(this.jtaTransaction, "bundle", this.bundle); +// +// try { +// this.jtaTransaction.isMarkedRollback(); +// fail(); +// }catch(DemoiselleException cause) { +// assertTrue(true); +// } +// } +// +// @Test +// public void testIsMarkedRollback() throws SystemException { +// expect(this.userTransaction.getStatus()).andReturn(Status.STATUS_MARKED_ROLLBACK); +// replay(this.userTransaction); +// assertTrue(this.jtaTransaction.isMarkedRollback()); +// verify(this.userTransaction); +// } +// +// @Test +// public void testIsNotMarkedRollback() throws SystemException { +// expect(this.userTransaction.getStatus()).andReturn(2); +// replay(this.userTransaction); +// assertFalse(this.jtaTransaction.isMarkedRollback()); +// verify(this.userTransaction); +// } +// +// @Test +// public void testIsAtive() throws SystemException { +// expect(this.userTransaction.getStatus()).andReturn(Status.STATUS_ACTIVE); +// replay(this.userTransaction); +// assertTrue(this.jtaTransaction.isActive()); +// verify(this.userTransaction); +// } +// +// @Test +// public void testIsNotAtiveButMarkedRollback() throws SystemException { +// expect(this.userTransaction.getStatus()).andReturn(Status.STATUS_MARKED_ROLLBACK).times(2); +// replay(this.userTransaction); +// assertTrue(this.jtaTransaction.isActive()); +// verify(this.userTransaction); +// } +// +// @Test +// public void testBegin() throws NotSupportedException, SystemException { +// this.userTransaction.begin(); +// replay(this.userTransaction); +// this.jtaTransaction.begin(); +// verify(this.userTransaction); +// } +// +// @Test +// public void testCommit() throws SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { +// this.userTransaction.commit(); +// replay(this.userTransaction); +// this.jtaTransaction.commit(); +// verify(this.userTransaction); +// } +// +// @Test +// public void testgetStatus() throws SystemException{ +// expect(this.userTransaction.getStatus()).andReturn(Status.STATUS_MARKED_ROLLBACK); +// replay(this.userTransaction); +// assertEquals(Status.STATUS_MARKED_ROLLBACK,this.jtaTransaction.getStatus()); +// verify(this.userTransaction); +// } +// +// @Test +// public void testRollback() throws SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { +// this.userTransaction.rollback(); +// replay(this.userTransaction); +// this.jtaTransaction.rollback(); +// verify(this.userTransaction); +// } +// +// @Test +// public void testSetRollbackOnly() throws SystemException{ +// this.userTransaction.setRollbackOnly(); +// replay(this.userTransaction); +// this.jtaTransaction.setRollbackOnly(); +// verify(this.userTransaction); +// } +// +// @Test +// public void testSetTransactionTimeout() throws SystemException{ +// this.userTransaction.setTransactionTimeout(0); +// replay(this.userTransaction); +// this.jtaTransaction.setTransactionTimeout(0); +// verify(this.userTransaction); +// } +//} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/util/BeansTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/util/BeansTest.java new file mode 100644 index 0000000..9963ff4 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/util/BeansTest.java @@ -0,0 +1,125 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.HashSet; +import java.util.Set; + +import javax.enterprise.context.spi.Contextual; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; + +import org.easymock.EasyMock; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ BeanManager.class, Bean.class }) +public class BeansTest { + + @SuppressWarnings({ "unchecked", "static-access" }) + @Test + public void testGetReferenceByClass() { + BeanManager beanManager = PowerMock.createMock(BeanManager.class); + + Set> collection = new HashSet>(); + Bean bean = PowerMock.createMock(Bean.class); + collection.add(bean); + + String object = "object"; + + expect(bean.getBeanClass()).andReturn(null); + expect(beanManager.createCreationalContext(EasyMock.anyObject(Contextual.class))).andReturn(null); + expect(beanManager.getBeans(EasyMock.anyObject(Class.class))).andReturn(collection); + expect( + beanManager.getReference(EasyMock.anyObject(Bean.class), EasyMock.anyObject(Class.class), + EasyMock.anyObject(CreationalContext.class))).andReturn(object); + + replayAll(beanManager, bean); + + // We don't need to instantiate utility classes. But if we don't get in this way, we'll not get 100% cobertura. + Beans beans = new Beans(); + beans.setBeanManager(beanManager); + String returned = beans.getReference(String.class); + + assertEquals(returned, object); + assertEquals(beanManager, beans.getBeanManager()); + + verifyAll(); + } + + @SuppressWarnings({ "unchecked", "static-access" }) + @Test + public void testGetReferenceByString() { + BeanManager beanManager = PowerMock.createMock(BeanManager.class); + + Set> collection = new HashSet>(); + Bean bean = PowerMock.createMock(Bean.class); + collection.add(bean); + + String object = "object"; + + expect(bean.getBeanClass()).andReturn(null); + expect(beanManager.createCreationalContext(EasyMock.anyObject(Contextual.class))).andReturn(null); + expect(beanManager.getBeans("something")).andReturn(collection); + expect( + beanManager.getReference(EasyMock.anyObject(Bean.class), EasyMock.anyObject(Class.class), + EasyMock.anyObject(CreationalContext.class))).andReturn(object); + + replayAll(beanManager, bean); + + // We don't need to instantiate utility classes. But if we don't get in this way, we'll not get 100% cobertura. + Beans beans = new Beans(); + beans.setBeanManager(beanManager); + String returned = beans.getReference("something"); + + assertEquals(returned, object); + assertEquals(beanManager, beans.getBeanManager()); + + verifyAll(); + } + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/util/ExceptionsTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/util/ExceptionsTest.java new file mode 100644 index 0000000..7875578 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/util/ExceptionsTest.java @@ -0,0 +1,90 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; + +public class ExceptionsTest { + + @Test + public void testIsApplicationException() { + assertTrue(Exceptions.isApplicationException(new MyException())); + assertFalse(Exceptions.isApplicationException(new Exception())); + } + + @SuppressWarnings("static-access") + @Test + public void testHandleRuntimeException() { + Exceptions exceptions = new Exceptions(); + try { + exceptions.handleToRuntimeException(new SomeRuntimeException()); + fail(); + } catch (Throwable t) { + if ( !RuntimeException.class.isInstance(t) ) { + fail(); + } + } + + try { + exceptions.handleToRuntimeException(new Exception()); + fail(); + } catch (Throwable t) { + if ( !RuntimeException.class.isInstance(t) ) { + fail(); + } + } + + } + +} + +@SuppressWarnings("serial") +@ApplicationException +class MyException extends Exception { + +} + +@SuppressWarnings("serial") +class SomeRuntimeException extends RuntimeException { + +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/util/ReflectionsTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/util/ReflectionsTest.java new file mode 100644 index 0000000..b5d40f2 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/util/ReflectionsTest.java @@ -0,0 +1,58 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ReflectionsTest { + + @Test + public void testGetGenericTypeArgumentClass() { + assertEquals(Long.class, Reflections.getGenericTypeArgument(OtherClass.class, 0)); + assertEquals(String.class, Reflections.getGenericTypeArgument(OtherClass.class, 1)); + } + +} + +class SomeClass { + +} + +class OtherClass extends SomeClass { +} \ No newline at end of file diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/util/ResourceBundleTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/util/ResourceBundleTest.java new file mode 100644 index 0000000..b8dc622 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/util/ResourceBundleTest.java @@ -0,0 +1,92 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class ResourceBundleTest { + + private ResourceBundle resourceBundle; + private transient java.util.ResourceBundle resourceBundleMocked; + + @Before + public void setUp() throws Exception { + this.resourceBundleMocked = PowerMock.createMock(java.util.ResourceBundle.class); + this.resourceBundle = new ResourceBundle(resourceBundleMocked); + } + + @Test + public void testContainsKey() { + expect(this.resourceBundleMocked.containsKey("")).andReturn(true); + replay(this.resourceBundleMocked); + this.resourceBundle.containsKey(""); + verify(this.resourceBundleMocked); + } + + @Test + public void testGetKeys() { + expect(this.resourceBundleMocked.getKeys()).andReturn(null); + replay(this.resourceBundleMocked); + this.resourceBundle.getKeys(); + verify(this.resourceBundleMocked); + } + + @Test + public void testGetLocale() { + expect(this.resourceBundleMocked.getLocale()).andReturn(null); + replay(this.resourceBundleMocked); + this.resourceBundle.getLocale(); + verify(this.resourceBundleMocked); + } + + @Test + public void testKeySet() { + expect(this.resourceBundleMocked.keySet()).andReturn(null); + replay(this.resourceBundleMocked); + this.resourceBundle.keySet(); + verify(this.resourceBundleMocked); + } +} diff --git a/core/src/test/java/br/gov/frameworkdemoiselle/util/StringsTest.java b/core/src/test/java/br/gov/frameworkdemoiselle/util/StringsTest.java new file mode 100644 index 0000000..ba0bb27 --- /dev/null +++ b/core/src/test/java/br/gov/frameworkdemoiselle/util/StringsTest.java @@ -0,0 +1,195 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.lang.reflect.Field; + +import org.easymock.EasyMock; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.annotation.Ignore; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Reflections.class }) +public class StringsTest { + + @Test + public void testGetString() { + testEqualsGetString("teste", "teste"); + testEqualsGetString("", ""); + testEqualsGetString(null, null); + testEqualsGetString(null, null, "teste"); + testEqualsGetString("{0}", "teste", "teste"); + testEqualsGetString("teste", "teste", (Object[]) null); + testEqualsGetString("teste {0}", "teste 1", "1"); + testEqualsGetString("{0} teste", "Um teste", "Um"); + testEqualsGetString("{1} testando {0}", "Apenas testando novamente", "novamente", "Apenas"); + testEqualsGetString("testando {1} novamente", "testando isto novamente", "aquilo", "isto"); + testEqualsGetString("teste", "teste", "1", "2"); + testEqualsGetString("teste {0}.", "teste \\.", "\\"); + } + + @Test + public void testIsEmpty() { + assertTrue(Strings.isEmpty(null)); + assertTrue(Strings.isEmpty("")); + assertTrue(Strings.isEmpty(" ")); + assertTrue(Strings.isEmpty(" ")); + + assertFalse(Strings.isEmpty(" _ ")); + assertFalse(Strings.isEmpty(".")); + assertFalse(Strings.isEmpty("null")); + } + + @Test + public void testIsResourceBundleKeyFormat() { + assertTrue(Strings.isResourceBundleKeyFormat("{x}")); + assertTrue(Strings.isResourceBundleKeyFormat("{.}")); + assertTrue(Strings.isResourceBundleKeyFormat("{*}")); + assertTrue(Strings.isResourceBundleKeyFormat("{$}")); + assertFalse(Strings.isResourceBundleKeyFormat("{}")); + assertFalse(Strings.isResourceBundleKeyFormat("")); + assertFalse(Strings.isResourceBundleKeyFormat(" ")); + assertFalse(Strings.isResourceBundleKeyFormat(null)); + assertFalse(Strings.isResourceBundleKeyFormat("a{a}a")); + assertFalse(Strings.isResourceBundleKeyFormat("a{a}")); + assertFalse(Strings.isResourceBundleKeyFormat("{a}a")); + assertFalse(Strings.isResourceBundleKeyFormat(" {a} ")); + assertFalse(Strings.isResourceBundleKeyFormat("{a")); + assertFalse(Strings.isResourceBundleKeyFormat("a}")); + } + + @Test + public void testCamelCaseToSymbolSeparated() { + assertEquals(null, Strings.camelCaseToSymbolSeparated(null, null)); + assertEquals(null, Strings.camelCaseToSymbolSeparated(null, ".")); + assertEquals("myvar", Strings.camelCaseToSymbolSeparated("myVar", null)); + assertEquals("myvar", Strings.camelCaseToSymbolSeparated("myVar", "")); + assertEquals("my.var", Strings.camelCaseToSymbolSeparated("myVar", ".")); + assertEquals("my-var", Strings.camelCaseToSymbolSeparated("MyVar", "-")); + assertEquals("my?var?name", Strings.camelCaseToSymbolSeparated("myVarName", "?")); + assertEquals("my___var___name", Strings.camelCaseToSymbolSeparated("myVarName", "___")); + } + + @Test + public void testFirstToUpper() { + assertNull(Strings.firstToUpper(null)); + assertEquals("", Strings.firstToUpper("")); + assertEquals("A", Strings.firstToUpper("a")); + assertEquals("A", Strings.firstToUpper("A")); + assertEquals("Ab", Strings.firstToUpper("Ab")); + assertEquals("AB", Strings.firstToUpper("AB")); + assertEquals("Ab", Strings.firstToUpper("ab")); + assertEquals("AB", Strings.firstToUpper("aB")); + } + + @Test + public void testToString() throws SecurityException, NoSuchFieldException { + + @SuppressWarnings("unused") + class Test { + + private String name = "myName"; + + private String lastname = "myLastname"; + + @Ignore + private String ignore = "ignoreMe"; + } + + mockStatic(Reflections.class); + Test test = new Test(); + + expect(Reflections.getNonStaticDeclaredFields(test.getClass())).andReturn(Test.class.getDeclaredFields()); + expect(Reflections.getFieldValue(EasyMock.anyObject(Field.class), EasyMock.anyObject())).andReturn("MyName"); + expect(Reflections.getFieldValue(EasyMock.anyObject(Field.class), EasyMock.anyObject())) + .andReturn("MyLastname"); + expect(Reflections.getFieldValue(EasyMock.anyObject(Field.class), EasyMock.anyObject())).andReturn("Object"); + + replayAll(Reflections.class); + + // FIXME Este this$0=Object não deveria aparecer! + assertEquals("Test [name=MyName, lastname=MyLastname, this$0=Object]", Strings.toString(new Test())); + + verifyAll(); + } + + private void testEqualsGetString(String in, String expected, Object... params) { + String out = Strings.getString(in, params); + assertEquals(expected, out); + } + + @Test + public void testRemoveBraces() { + assertNull(Strings.removeBraces(null)); + assertEquals("", Strings.removeBraces("")); + assertEquals(" ", Strings.removeBraces(" ")); + assertEquals(" {x} ", Strings.removeBraces(" {x} ")); + assertEquals("{x} ", Strings.removeBraces("{x} ")); + assertEquals(" {x}", Strings.removeBraces(" {x}")); + assertEquals("x", Strings.removeBraces("{x}")); + assertEquals("a b c", Strings.removeBraces("{a b c}")); + assertEquals("{}", Strings.removeBraces("{}")); + assertEquals("{}", Strings.removeBraces("{{}}")); + assertEquals("?", Strings.removeBraces("{?}")); + assertEquals("*", Strings.removeBraces("{*}")); + } + + @Test + public void testInsertBraces() { + assertNull(Strings.insertBraces(null)); + assertEquals("", Strings.insertBraces("")); + assertEquals(" ", Strings.insertBraces(" ")); + assertEquals("{ x }", Strings.insertBraces(" x ")); + assertEquals("{ {x} }", Strings.insertBraces(" {x} ")); + assertEquals("{{x}", Strings.insertBraces("{x")); + assertEquals("{*}", Strings.insertBraces("*")); + assertEquals("{?}", Strings.insertBraces("?")); + } +} diff --git a/core/src/test/resources/configuration.properties b/core/src/test/resources/configuration.properties new file mode 100644 index 0000000..27c3d1b --- /dev/null +++ b/core/src/test/resources/configuration.properties @@ -0,0 +1,50 @@ +# 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. + +key=value + +framework.stringValue=value +framework.integerValue=10 +framework.intValue=10 +framework.listValue=value1, value2, value3 + +prefix.key1 = value1 +prefix.key2 = value2 +prefix.key3 = value3 + +interpolation = interx + +#get from var.${interpolation}-${interpolation}.prop +var.interx-interx.prop = value diff --git a/core/src/test/resources/configuration.xml b/core/src/test/resources/configuration.xml new file mode 100644 index 0000000..d473be3 --- /dev/null +++ b/core/src/test/resources/configuration.xml @@ -0,0 +1,47 @@ + + + + + value + 10 + 10 + value1 + value2 + value3 + + \ No newline at end of file diff --git a/core/src/test/resources/configuration2.properties b/core/src/test/resources/configuration2.properties new file mode 100644 index 0000000..2d5e539 --- /dev/null +++ b/core/src/test/resources/configuration2.properties @@ -0,0 +1,36 @@ +# 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. + +key2=value2 \ No newline at end of file diff --git a/core/src/test/resources/demoiselle-core-bundle.properties b/core/src/test/resources/demoiselle-core-bundle.properties new file mode 100644 index 0000000..9a85572 --- /dev/null +++ b/core/src/test/resources/demoiselle-core-bundle.properties @@ -0,0 +1,95 @@ +# 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. + +engine-on=Ligando os motores do Demoiselle ${project.version} +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} +proxy-detected=Detectado o proxy {0} da classe {1} +ambiguous-key=Existe mais de uma chave declarada no arquivo de configura\u00E7\u00E3o para o campo {0} da classe {1}. Indique qual a chave correta utilizando a anota\u00E7\u00E3o Name +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} + +loading-configuration-class=Carregando a classe de configura\u00E7\u00E3o {0} +configuration-field-loaded=Configura\u00E7\u00E3o {0} atribu\u00EDda \u00E0 {1} com o valor {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-key-not-found=Chave de configura\u00E7\u00E3o "{0}" n\u00E3o encontrada. Conven\u00E7\u00F5es verificadas\: "{1}" + +transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo beans.xml +executing-all=Executando todos os \: {0} +custom-context-was-registered=O contexto {0} foi registrado +custom-context-was-unregistered=O contexto {0} foi removido + +error-creating-configuration-from-resource=Error creating configuration from resource named "{0}" +configuration-type-not-implemented-yet=Configuration type "{0}" is not implemented yet +error-converting-to-type=Error converting to type "{0}" +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} +transaction-class-not-found=A classe de transa\u00E7\u00E3o "{0}" informada n\u00E3o foi encontrada. +transaction-class-must-be-of-type=A classe de transa\u00E7\u00E3o "{0}" informada deve ser do tipo {1} +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}] +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 + +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +cleaning-message-context=Limpando o contexto de mensagens +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 estrat\u00E9gia de resolu\u00E7\u00E3o de permiss\u00F5es desejada no arquivo beans.xml +user-not-authenticated=Usu\u00E1rio n\u00E3o autenticado +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} +authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir o mecanismo de autentica\u00E7\u00E3o desejado no arquivo beans.xml \ No newline at end of file diff --git a/core/src/test/resources/demoiselle-core-bundle_pt_BR.properties b/core/src/test/resources/demoiselle-core-bundle_pt_BR.properties new file mode 100644 index 0000000..d9229e3 --- /dev/null +++ b/core/src/test/resources/demoiselle-core-bundle_pt_BR.properties @@ -0,0 +1,95 @@ +# 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. + +engine-on=Ligando os motores do Demoiselle ${project.version} +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} +proxy-detected=Detectado o proxy {0} da classe {1} +ambiguous-key=Existe mais de uma chave declarada no arquivo de configura\u00E7\u00E3o para o campo {0} da classe {1}. Indique qual a chave correta utilizando a anota\u00E7\u00E3o Name +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 inciada +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} + +loading-configuration-class=Carregando a classe de configura\u00E7\u00E3o {0} +configuration-field-loaded=Configura\u00E7\u00E3o {0} atribu\u00EDda \u00E0 {1} com o valor {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-key-not-found=Chave de configura\u00E7\u00E3o "{0}" n\u00E3o encontrada. Conven\u00E7\u00F5es verificadas\: "{1}" + +transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo beans.xml +executing-all=Executando todos os \: {0} +custom-context-was-registered=O contexto {0} foi registrado +custom-context-was-unregistered=O contexto {0} foi removido + +error-creating-configuration-from-resource=Error creating configuration from resource named "{0}" +configuration-type-not-implemented-yet=Configuration type "{0}" is not implemented yet +error-converting-to-type=Error converting to type "{0}" +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} +transaction-class-not-found=A classe de transa\u00E7\u00E3o "{0}" informada n\u00E3o foi encontrada. +transaction-class-must-be-of-type=A classe de transa\u00E7\u00E3o "{0}" informada deve ser do tipo {1} +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}] +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 + +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +cleaning-message-context=Limpando o contexto de mensagens +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 estrat\u00E9gia de resolu\u00E7\u00E3o de permiss\u00F5es desejada no arquivo beans.xml +user-not-authenticated=Usu\u00E1rio n\u00E3o autenticado +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} +authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir o mecanismo de autentica\u00E7\u00E3o desejado no arquivo beans.xml \ No newline at end of file diff --git a/core/src/test/resources/demoiselle.properties b/core/src/test/resources/demoiselle.properties new file mode 100644 index 0000000..eb43e88 --- /dev/null +++ b/core/src/test/resources/demoiselle.properties @@ -0,0 +1,78 @@ +# 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. + +frameworkdemoiselle.core.bootstrap.observed= +frameworkdemoiselle.persistence.unit= + +frameworkdemoiselle.pagination.page_size=50 +frameworkdemoiselle.pagination.max_page_links=10 + +br.gov.frameworkdemoiselle.success=Success +frameworkdemoiselle.configurationtest.nameConfiguration=ConfigurationTest +frameworkdemoiselle.configurationtest.name=ConfigurationTest2 +nameConfiguration=ConfigurationTest +isNameConfiguration=true +byteConfiguration=75 +doubleConfiguration=7.5 +floatConfiguration=0.0f +integerConfiguration=75 +longConfiguration=75 +shortConfiguration=-75 +bigDecimalConfiguration=7.5 +bigIntegerConfiguration=75 +listConfiguration=azul,verde +stringArrayConfiguration=azul,verde +intArrayConfiguration=1,2 +objectConfiguration=null +propertiesConfiguration.valor1=azul +propertiesConfiguration.valor2=verde +fourConfiguration=quatro +four.configuration=quatro +four_configuration=quatro +fourconfiguration=quatro +threeConfiguration=três +three.configuration=três +three_configuration=três +twoConfiguration=dois +two.configuration=dois +typeOneConfiguration=tipo um +type.two.configuration=tipo dois +type_three_configuration=tipo tres +typefourconfiguration=tipo quatro +convention_underline=Convention Underline +convention.dot=Convention Dot +conventionalllowercase=All LowerCase +CONVENTIONALLUPPERCASE=ALL UPPERCASE +complexObject=null \ No newline at end of file diff --git a/core/src/test/resources/demoiselle.xml b/core/src/test/resources/demoiselle.xml new file mode 100644 index 0000000..4efffd1 --- /dev/null +++ b/core/src/test/resources/demoiselle.xml @@ -0,0 +1,53 @@ + + + + All LowerCase + ALL UPPERCASE + Convention_Underline + + convention.dot + + ConfigurationTest +
+ + + ConfigurationTest + + +
+
\ No newline at end of file diff --git a/core/src/test/resources/log4j.properties b/core/src/test/resources/log4j.properties new file mode 100755 index 0000000..48a89ba --- /dev/null +++ b/core/src/test/resources/log4j.properties @@ -0,0 +1,42 @@ +# 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. + +log4j.rootCategory=INFO, stdout + +log4j.logger.br.gov.frameworkdemoiselle=TRACE + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p [%c{1}] %m%n diff --git a/core/src/test/resources/messages.properties b/core/src/test/resources/messages.properties new file mode 100644 index 0000000..a447696 --- /dev/null +++ b/core/src/test/resources/messages.properties @@ -0,0 +1,47 @@ +# 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. + +teste=teste + +# Message test +testGetStringMessageDefaultResourceName.message=Testando mensagens usando o resourceName padrão + +first-key=First message text +second-key=Second message text +THIRD_KEY=Third message text +FOURTH_KEY=Fourth message text + +FIRST_ERROR_KEY=First error message text +second-error-key=Second error message text \ No newline at end of file diff --git a/core/src/test/resources/testGetStringMessage.properties b/core/src/test/resources/testGetStringMessage.properties new file mode 100644 index 0000000..f3146dd --- /dev/null +++ b/core/src/test/resources/testGetStringMessage.properties @@ -0,0 +1,37 @@ +# 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. + +DefaultMessageTest.s1=Rodando {0} para {1} +DefaultMessageTest.no-locale=Usando o locale default \ No newline at end of file diff --git a/core/src/test/resources/testGetStringMessage_en.properties b/core/src/test/resources/testGetStringMessage_en.properties new file mode 100644 index 0000000..fed5586 --- /dev/null +++ b/core/src/test/resources/testGetStringMessage_en.properties @@ -0,0 +1,36 @@ +# 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. + +DefaultMessageTest.s1=Running {0} for {1} \ No newline at end of file diff --git a/core/src/uml/configuration.ucls b/core/src/uml/configuration.ucls new file mode 100644 index 0000000..d053a27 --- /dev/null +++ b/core/src/uml/configuration.ucls @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/controller.ucls b/core/src/uml/controller.ucls new file mode 100644 index 0000000..9857421 --- /dev/null +++ b/core/src/uml/controller.ucls @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/exception.ucls b/core/src/uml/exception.ucls new file mode 100644 index 0000000..27fac86 --- /dev/null +++ b/core/src/uml/exception.ucls @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/injection-bootstrap.ucls b/core/src/uml/injection-bootstrap.ucls new file mode 100644 index 0000000..c0cd9bc --- /dev/null +++ b/core/src/uml/injection-bootstrap.ucls @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/injection-producer.ucls b/core/src/uml/injection-producer.ucls new file mode 100644 index 0000000..4aac609 --- /dev/null +++ b/core/src/uml/injection-producer.ucls @@ -0,0 +1,151 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/lifecycle-shutdown.ucls b/core/src/uml/lifecycle-shutdown.ucls new file mode 100644 index 0000000..d8d9429 --- /dev/null +++ b/core/src/uml/lifecycle-shutdown.ucls @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/lifecycle-startup.ucls b/core/src/uml/lifecycle-startup.ucls new file mode 100644 index 0000000..3790d92 --- /dev/null +++ b/core/src/uml/lifecycle-startup.ucls @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/message.ucls b/core/src/uml/message.ucls new file mode 100644 index 0000000..949690f --- /dev/null +++ b/core/src/uml/message.ucls @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/pagination.ucls b/core/src/uml/pagination.ucls new file mode 100644 index 0000000..b3fe15a --- /dev/null +++ b/core/src/uml/pagination.ucls @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/security-authentication.ucls b/core/src/uml/security-authentication.ucls new file mode 100644 index 0000000..935e6fe --- /dev/null +++ b/core/src/uml/security-authentication.ucls @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/security-authorization.ucls b/core/src/uml/security-authorization.ucls new file mode 100644 index 0000000..33bcfdb --- /dev/null +++ b/core/src/uml/security-authorization.ucls @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/template.ucls b/core/src/uml/template.ucls new file mode 100644 index 0000000..0ababe4 --- /dev/null +++ b/core/src/uml/template.ucls @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/transaction.ucls b/core/src/uml/transaction.ucls new file mode 100644 index 0000000..4e01de1 --- /dev/null +++ b/core/src/uml/transaction.ucls @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/src/uml/util.ucls b/core/src/uml/util.ucls new file mode 100644 index 0000000..ef2eca6 --- /dev/null +++ b/core/src/uml/util.ucls @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/.gitignore b/extension/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/extension/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/extension/jpa/.gitignore b/extension/jpa/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/extension/jpa/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/extension/jpa/pom.xml b/extension/jpa/pom.xml new file mode 100644 index 0000000..47c9efc --- /dev/null +++ b/extension/jpa/pom.xml @@ -0,0 +1,73 @@ + + + + 4.0.0 + + demoiselle-jpa + jar + + + br.gov.frameworkdemoiselle + demoiselle-extension-parent + 2.2.1-SNAPSHOT + ../../parent/extension/pom.xml + + + JPA Extension + + + + + org.eclipse.persistence + javax.persistence + + + + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + \ No newline at end of file diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java new file mode 100644 index 0000000..9fefb52 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java @@ -0,0 +1,61 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +/** + * Configuration class responsible for retrieving specific entity manager parameter values from properties file. + */ +@Configuration(prefix = "frameworkdemoiselle.persistence") +public class EntityManagerConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("unit.name") + private String persistenceUnitName; + + /** + * Getter for persistence unit name. + */ + public String getPersistenceUnitName() { + return persistenceUnitName; + } +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducer.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducer.java new file mode 100644 index 0000000..c65b483 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducer.java @@ -0,0 +1,99 @@ +package br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.slf4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@ApplicationScoped +public class EntityManagerFactoryProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + public static String ENTITY_MANAGER_RESOURCE = "META-INF/persistence.xml"; + + @Inject + private Logger logger; + + @Inject + @Name("demoiselle-jpa-bundle") + private ResourceBundle bundle; + + private final Map cache = Collections + .synchronizedMap(new HashMap()); + + public EntityManagerFactory create(String persistenceUnit) { + EntityManagerFactory factory; + + if (cache.containsKey(persistenceUnit)) { + factory = cache.get(persistenceUnit); + } else { + factory = Persistence.createEntityManagerFactory(persistenceUnit); + cache.put(persistenceUnit, factory); + } + + return factory; + } + + @PostConstruct + public void init() { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + + try { + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document document = documentBuilder.parse(contextClassLoader.getResourceAsStream(ENTITY_MANAGER_RESOURCE)); + NodeList nodes = document.getElementsByTagName("persistence-unit"); + + String persistenceUnit = ""; + for (int index = 0; index < nodes.getLength(); index++) { + Node node = nodes.item(index); + persistenceUnit = ((Element) node).getAttribute("name"); + + if ("".equals(persistenceUnit)) { + throw new DemoiselleException(bundle.getString("can-not-get-persistence-unit-from-persistence")); + } + + create(persistenceUnit); + logger.debug(bundle.getString("persistence-unit-name-found", persistenceUnit)); + } + + } catch (Exception cause) { + String message = bundle.getString("can-not-get-persistence-unit-from-persistence"); + logger.error(message, cause); + + throw new DemoiselleException(message, cause); + } + } + + @PreDestroy + public void close() { + for (EntityManagerFactory factory : cache.values()) { + factory.close(); + } + + cache.clear(); + } + + public Map getCache() { + return cache; + } +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducer.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducer.java new file mode 100644 index 0000000..664b235 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducer.java @@ -0,0 +1,196 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.FlushModeType; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.internal.configuration.EntityManagerConfig; +import br.gov.frameworkdemoiselle.internal.proxy.EntityManagerProxy; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + *

+ * Factory class responsible to produces instances of EntityManager. Produces instances based on informations defined in + * persistence.xml, demoiselle.properties or @PersistenceUnit annotation. + *

+ * TODO allow users to define EntityManager's scope using demoiselle.properties + */ +@RequestScoped +public class EntityManagerProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + private Logger logger; + + @Inject + @Name("demoiselle-jpa-bundle") + private ResourceBundle bundle; + + private final Map cache = Collections.synchronizedMap(new HashMap()); + + @Inject + private EntityManagerFactoryProducer factory; + + /** + *

+ * Default EntityManager factory. Tries two strategies to produces EntityManager instances. + *

  • The first one is based on informations available on demoiselle properties file + * ("frameworkdemoiselle.persistence.unit.name" key).
  • + *
  • The second one is based on persistence.xml file. If exists only one Persistence Unit defined, this one is + * used.
  • + * + * @param config + * Suplies informations about EntityManager defined in properties file. + * @return Produced EntityManager. + */ + @Default + @Produces + public EntityManager create(InjectionPoint ip, EntityManagerConfig config) { + String persistenceUnit = getPersistenceUnit(ip, config); + return new EntityManagerProxy(persistenceUnit); + } + + public EntityManager getEntityManager(String persistenceUnit) { + EntityManager entityManager = null; + + if (cache.containsKey(persistenceUnit)) { + entityManager = cache.get(persistenceUnit); + + } else { + entityManager = factory.create(persistenceUnit).createEntityManager(); + entityManager.setFlushMode(FlushModeType.AUTO); + // entityManager.setFlushMode(FlushModeType.COMMIT); + + cache.put(persistenceUnit, entityManager); + this.logger.info(bundle.getString("entity-manager-was-created", persistenceUnit)); + } + + return entityManager; + } + + private String getPersistenceUnit(InjectionPoint ip, EntityManagerConfig config) { + String persistenceUnitName; + + if (ip != null && ip.getAnnotated().isAnnotationPresent(Name.class)) { + persistenceUnitName = ip.getAnnotated().getAnnotation(Name.class).value(); + + } else { + persistenceUnitName = getFromProperties(config); + + if (persistenceUnitName == null) { + persistenceUnitName = getFromXML(); + } + } + + return persistenceUnitName; + } + + /** + * Tries to get persistence unit name from demoiselle.properties. + * + * @param config + * Configuration containing persistence unit name. + * @return Persistence unit name. + */ + private String getFromProperties(EntityManagerConfig config) { + String persistenceUnit = config.getPersistenceUnitName(); + + if (persistenceUnit != null) { + this.logger.debug(bundle.getString("getting-persistence-unit-from-properties", + Configuration.DEFAULT_RESOURCE)); + } + + return persistenceUnit; + } + + /** + * Uses persistence.xml to get informations about which persistence unit to use. Throws DemoiselleException if + * more than one Persistence Unit is defined. + * + * @return Persistence Unit Name + */ + private String getFromXML() { + Set persistenceUnits = factory.getCache().keySet(); + + if (persistenceUnits.size() > 1) { + throw new DemoiselleException(bundle.getString("more-than-one-persistence-unit-defined", + Name.class.getSimpleName())); + } else { + return persistenceUnits.iterator().next(); + } + } + + @PostConstruct + public void init() { + for (String persistenceUnit : factory.getCache().keySet()) { + getEntityManager(persistenceUnit); + } + } + + @PreDestroy + public void close() { + for (EntityManager entityManager : cache.values()) { + entityManager.close(); + } + + cache.clear(); + } + + public Map getCache() { + return cache; + } +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxy.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxy.java new file mode 100644 index 0000000..e2429f4 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxy.java @@ -0,0 +1,513 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import java.io.Serializable; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; +import javax.persistence.TransactionRequiredException; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.metamodel.Metamodel; + +import br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer; +import br.gov.frameworkdemoiselle.util.Beans; + +/** + * Delegates all operation invocations to the cached EntityManager. + * + * @author CETEC + */ +public class EntityManagerProxy implements EntityManager, Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Persistence unit of the delegated EntityManager. + */ + private String persistenceUnit; + + /** + * Constructor based on persistence unit name. + * + * @param persistenceUnit + */ + public EntityManagerProxy(String persistenceUnit) { + this.persistenceUnit = persistenceUnit; + } + + /** + * Retrieves a EntityManager from the EntityManagerProducer cache. All operations of this proxy are delegated to the + * cached EntityManager. + * + * @return Cached EntityManager + */ + private EntityManager getEntityManagerDelegate() { + EntityManagerProducer emp = Beans.getReference(EntityManagerProducer.class); + return emp.getEntityManager(this.persistenceUnit); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#persist(java.lang.Object) + */ + @Override + public void persist(Object entity) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().persist(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#merge(java.lang.Object) + */ + @Override + public T merge(T entity) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().merge(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#remove(java.lang.Object) + */ + @Override + public void remove(Object entity) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().remove(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#find(java.lang.Class, java.lang.Object) + */ + @Override + public T find(Class entityClass, Object primaryKey) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().find(entityClass, primaryKey); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#find(java.lang.Class, java.lang.Object, java.util.Map) + */ + @Override + public T find(Class entityClass, Object primaryKey, Map properties) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().find(entityClass, primaryKey, properties); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#find(java.lang.Class, java.lang.Object, javax.persistence.LockModeType) + */ + @Override + public T find(Class entityClass, Object primaryKey, LockModeType lockMode) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().find(entityClass, primaryKey, lockMode); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#find(java.lang.Class, java.lang.Object, javax.persistence.LockModeType, + * java.util.Map) + */ + @Override + public T find(Class entityClass, Object primaryKey, LockModeType lockMode, Map properties) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().find(entityClass, primaryKey, lockMode, properties); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getReference(java.lang.Class, java.lang.Object) + */ + @Override + public T getReference(Class entityClass, Object primaryKey) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().getReference(entityClass, primaryKey); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#flush() + */ + @Override + public void flush() { + getEntityManagerDelegate().flush(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#setFlushMode(javax.persistence.FlushModeType) + */ + @Override + public void setFlushMode(FlushModeType flushMode) { + getEntityManagerDelegate().setFlushMode(flushMode); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getFlushMode() + */ + @Override + public FlushModeType getFlushMode() { + return getEntityManagerDelegate().getFlushMode(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#lock(java.lang.Object, javax.persistence.LockModeType) + */ + @Override + public void lock(Object entity, LockModeType lockMode) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().lock(entity, lockMode); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#lock(java.lang.Object, javax.persistence.LockModeType, java.util.Map) + */ + @Override + public void lock(Object entity, LockModeType lockMode, Map properties) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().lock(entity, lockMode, properties); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#refresh(java.lang.Object) + */ + @Override + public void refresh(Object entity) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().refresh(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#refresh(java.lang.Object, java.util.Map) + */ + @Override + public void refresh(Object entity, Map properties) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().refresh(entity, properties); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#refresh(java.lang.Object, javax.persistence.LockModeType) + */ + @Override + public void refresh(Object entity, LockModeType lockMode) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().refresh(entity, lockMode); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#refresh(java.lang.Object, javax.persistence.LockModeType, java.util.Map) + */ + @Override + public void refresh(Object entity, LockModeType lockMode, Map properties) { + joinTransactionIfNecessary(); + getEntityManagerDelegate().refresh(entity, lockMode, properties); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#clear() + */ + @Override + public void clear() { + getEntityManagerDelegate().clear(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#detach(java.lang.Object) + */ + @Override + public void detach(Object entity) { + getEntityManagerDelegate().detach(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#contains(java.lang.Object) + */ + @Override + public boolean contains(Object entity) { + return getEntityManagerDelegate().contains(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getLockMode(java.lang.Object) + */ + @Override + public LockModeType getLockMode(Object entity) { + joinTransactionIfNecessary(); + return getEntityManagerDelegate().getLockMode(entity); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#setProperty(java.lang.String, java.lang.Object) + */ + @Override + public void setProperty(String propertyName, Object value) { + getEntityManagerDelegate().setProperty(propertyName, value); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getProperties() + */ + @Override + public Map getProperties() { + return getEntityManagerDelegate().getProperties(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createQuery(java.lang.String) + */ + @Override + public Query createQuery(String qlString) { + return new QueryProxy(getEntityManagerDelegate().createQuery(qlString) , this) ; + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createQuery(javax.persistence.criteria.CriteriaQuery) + */ + @Override + public TypedQuery createQuery(CriteriaQuery criteriaQuery) { + return new TypedQueryProxy( getEntityManagerDelegate().createQuery(criteriaQuery) , this ); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createQuery(java.lang.String, java.lang.Class) + */ + @Override + public TypedQuery createQuery(String qlString, Class resultClass) { + return new TypedQueryProxy(getEntityManagerDelegate().createQuery(qlString, resultClass),this); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createNamedQuery(java.lang.String) + */ + @Override + public Query createNamedQuery(String name) { + return new QueryProxy(getEntityManagerDelegate().createNamedQuery(name), this); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createNamedQuery(java.lang.String, java.lang.Class) + */ + @Override + public TypedQuery createNamedQuery(String name, Class resultClass) { + return getEntityManagerDelegate().createNamedQuery(name, resultClass); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String) + */ + @Override + public Query createNativeQuery(String sqlString) { + return new QueryProxy(getEntityManagerDelegate().createNativeQuery(sqlString), this); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String, java.lang.Class) + */ + @Override + public Query createNativeQuery(String sqlString, @SuppressWarnings("rawtypes") Class resultClass) { + return new QueryProxy(getEntityManagerDelegate().createNativeQuery(sqlString, resultClass), this); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String, java.lang.String) + */ + @Override + public Query createNativeQuery(String sqlString, String resultSetMapping) { + return new QueryProxy(getEntityManagerDelegate().createNativeQuery(sqlString, resultSetMapping),this); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#joinTransaction() + */ + @Override + public void joinTransaction() { + getEntityManagerDelegate().joinTransaction(); + } + + /** + * Attemp to join transaction, if the active transaction is not managed by current EntityManager. + */ + protected final void joinTransactionIfNecessary() { + try { + getEntityManagerDelegate().getTransaction(); + } catch (IllegalStateException cause) { + //IllegalStateException is launched if we are on a JTA entity manager, so + //we assume we need to join transaction instead of creating one. + + try{ + getEntityManagerDelegate().joinTransaction(); + } + catch(TransactionRequiredException te){ + //It get's launched if there is no JTA transaction opened. It usually means we are + //being launched inside a method not marked with @Transactional so we ignore the exception. + } + } + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#unwrap(java.lang.Class) + */ + @Override + public T unwrap(Class cls) { + return getEntityManagerDelegate().unwrap(cls); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getDelegate() + */ + @Override + public Object getDelegate() { + return getEntityManagerDelegate().getDelegate(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#close() + */ + @Override + public void close() { + getEntityManagerDelegate().close(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#isOpen() + */ + @Override + public boolean isOpen() { + return getEntityManagerDelegate().isOpen(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getTransaction() + */ + @Override + public EntityTransaction getTransaction() { + return getEntityManagerDelegate().getTransaction(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getEntityManagerFactory() + */ + @Override + public EntityManagerFactory getEntityManagerFactory() { + return getEntityManagerDelegate().getEntityManagerFactory(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getCriteriaBuilder() + */ + @Override + public CriteriaBuilder getCriteriaBuilder() { + return getEntityManagerDelegate().getCriteriaBuilder(); + } + + /* + * (non-Javadoc) + * @see javax.persistence.EntityManager#getMetamodel() + */ + @Override + public Metamodel getMetamodel() { + return getEntityManagerDelegate().getMetamodel(); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object arg0) { + return getEntityManagerDelegate().equals(arg0); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return getEntityManagerDelegate().hashCode(); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return getEntityManagerDelegate().toString(); + } +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/QueryProxy.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/QueryProxy.java new file mode 100644 index 0000000..07b0bd3 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/QueryProxy.java @@ -0,0 +1,179 @@ +package br.gov.frameworkdemoiselle.internal.proxy; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Parameter; +import javax.persistence.Query; +import javax.persistence.TemporalType; + +public class QueryProxy implements Query { + + private Query queryDelegate; + private EntityManagerProxy entityManagerCaller; + + public QueryProxy(Query queryDelegate,EntityManagerProxy entityManagerCaller){ + this.queryDelegate = queryDelegate; + this.entityManagerCaller = entityManagerCaller; + } + + @SuppressWarnings("rawtypes") + public List getResultList() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.getResultList(); + } + + public Object getSingleResult() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.getSingleResult(); + } + + public int executeUpdate() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.executeUpdate(); + } + + public Query setMaxResults(int maxResult) { + queryDelegate.setMaxResults(maxResult); + return this; + } + + public int getMaxResults() { + return queryDelegate.getMaxResults(); + } + + public Query setFirstResult(int startPosition) { + queryDelegate.setFirstResult(startPosition); + return this; + } + + public int getFirstResult() { + return queryDelegate.getFirstResult(); + } + + public Query setHint(String hintName, Object value) { + queryDelegate.setHint(hintName, value); + return this; + } + + public Map getHints() { + return queryDelegate.getHints(); + } + + public Query setParameter(Parameter param, T value) { + queryDelegate.setParameter(param, value); + return this; + } + + public Query setParameter(Parameter param, Calendar value, + TemporalType temporalType) { + queryDelegate.setParameter(param, value, temporalType); + return this; + } + + public Query setParameter(Parameter param, Date value, + TemporalType temporalType) { + queryDelegate.setParameter(param, value, temporalType); + return this; + } + + public Query setParameter(String name, Object value) { + queryDelegate.setParameter(name, value); + return this; + } + + public Query setParameter(String name, Calendar value, + TemporalType temporalType) { + queryDelegate.setParameter(name, value, temporalType); + return this; + } + + public Query setParameter(String name, Date value, TemporalType temporalType) { + queryDelegate.setParameter(name, value, temporalType); + return this; + } + + public Query setParameter(int position, Object value) { + queryDelegate.setParameter(position, value); + return this; + } + + public Query setParameter(int position, Calendar value, + TemporalType temporalType) { + queryDelegate.setParameter(position, value, temporalType); + return this; + } + + public Query setParameter(int position, Date value, + TemporalType temporalType) { + queryDelegate.setParameter(position, value, temporalType); + return this; + } + + public Set> getParameters() { + return queryDelegate.getParameters(); + } + + public Parameter getParameter(String name) { + return queryDelegate.getParameter(name); + } + + public Parameter getParameter(String name, Class type) { + return queryDelegate.getParameter(name, type); + } + + public Parameter getParameter(int position) { + return queryDelegate.getParameter(position); + } + + public Parameter getParameter(int position, Class type) { + return queryDelegate.getParameter(position, type); + } + + public boolean isBound(Parameter param) { + return queryDelegate.isBound(param); + } + + public T getParameterValue(Parameter param) { + return queryDelegate.getParameterValue(param); + } + + public Object getParameterValue(String name) { + return queryDelegate.getParameterValue(name); + } + + public Object getParameterValue(int position) { + return queryDelegate.getParameterValue(position); + } + + public Query setFlushMode(FlushModeType flushMode) { + queryDelegate.setFlushMode(flushMode); + return this; + } + + public FlushModeType getFlushMode() { + return queryDelegate.getFlushMode(); + } + + public Query setLockMode(LockModeType lockMode) { + entityManagerCaller.joinTransactionIfNecessary(); + queryDelegate.setLockMode(lockMode); + return this; + } + + public LockModeType getLockMode() { + return queryDelegate.getLockMode(); + } + + public T unwrap(Class cls) { + return queryDelegate.unwrap(cls); + } + + + +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/TypedQueryProxy.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/TypedQueryProxy.java new file mode 100644 index 0000000..11e4a51 --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/TypedQueryProxy.java @@ -0,0 +1,179 @@ +package br.gov.frameworkdemoiselle.internal.proxy; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Parameter; +import javax.persistence.TemporalType; +import javax.persistence.TypedQuery; + +public class TypedQueryProxy implements TypedQuery { + + private TypedQuery queryDelegate; + private EntityManagerProxy entityManagerCaller; + + public TypedQueryProxy(TypedQuery queryDelegate, + EntityManagerProxy entityManagerCaller) { + this.queryDelegate = queryDelegate; + this.entityManagerCaller = entityManagerCaller; + } + + public List getResultList() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.getResultList(); + } + + public X getSingleResult() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.getSingleResult(); + } + + public int executeUpdate() { + entityManagerCaller.joinTransactionIfNecessary(); + return queryDelegate.executeUpdate(); + } + + public TypedQuery setMaxResults(int maxResult) { + queryDelegate.setMaxResults(maxResult); + return this; + } + + public TypedQuery setFirstResult(int startPosition) { + queryDelegate.setFirstResult(startPosition); + return this; + } + + public TypedQuery setHint(String hintName, Object value) { + queryDelegate.setHint(hintName, value); + return this; + } + + public int getMaxResults() { + return queryDelegate.getMaxResults(); + } + + public TypedQuery setParameter(Parameter param, T value) { + queryDelegate.setParameter(param, value); + return this; + } + + public int getFirstResult() { + return queryDelegate.getFirstResult(); + } + + public TypedQuery setParameter(Parameter param, + Calendar value, TemporalType temporalType) { + queryDelegate.setParameter(param, value, temporalType); + return this; + } + + public TypedQuery setParameter(Parameter param, Date value, + TemporalType temporalType) { + queryDelegate.setParameter(param, value, temporalType); + return this; + } + + public Map getHints() { + return queryDelegate.getHints(); + } + + public TypedQuery setParameter(String name, Object value) { + queryDelegate.setParameter(name, value); + return this; + } + + public TypedQuery setParameter(String name, Calendar value, + TemporalType temporalType) { + queryDelegate.setParameter(name, value, temporalType); + return this; + } + + public TypedQuery setParameter(String name, Date value, + TemporalType temporalType) { + queryDelegate.setParameter(name, value, temporalType); + return this; + } + + public TypedQuery setParameter(int position, Object value) { + queryDelegate.setParameter(position, value); + return this; + } + + public TypedQuery setParameter(int position, Calendar value, + TemporalType temporalType) { + queryDelegate.setParameter(position, value, temporalType); + return this; + } + + public TypedQuery setParameter(int position, Date value, + TemporalType temporalType) { + queryDelegate.setParameter(position, value, temporalType); + return this; + } + + public TypedQuery setFlushMode(FlushModeType flushMode) { + queryDelegate.setFlushMode(flushMode); + return this; + } + + public TypedQuery setLockMode(LockModeType lockMode) { + queryDelegate.setLockMode(lockMode); + return this; + } + + public Set> getParameters() { + return queryDelegate.getParameters(); + } + + public Parameter getParameter(String name) { + return queryDelegate.getParameter(name); + } + + public Parameter getParameter(String name, Class type) { + return queryDelegate.getParameter(name, type); + } + + public Parameter getParameter(int position) { + return queryDelegate.getParameter(position); + } + + public Parameter getParameter(int position, Class type) { + return queryDelegate.getParameter(position, type); + } + + public boolean isBound(Parameter param) { + return queryDelegate.isBound(param); + } + + public T getParameterValue(Parameter param) { + return queryDelegate.getParameterValue(param); + } + + public Object getParameterValue(String name) { + return queryDelegate.getParameterValue(name); + } + + public Object getParameterValue(int position) { + return queryDelegate.getParameterValue(position); + } + + public FlushModeType getFlushMode() { + return queryDelegate.getFlushMode(); + } + + public LockModeType getLockMode() { + return queryDelegate.getLockMode(); + } + + public T unwrap(Class cls) { + return queryDelegate.unwrap(cls); + } + + + +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/JPACrud.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/JPACrud.java new file mode 100644 index 0000000..3ba61cc --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/template/JPACrud.java @@ -0,0 +1,253 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import javax.enterprise.inject.Instance; +import javax.inject.Inject; +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.EntityManager; +import javax.persistence.Enumerated; +import javax.persistence.Query; +import javax.persistence.TransactionRequiredException; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.transaction.Transactional; +import br.gov.frameworkdemoiselle.util.Reflections; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * JPA specific implementation for Crud interface. + * + * @param + * bean object type + * @param + * bean id type + * @author SERPRO + * @see Crud + */ +public class JPACrud implements Crud { + + private static final long serialVersionUID = 1L; + + @Inject + private EntityManager entityManager; + + @Inject + private Instance paginationContext; + + private Pagination pagination; + + @Inject + @Name("demoiselle-jpa-bundle") + private Instance bundle; + + private Class beanClass; + + protected Class getBeanClass() { + + if (this.beanClass == null) { + this.beanClass = Reflections.getGenericTypeArgument(this.getClass(), 0); + } + + return this.beanClass; + } + + protected CriteriaBuilder getCriteriaBuilder() { + return getEntityManager().getCriteriaBuilder(); + } + + protected EntityManager getEntityManager() { + return this.entityManager; + } + + protected Pagination getPagination() { + if (pagination == null) { + PaginationContext context = paginationContext.get(); + pagination = context.getPagination(getBeanClass()); + } + return pagination; + } + + protected CriteriaQuery createCriteriaQuery() { + return getCriteriaBuilder().createQuery(getBeanClass()); + } + + protected Query createQuery(final String ql) { + return getEntityManager().createQuery(ql); + } + + protected void handleException(Throwable cause) throws Throwable { + if (cause instanceof TransactionRequiredException) { + String message = bundle.get().getString("no-transaction-active", "frameworkdemoiselle.transaction.class", + Configuration.DEFAULT_RESOURCE); + throw new DemoiselleException(message, cause); + + } else { + throw cause; + } + } + + @Override + @Transactional + public void insert(final T entity) { + getEntityManager().persist(entity); + } + + @Override + @Transactional + public void delete(final I id) { + T entity = getEntityManager().getReference(getBeanClass(), id); + getEntityManager().remove(entity); + } + + @Override + @Transactional + public void update(final T entity) { + getEntityManager().merge(entity); + } + + @Override + public T load(final Object id) { + return getEntityManager().find(getBeanClass(), id); + } + + @Override + @SuppressWarnings("unchecked") + public List findAll() { + final String jpql = "select this from " + getBeanClass().getSimpleName() + " this"; + final Query query = getEntityManager().createQuery(jpql); + + final Pagination pagination = getPagination(); + if (pagination != null) { + pagination.setTotalResults(this.countAll().intValue()); + query.setFirstResult(pagination.getFirstResult()); + query.setMaxResults(pagination.getPageSize()); + } + + List lista = query.getResultList(); + return lista; + } + + /** + * Retrieves the number of persisted objects for the current class type. + * + * @return the row count + */ + private Long countAll() { + final Query query = getEntityManager().createQuery( + "select count(this) from " + beanClass.getSimpleName() + " this"); + return (Long) query.getSingleResult(); + } + + /** + * Retrieves a list of entities based on a single example instance of it. + *

    + * See below a sample of its usage: + * + *

    +	 * Employee example = new Employee();
    +	 * example.setId(12345);
    +	 * return (List<Employee>) findByExample(example);
    +	 * 
    + * + * @param example + * an entity example + * @return a list of entities + */ + protected List findByExample(final T example) { + final CriteriaQuery criteria = createCriteriaByExample(example); + return getEntityManager().createQuery(criteria).getResultList(); + } + + /** + * Support method which will be used for construction of criteria-based queries. + * + * @param example + * an example of the given entity + * @return an instance of {@code CriteriaQuery} + */ + private CriteriaQuery createCriteriaByExample(final T example) { + + final CriteriaBuilder builder = getCriteriaBuilder(); + final CriteriaQuery query = builder.createQuery(getBeanClass()); + final Root entity = query.from(getBeanClass()); + + final List predicates = new ArrayList(); + final Field[] fields = example.getClass().getDeclaredFields(); + + for (Field field : fields) { + + if (!field.isAnnotationPresent(Column.class) && !field.isAnnotationPresent(Basic.class) + && !field.isAnnotationPresent(Enumerated.class)) { + continue; + } + + Object value = null; + + try { + field.setAccessible(true); + value = field.get(example); + } catch (IllegalArgumentException e) { + continue; + } catch (IllegalAccessException e) { + continue; + } + + if (value == null) { + continue; + } + + final Predicate pred = builder.equal(entity.get(field.getName()), value); + predicates.add(pred); + } + return query.where(predicates.toArray(new Predicate[0])).select(entity); + } + +} diff --git a/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/transaction/JPATransaction.java b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/transaction/JPATransaction.java new file mode 100644 index 0000000..d6720ab --- /dev/null +++ b/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/transaction/JPATransaction.java @@ -0,0 +1,146 @@ +/* + * 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 br.gov.frameworkdemoiselle.transaction; + +import java.util.Collection; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Alternative; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; + +import br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer; + +/** + * Represents the strategy destinated to manage JPA transactions. + * + * @author SERPRO + * @see Transaction + */ +@Alternative +@RequestScoped +public class JPATransaction implements Transaction { + + private static final long serialVersionUID = 1L; + + @Inject + private EntityManagerProducer producer; + + public Collection getDelegate() { + return producer.getCache().values(); + } + + @Override + public void begin() { + EntityTransaction transaction; + for (EntityManager entityManager : getDelegate()) { + transaction = entityManager.getTransaction(); + + if (!transaction.isActive()) { + transaction.begin(); + } + } + } + + @Override + public void commit() { + EntityTransaction transaction; + for (EntityManager entityManager : getDelegate()) { + transaction = entityManager.getTransaction(); + + if (transaction.isActive()) { + transaction.commit(); + } + } + } + + @Override + public void rollback() { + EntityTransaction transaction; + for (EntityManager entityManager : getDelegate()) { + transaction = entityManager.getTransaction(); + + if (transaction.isActive()) { + transaction.rollback(); + } + } + } + + @Override + public void setRollbackOnly() { + EntityTransaction transaction; + for (EntityManager entityManager : getDelegate()) { + transaction = entityManager.getTransaction(); + + if (transaction.isActive()) { + transaction.setRollbackOnly(); + } + } + } + + @Override + public boolean isActive() { + boolean active = false; + + for (EntityManager entityManager : getDelegate()) { + if (entityManager.getTransaction().isActive()) { + active = true; + break; + } + } + + return active; + } + + @Override + public boolean isMarkedRollback() { + boolean rollbackOnly = false; + + EntityTransaction transaction; + for (EntityManager entityManager : getDelegate()) { + transaction = entityManager.getTransaction(); + + if (transaction.isActive() && transaction.getRollbackOnly()) { + rollbackOnly = true; + break; + } + } + + return rollbackOnly; + } +} diff --git a/extension/jpa/src/main/resources/META-INF/beans.xml b/extension/jpa/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..527e828 --- /dev/null +++ b/extension/jpa/src/main/resources/META-INF/beans.xml @@ -0,0 +1,40 @@ + + + + \ No newline at end of file diff --git a/extension/jpa/src/main/resources/demoiselle-jpa-bundle.properties b/extension/jpa/src/main/resources/demoiselle-jpa-bundle.properties new file mode 100644 index 0000000..9dde8ee --- /dev/null +++ b/extension/jpa/src/main/resources/demoiselle-jpa-bundle.properties @@ -0,0 +1,44 @@ +# 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. + +entity-manager-was-created=Gerenciador de entidades criado a partir da unidade de persist\u00EAncia "{0}". +operation-not-supported=Esta operação não é suportada. +getting-persistence-unit-from-properties=Obtendo a unidade de persist\u00EAncia a partir do arquivo de configura\u00E7\u00E3o "{0}". +getting-persistence-unit-from-persistence=Obtendo a unidade de persist\u00EAncia a partir do arquivo "persistence.xml". +can-not-get-persistence-unit-from-persistence=N\u00E3o foi poss\u00EDvel obter a unidade de persist\u00EAncia a partir do arquivo "persistence.xml". +more-than-one-persistence-unit-defined=Existe mais de uma unidade de persist\u00EAncia definida. Utilize @{0} no ponto de inje\u00E7\u00E3o ou defina o atributo "frameworkdemoiselle.persistence.unit.name" no arquivo demoiselle.properties. +persistence-unit-name-found=Unidade de persist\u00EAncia "{0}" encontrada. +entity-manager-closed=O gerenciador de entidades foi fechado. +no-transaction-active=Nenhuma transa\u00E7\u00E3o est\u00E1 ativa, verifique a configura\u00E7\u00E3o "{0}" no arquivo "{1}" e defina a sua estrat\u00E9gia de transa\u00E7\u00E3o. \ No newline at end of file diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfigTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfigTest.java new file mode 100644 index 0000000..93ab15e --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfigTest.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 br.gov.frameworkdemoiselle.internal.configuration; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.mockStatic; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.bootstrap.CoreBootstrap; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +/** + * @author e-saito + */ +/** + * @author 80342167553 + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(CoreBootstrap.class) +public class EntityManagerConfigTest { + + private EntityManagerConfig config = new EntityManagerConfig(); + + @Before + public void setUp() throws Exception { + Logger logger = PowerMock.createMock(Logger.class); + ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle"));; + + ConfigurationLoader configurationLoader = new ConfigurationLoader(); + + Whitebox.setInternalState(configurationLoader, "bundle", bundle); + Whitebox.setInternalState(configurationLoader, "logger", logger); + + mockStatic(CoreBootstrap.class); + expect(CoreBootstrap.isAnnotatedType(config.getClass())).andReturn(true); + PowerMock.replay(CoreBootstrap.class); + + configurationLoader.load(config); + } + + @After + public void tearDown() throws Exception { + config = null; + } + + /** + * Test method for + * {@link br.gov.frameworkdemoiselle.internal.configuration.EntityManagerConfig#getPersistenceUnitName()}. + */ + @Test + public void testGetPersistenceUnitName() { + assertEquals("PersistenceUnitName", config.getPersistenceUnitName()); + } +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducerTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducerTest.java new file mode 100644 index 0000000..4152c1d --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerFactoryProducerTest.java @@ -0,0 +1,101 @@ +package br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.verify; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.reflect.Whitebox.setInternalState; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(Persistence.class) +public class EntityManagerFactoryProducerTest { + + private EntityManagerFactory emFactory; + private EntityManagerFactoryProducer producer; + private Map cache; + private Logger logger; + private ResourceBundle bundle; + + @Before + public void setUp() { + logger = createMock(Logger.class); + bundle = new ResourceBundleProducer().create("demoiselle-jpa-bundle"); + producer = new EntityManagerFactoryProducer(); + cache = Collections.synchronizedMap(new HashMap()); + setInternalState(producer, Map.class, cache); + setInternalState(producer, Logger.class, logger); + setInternalState(producer, ResourceBundle.class, bundle); + emFactory = createMock(EntityManagerFactory.class); + } + + @Test + public void testCreateWithUnitPersistenceExisting() { + cache.put("pu1", emFactory); + Assert.assertEquals(emFactory, producer.create("pu1")); + } + + @Test + public void testCreateWithUnitPersistenceNotExisting() { + + mockStatic(Persistence.class); + expect(Persistence.createEntityManagerFactory("pu1")).andReturn(emFactory); + + replay(Persistence.class); + + Assert.assertEquals(emFactory, producer.create("pu1")); + } + + @Test + public void testInitWithoutError() { + mockStatic(Persistence.class); + expect(Persistence.createEntityManagerFactory("pu1")).andReturn(emFactory); + replay(Persistence.class); + + producer.init(); + Assert.assertEquals(emFactory, cache.get("pu1")); + } + + @Test + public void testInitWithError() { + try { + producer.init(); + Assert.fail(); + }catch(DemoiselleException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testGetCache() { + Assert.assertEquals(cache, producer.getCache()); + } + + @Test + public void testClose() { + cache.put("pu1", emFactory); + emFactory.close(); + replay(emFactory); + producer.close(); + verify(emFactory); + } +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducerTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducerTest.java new file mode 100644 index 0000000..20a875f --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/EntityManagerProducerTest.java @@ -0,0 +1,190 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertNotNull; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.reflect.Whitebox.setInternalState; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.inject.spi.Annotated; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.Assert; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.internal.configuration.EntityManagerConfig; +import br.gov.frameworkdemoiselle.internal.proxy.EntityManagerProxy; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(Persistence.class) +public class EntityManagerProducerTest { + + private EntityManagerProducer producer; + + private Logger logger; + + private ResourceBundle bundle; + + private InjectionPoint ip; + + private EntityManagerConfig config; + + private Annotated annotated; + + private Name name; + + private EntityManagerFactory emf; + + private Map cache; + + private EntityManager em; + + @Before + public void setUp() { + emf = createMock(EntityManagerFactory.class); + em = createMock(EntityManager.class); + + mockStatic(Persistence.class); + expect(Persistence.createEntityManagerFactory("pu1")).andReturn(emf); + expect(emf.createEntityManager()).andReturn(em); + + replay(emf, Persistence.class); + + producer = new EntityManagerProducer(); + bundle = new ResourceBundleProducer().create("demoiselle-jpa-bundle"); + logger = createMock(Logger.class); + + setInternalState(producer, ResourceBundle.class, bundle); + setInternalState(producer, Logger.class, logger); + + ip = createMock(InjectionPoint.class); + config = createMock(EntityManagerConfig.class); + annotated = createMock(Annotated.class); + } + + @Test + public void testClose() { + em.close(); + replay(em); + cache = Collections.synchronizedMap(new HashMap()); + cache.put("pu1", em); + setInternalState(producer, Map.class, cache); + producer.close(); + verify(em); + } + + @Test + public void testGetCache() { + cache = Collections.synchronizedMap(new HashMap()); + setInternalState(producer, Map.class, cache); + Assert.assertEquals(cache, producer.getCache()); + } + + @After + public void tearDown() { + producer = null; + } + + @Test + public void testCreateWithEntityManagerAnnotatedWithName() { + name = createMock(Name.class); + expect(name.value()).andReturn("pu1"); + expect(annotated.isAnnotationPresent(Name.class)).andReturn(true); + expect(annotated.getAnnotation(Name.class)).andReturn(name); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + replay(name, annotated, ip); + + EntityManagerProxy entityManagerProxy = (EntityManagerProxy) producer.create(ip, config); + assertNotNull(entityManagerProxy); + } + + @Test + public void testCreateWithPersistenceUnitNameFromDemoiselleProperties() { + expect(annotated.isAnnotationPresent(Name.class)).andReturn(false); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + expect(config.getPersistenceUnitName()).andReturn("pu1"); + + replay(annotated, ip, config); + + EntityManagerProxy entityManagerProxy = (EntityManagerProxy) producer.create(ip, config); + assertNotNull(entityManagerProxy); + } + + @Test + public void testCreateWithPersistenceUnitNameFromPersistenceXML() { + + Map cache = Collections + .synchronizedMap(new HashMap()); + + cache.put("pu1", emf); + + EntityManagerFactoryProducer entityManagerFactoryProducer = createMock(EntityManagerFactoryProducer.class); + + expect(entityManagerFactoryProducer.getCache()).andReturn(cache); + + expect(annotated.isAnnotationPresent(Name.class)).andReturn(false); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + expect(config.getPersistenceUnitName()).andReturn(null); + + replay(annotated, ip, config, entityManagerFactoryProducer); + + setInternalState(producer, EntityManagerFactoryProducer.class, entityManagerFactoryProducer); + + EntityManagerProxy entityManagerProxy = (EntityManagerProxy) producer.create(ip, config); + assertNotNull(entityManagerProxy); + } +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FakeEntityManager.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FakeEntityManager.java new file mode 100644 index 0000000..23f4761 --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FakeEntityManager.java @@ -0,0 +1,275 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.metamodel.Metamodel; + +public class FakeEntityManager implements EntityManager { + + private boolean closed = false; + + private boolean equals = true; + + private int hashCode = 1; + + private String toString = ""; + + @Override + public void clear() { + } + + @Override + public void close() { + closed = true; + } + + @Override + public boolean contains(Object arg0) { + return false; + } + + @Override + public Query createNamedQuery(String arg0) { + return null; + } + + @Override + public TypedQuery createNamedQuery(String arg0, Class arg1) { + return null; + } + + @Override + public Query createNativeQuery(String arg0) { + return null; + } + + @Override + public Query createNativeQuery(String arg0, @SuppressWarnings("rawtypes") Class arg1) { + return null; + } + + @Override + public Query createNativeQuery(String arg0, String arg1) { + return null; + } + + @Override + public Query createQuery(String arg0) { + return null; + } + + @Override + public TypedQuery createQuery(CriteriaQuery arg0) { + return null; + } + + @Override + public TypedQuery createQuery(String arg0, Class arg1) { + return null; + } + + @Override + public void detach(Object arg0) { + } + + @Override + public T find(Class arg0, Object arg1) { + return null; + } + + @Override + public T find(Class arg0, Object arg1, Map arg2) { + return null; + } + + @Override + public T find(Class arg0, Object arg1, LockModeType arg2) { + return null; + } + + @Override + public T find(Class arg0, Object arg1, LockModeType arg2, Map arg3) { + return null; + } + + @Override + public void flush() { + } + + @Override + public CriteriaBuilder getCriteriaBuilder() { + return null; + } + + @Override + public Object getDelegate() { + return null; + } + + @Override + public EntityManagerFactory getEntityManagerFactory() { + return null; + } + + @Override + public FlushModeType getFlushMode() { + return null; + } + + @Override + public LockModeType getLockMode(Object arg0) { + return null; + } + + @Override + public Metamodel getMetamodel() { + return null; + } + + @Override + public Map getProperties() { + return null; + } + + @Override + public T getReference(Class arg0, Object arg1) { + return null; + } + + @Override + public EntityTransaction getTransaction() { + return null; + } + + @Override + public boolean isOpen() { + return !closed; + } + + @Override + public void joinTransaction() { + } + + @Override + public void lock(Object arg0, LockModeType arg1) { + } + + @Override + public void lock(Object arg0, LockModeType arg1, Map arg2) { + } + + @Override + public T merge(T arg0) { + return null; + } + + @Override + public void persist(Object arg0) { + } + + @Override + public void refresh(Object arg0) { + } + + @Override + public void refresh(Object arg0, Map arg1) { + } + + @Override + public void refresh(Object arg0, LockModeType arg1) { + } + + @Override + public void refresh(Object arg0, LockModeType arg1, Map arg2) { + } + + @Override + public void remove(Object arg0) { + } + + @Override + public void setFlushMode(FlushModeType arg0) { + } + + @Override + public void setProperty(String arg0, Object arg1) { + } + + @Override + public T unwrap(Class arg0) { + return null; + } + + @Override + public boolean equals(Object obj) { + return equals; + } + + public void setEquals(boolean equals) { + this.equals = equals; + } + + @Override + public int hashCode() { + return hashCode; + } + + public void setHashCode(int hash) { + this.hashCode = hash; + } + + @Override + public String toString() { + return toString; + } + + public void setToString(String toString) { + this.toString = toString; + } + +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxyTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxyTest.java new file mode 100644 index 0000000..4a839c0 --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/EntityManagerProxyTest.java @@ -0,0 +1,530 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; + +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.metamodel.Metamodel; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer; +import br.gov.frameworkdemoiselle.internal.producer.FakeEntityManager; +import br.gov.frameworkdemoiselle.util.Beans; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class }) +public class EntityManagerProxyTest { + + private EntityManagerProxy entityManagerProxy; + + private EntityManager entityManager; + + private EntityManagerProducer entityManagerContext; + + @Before + public void setUp() throws Exception { + mockStatic(Beans.class); + this.entityManager = EasyMock.createMock(EntityManager.class); + this.entityManagerContext = EasyMock.createMock(EntityManagerProducer.class); + + expect(Beans.getReference(EntityManagerProducer.class)).andReturn(this.entityManagerContext).anyTimes(); + expect(this.entityManagerContext.getEntityManager("teste")).andReturn(this.entityManager).anyTimes(); + replay(this.entityManagerContext); + replayAll(); + + this.entityManagerProxy = new EntityManagerProxy("teste"); + + } + + @Test + public void testJoinTransactionIfNecessaryException() { + this.entityManager.persist("teste"); + expect(this.entityManager.getTransaction()).andThrow(new IllegalStateException()).anyTimes(); + this.entityManager.joinTransaction(); + replay(this.entityManager); + + this.entityManagerProxy.persist("teste"); + verify(this.entityManager); + } + + @Test + public void testPersist() { + this.entityManager.persist("teste"); + expect(this.entityManager.getTransaction()).andReturn(null); + replay(this.entityManager); + this.entityManagerProxy.persist("teste"); + verify(this.entityManager); + } + + @Test + public void testRemove() { + this.entityManager.remove("teste"); + expect(this.entityManager.getTransaction()).andReturn(null); + replay(this.entityManager); + this.entityManagerProxy.remove("teste"); + verify(this.entityManager); + } + + @Test + public void testFlush() { + this.entityManager.flush(); + replay(this.entityManager); + this.entityManagerProxy.flush(); + verify(this.entityManager); + } + + @Test + public void testSetFlushMode() { + FlushModeType flushModeType = null; + this.entityManager.setFlushMode(flushModeType); + replay(this.entityManager); + this.entityManagerProxy.setFlushMode(flushModeType); + verify(this.entityManager); + } + + @Test + public void testLockWithParamsStringAndLockModeType() { + LockModeType lockMode = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.lock("teste", lockMode); + replay(this.entityManager); + this.entityManagerProxy.lock("teste", lockMode); + verify(this.entityManager); + } + + @Test + public void testLockWithParamsStringLockModeTypeAndMap() { + LockModeType lockMode = null; + Map map = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.lock("teste", lockMode, map); + replay(this.entityManager); + this.entityManagerProxy.lock("teste", lockMode, map); + verify(this.entityManager); + } + + @Test + public void testRefresh() { + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.refresh("teste"); + replay(this.entityManager); + this.entityManagerProxy.refresh("teste"); + verify(this.entityManager); + } + + @Test + public void testRefreshWithParamsStringAndMap() { + Map map = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.refresh("teste", map); + replay(this.entityManager); + this.entityManagerProxy.refresh("teste", map); + verify(this.entityManager); + } + + @Test + public void testRefreshWithParamsStringAndLockModeType() { + LockModeType lockMode = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.refresh("teste", lockMode); + replay(this.entityManager); + this.entityManagerProxy.refresh("teste", lockMode); + verify(this.entityManager); + } + + @Test + public void testRefreshWithParamsStringLockModeTypeAndMap() { + LockModeType lockMode = null; + Map map = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + this.entityManager.refresh("teste", lockMode, map); + replay(this.entityManager); + this.entityManagerProxy.refresh("teste", lockMode, map); + verify(this.entityManager); + } + + @Test + public void testClear() { + this.entityManager.clear(); + replay(this.entityManager); + this.entityManagerProxy.clear(); + verify(this.entityManager); + } + + @Test + public void testDetach() { + this.entityManager.detach("teste"); + replay(this.entityManager); + this.entityManagerProxy.detach("teste"); + verify(this.entityManager); + } + + @Test + public void testSetProperty() { + this.entityManager.setProperty("teste", "teste"); + replay(this.entityManager); + this.entityManagerProxy.setProperty("teste", "teste"); + verify(this.entityManager); + } + + @Test + public void testJoinTransaction() { + this.entityManager.joinTransaction(); + replay(this.entityManager); + this.entityManagerProxy.joinTransaction(); + verify(this.entityManager); + } + + @Test + public void testClose() { + this.entityManager.close(); + replay(this.entityManager); + this.entityManagerProxy.close(); + verify(this.entityManager); + } + + @Test + public void testMerge() { + expect(this.entityManager.merge("teste")).andReturn("xxx"); + expect(this.entityManager.getTransaction()).andReturn(null); + replay(this.entityManager); + assertEquals("xxx", this.entityManagerProxy.merge("teste")); + verify(this.entityManager); + } + + @Test + public void testFindWithParamsClassAndObject() { + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.find(String.class, "teste")).andReturn("retorno"); + replay(this.entityManager); + assertEquals("retorno", this.entityManagerProxy.find(String.class, "teste")); + verify(this.entityManager); + } + + @Test + public void testFindWithParamsClassObjectAndMap() { + Map map = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.find(String.class, "teste", map)).andReturn("retorno"); + replay(this.entityManager); + assertEquals("retorno", this.entityManagerProxy.find(String.class, "teste", map)); + verify(this.entityManager); + } + + @Test + public void testFindWithParamsClassObjectAndLockModeType() { + LockModeType lock = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.find(String.class, "teste", lock)).andReturn("retorno"); + replay(this.entityManager); + assertEquals("retorno", this.entityManagerProxy.find(String.class, "teste", lock)); + verify(this.entityManager); + } + + @Test + public void testFindWithParamsClassObjectLockModeTypeAndMap() { + Map map = null; + LockModeType lock = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.find(String.class, "teste", lock, map)).andReturn("retorno"); + replay(this.entityManager); + assertEquals("retorno", this.entityManagerProxy.find(String.class, "teste", lock, map)); + verify(this.entityManager); + } + + @Test + public void testGetReference() { + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.getReference(String.class, "teste")).andReturn("retorno"); + replay(this.entityManager); + assertEquals("retorno", this.entityManagerProxy.getReference(String.class, "teste")); + verify(this.entityManager); + } + + @Test + public void testGetFlushMode() { + FlushModeType flushModeType = null; + expect(this.entityManager.getFlushMode()).andReturn(flushModeType); + replay(this.entityManager); + assertEquals(flushModeType, this.entityManagerProxy.getFlushMode()); + verify(this.entityManager); + } + + @Test + public void testContains() { + expect(this.entityManager.contains("teste")).andReturn(true); + replay(this.entityManager); + assertTrue(this.entityManagerProxy.contains("teste")); + verify(this.entityManager); + } + + @Test + public void testGetLockMode() { + LockModeType lockModeType = null; + expect(this.entityManager.getTransaction()).andReturn(null).anyTimes(); + expect(this.entityManager.getLockMode("teste")).andReturn(lockModeType); + replay(this.entityManager); + assertEquals(lockModeType, this.entityManagerProxy.getLockMode("teste")); + verify(this.entityManager); + } + + @Test + public void testGetProperties() { + Map map = null; + expect(this.entityManager.getProperties()).andReturn(map); + replay(this.entityManager); + assertEquals(map, this.entityManagerProxy.getProperties()); + verify(this.entityManager); + } + + @Test + public void testCreateQuery() { + Query query = null; + expect(this.entityManager.createQuery("teste")).andReturn(query); + replay(this.entityManager); + assertEquals(QueryProxy.class, this.entityManagerProxy.createQuery("teste").getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateQueryWithParamCriteria() { + TypedQuery typedQuery = null; + CriteriaQuery criteriaQuery = null; + expect(this.entityManager.createQuery(criteriaQuery)).andReturn(typedQuery); + replay(this.entityManager); + assertEquals(TypedQueryProxy.class, this.entityManagerProxy.createQuery(criteriaQuery).getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateQueryWithParamStringAndClass() { + TypedQuery typeQuery = null; + expect(this.entityManager.createQuery("teste", String.class)).andReturn(typeQuery); + replay(this.entityManager); + assertEquals(TypedQueryProxy.class, this.entityManagerProxy.createQuery("teste", String.class).getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateNamedQuery() { + Query query = null; + expect(this.entityManager.createNamedQuery("teste")).andReturn(query); + replay(this.entityManager); + assertEquals(QueryProxy.class, this.entityManagerProxy.createNamedQuery("teste").getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateNamedQueryWithParamsStringAndClass() { + TypedQuery typedQuery = null; + expect(this.entityManager.createNamedQuery("teste", String.class)).andReturn(typedQuery); + replay(this.entityManager); + assertEquals(typedQuery, this.entityManagerProxy.createNamedQuery("teste", String.class)); + verify(this.entityManager); + } + + @Test + public void testCreateNativeQuery() { + Query query = null; + expect(this.entityManager.createNativeQuery("teste")).andReturn(query); + replay(this.entityManager); + assertEquals(QueryProxy.class, this.entityManagerProxy.createNativeQuery("teste").getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateNativeQueryWithParamsStringAndClass() { + Query query = null; + expect(this.entityManager.createNativeQuery("teste", String.class)).andReturn(query); + replay(this.entityManager); + assertEquals(QueryProxy.class, this.entityManagerProxy.createNativeQuery("teste", String.class).getClass()); + verify(this.entityManager); + } + + @Test + public void testCreateNativeQueryWithParamsStringAndString() { + Query query = null; + expect(this.entityManager.createNativeQuery("teste", "teste")).andReturn(query); + replay(this.entityManager); + assertEquals(QueryProxy.class, this.entityManagerProxy.createNativeQuery("teste", "teste").getClass()); + verify(this.entityManager); + } + + @Test + public void testUnwrap() { + String query = null; + expect(this.entityManager.unwrap(String.class)).andReturn(query); + replay(this.entityManager); + assertEquals(query, this.entityManagerProxy.unwrap(String.class)); + verify(this.entityManager); + } + + @Test + public void testGetDelegate() { + Object obj = null; + expect(this.entityManager.getDelegate()).andReturn(obj); + replay(this.entityManager); + assertEquals(obj, this.entityManagerProxy.getDelegate()); + verify(this.entityManager); + } + + @Test + public void testIsOpen() { + expect(this.entityManager.isOpen()).andReturn(true); + replay(this.entityManager); + assertTrue(this.entityManagerProxy.isOpen()); + verify(this.entityManager); + } + + @Test + public void testGetTransaction() { + EntityTransaction entityTransaction = null; + expect(this.entityManager.getTransaction()).andReturn(entityTransaction); + replay(this.entityManager); + assertEquals(entityTransaction, this.entityManagerProxy.getTransaction()); + verify(this.entityManager); + } + + @Test + public void testGetEntityManagerFactory() { + EntityManagerFactory entityManagerFactory = null; + expect(this.entityManager.getEntityManagerFactory()).andReturn(entityManagerFactory); + replay(this.entityManager); + assertEquals(entityManagerFactory, this.entityManagerProxy.getEntityManagerFactory()); + verify(this.entityManager); + } + + @Test + public void testGetCriteriaBuilder() { + CriteriaBuilder criteriaBuilder = null; + expect(this.entityManager.getCriteriaBuilder()).andReturn(criteriaBuilder); + replay(this.entityManager); + assertEquals(criteriaBuilder, this.entityManagerProxy.getCriteriaBuilder()); + verify(this.entityManager); + } + + @Test + public void testGetMetamodel() { + Metamodel metamodel = null; + expect(this.entityManager.getMetamodel()).andReturn(metamodel); + replay(this.entityManager); + assertEquals(metamodel, this.entityManagerProxy.getMetamodel()); + verify(this.entityManager); + } + + @Test + public void testEquals() { + Object obj = null; + + mockStatic(Beans.class); + // Method "equals" can't be mocked... + EntityManager em = new FakeEntityManager(); + ((FakeEntityManager) em).setEquals(true); + + this.entityManagerContext = EasyMock.createMock(EntityManagerProducer.class); + expect(this.entityManagerContext.getEntityManager("teste")).andReturn(em).anyTimes(); + + expect(Beans.getReference(EntityManagerProducer.class)).andReturn(this.entityManagerContext).anyTimes(); + replay(this.entityManagerContext); + replayAll(); + + EntityManagerProxy emp = new EntityManagerProxy("teste"); + + assertTrue(emp.equals(obj)); + } + + @Test + public void testHashCode() { + mockStatic(Beans.class); + // Method "hashCode" can't be mocked... + EntityManager em = new FakeEntityManager(); + ((FakeEntityManager) em).setHashCode(1); + + this.entityManagerContext = EasyMock.createMock(EntityManagerProducer.class); + expect(this.entityManagerContext.getEntityManager("teste")).andReturn(em).anyTimes(); + + expect(Beans.getReference(EntityManagerProducer.class)).andReturn(this.entityManagerContext).anyTimes(); + replay(this.entityManagerContext); + replayAll(); + + EntityManagerProxy emp = new EntityManagerProxy("teste"); + + assertEquals(1, emp.hashCode()); + } + + @Test + public void testToString() { + mockStatic(Beans.class); + // Method "toString" can't be mocked... + EntityManager em = new FakeEntityManager(); + ((FakeEntityManager) em).setToString("testing"); + + this.entityManagerContext = EasyMock.createMock(EntityManagerProducer.class); + expect(this.entityManagerContext.getEntityManager("teste")).andReturn(em).anyTimes(); + + expect(Beans.getReference(EntityManagerProducer.class)).andReturn(this.entityManagerContext).anyTimes(); + replay(this.entityManagerContext); + replayAll(); + + EntityManagerProxy emp = new EntityManagerProxy("teste"); + + assertEquals("testing", emp.toString()); + } +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/template/JPACrudTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/template/JPACrudTest.java new file mode 100644 index 0000000..591c7c6 --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/template/JPACrudTest.java @@ -0,0 +1,408 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; +import static org.powermock.reflect.Whitebox.setInternalState; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.enterprise.inject.Instance; +import javax.persistence.Column; +import javax.persistence.EntityManager; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Query; +import javax.persistence.TransactionRequiredException; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.configuration.Configuration; +import br.gov.frameworkdemoiselle.internal.implementation.PaginationImpl; +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ ResourceBundle.class, Instance.class }) +public class JPACrudTest { + + private EntityManager entityManager; + + private Contact contact; + + private ContactDAO contactDAO; + + class ContactDAO extends JPACrud { + + private static final long serialVersionUID = 1L; + + } + + @Before + public void setUp() throws Exception { + this.entityManager = EasyMock.createMock(EntityManager.class); + this.contact = new Contact(); + this.contactDAO = new ContactDAO(); + setInternalState(this.contactDAO, EntityManager.class, this.entityManager); + } + + class Contact implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column + private Long id; + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + } + + @Test + public void testDelete() { + expect(this.entityManager.getReference(Contact.class, null)).andReturn(null); + this.entityManager.remove(null); + replay(this.entityManager); + this.contactDAO.delete(this.contact.getId()); + verify(this.entityManager); + } + + @Test + public void testCountAll() { + + Pagination pagination = new PaginationImpl(); + PaginationContext actualContext = PowerMock.createMock(PaginationContext.class); + expect(actualContext.getPagination(Contact.class)).andReturn(pagination); + @SuppressWarnings("unchecked") + Instance paginationContext = PowerMock.createMock(Instance.class); + expect(paginationContext.get()).andReturn(actualContext); + setInternalState(this.contactDAO, "paginationContext", paginationContext); + + Query query = EasyMock.createMock(Query.class); + expect(query.setFirstResult(EasyMock.anyInt())).andReturn(query); + expect(query.setMaxResults(EasyMock.anyInt())).andReturn(query); + expect(query.getSingleResult()).andReturn(10L); + + expect(this.entityManager.createQuery("select this from Contact this")).andReturn(query); + expect(this.entityManager.createQuery("select count(this) from Contact this")).andReturn(query); + expect(query.getResultList()).andReturn(createContacts(1)); + + replayAll(query, this.entityManager, paginationContext); + + List find = this.contactDAO.findAll(); + + assertEquals(1, find.size()); + assertTrue(find.iterator().next().getId().equals(1L)); + + verifyAll(); + } + + @Test + public void testFailCountAll() { + + Pagination pagination = new PaginationImpl(); + PaginationContext actualContext = PowerMock.createMock(PaginationContext.class); + expect(actualContext.getPagination(Contact.class)).andReturn(pagination); + @SuppressWarnings("unchecked") + Instance paginationContext = PowerMock.createMock(Instance.class); + expect(paginationContext.get()).andReturn(actualContext); + setInternalState(this.contactDAO, "paginationContext", paginationContext); + + Query query = EasyMock.createMock(Query.class); + + expect(query.getSingleResult()).andThrow(new DemoiselleException("")); + expect(this.entityManager.createQuery("select this from Contact this")).andReturn(query); + expect(this.entityManager.createQuery("select count(this) from Contact this")).andReturn(query); + + replayAll(query, this.entityManager, paginationContext); + + try { + this.contactDAO.findAll(); + fail(); + } catch (DemoiselleException exception) { + } + + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testHandleException() throws Throwable { + try { + TransactionRequiredException throwed = new TransactionRequiredException(); + ResourceBundle bundle = PowerMock.createMock(ResourceBundle.class); + Instance instance = PowerMock.createMock(Instance.class); + expect( + bundle.getString("no-transaction-active", "frameworkdemoiselle.transaction.class", + Configuration.DEFAULT_RESOURCE)).andReturn("message"); + expect(instance.get()).andReturn(bundle); + setInternalState(contactDAO, "bundle", instance); + replayAll(); + contactDAO.handleException(throwed); + fail(); + } catch (DemoiselleException exception) { + assertEquals(exception.getMessage(), "message"); + } + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testFailFindByExample() { + + CriteriaBuilder criteriaBuilder = PowerMock.createMock(CriteriaBuilder.class); + CriteriaQuery criteriaQuery = PowerMock.createMock(CriteriaQuery.class); + Root root = PowerMock.createMock(Root.class); + + expect(this.entityManager.getCriteriaBuilder()).andReturn(criteriaBuilder); + expect(criteriaBuilder.createQuery(Contact.class)).andReturn(criteriaQuery); + expect(criteriaQuery.from(Contact.class)).andReturn(root); + + expect(this.entityManager.createQuery(criteriaQuery)).andThrow(new DemoiselleException("")); + + Predicate predicate = PowerMock.createMock(Predicate.class); + + expect(root.get("id")).andReturn(null); + expect(criteriaBuilder.equal(EasyMock.anyObject(Predicate.class), EasyMock.anyObject())).andReturn(predicate); + expect(criteriaQuery.where(new Predicate[] { EasyMock.anyObject(Predicate.class) })).andReturn(criteriaQuery); + expect(criteriaQuery.select(EasyMock.anyObject(Root.class))).andReturn(criteriaQuery); + + replayAll(criteriaBuilder, criteriaQuery, root, this.entityManager); + + Contact example = new Contact(); + example.setId(1L); + try { + this.contactDAO.findByExample(example); + fail(); + } catch (DemoiselleException ce) { + } + + verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testFindByExample() { + + TypedQuery typedQuery = EasyMock.createMock(TypedQuery.class); + CriteriaBuilder criteriaBuilder = PowerMock.createMock(CriteriaBuilder.class); + CriteriaQuery criteriaQuery = PowerMock.createMock(CriteriaQuery.class); + Root root = PowerMock.createMock(Root.class); + + expect(this.entityManager.getCriteriaBuilder()).andReturn(criteriaBuilder); + expect(criteriaBuilder.createQuery(Contact.class)).andReturn(criteriaQuery); + expect(criteriaQuery.from(Contact.class)).andReturn(root); + + expect(this.entityManager.createQuery(criteriaQuery)).andReturn(typedQuery); + expect(typedQuery.getResultList()).andReturn(createContacts(1)); + + Predicate predicate = PowerMock.createMock(Predicate.class); + + expect(root.get("id")).andReturn(null); + expect(criteriaBuilder.equal(EasyMock.anyObject(Predicate.class), EasyMock.anyObject())).andReturn(predicate); + expect(criteriaQuery.where(new Predicate[] { EasyMock.anyObject(Predicate.class) })).andReturn(criteriaQuery); + expect(criteriaQuery.select(EasyMock.anyObject(Root.class))).andReturn(criteriaQuery); + + replayAll(typedQuery, criteriaBuilder, criteriaQuery, root, this.entityManager); + + Contact example = new Contact(); + example.setId(1L); + List find = this.contactDAO.findByExample(example); + + assertEquals(1, find.size()); + assertTrue(find.iterator().next().getId().equals(1L)); + + verifyAll(); + } + + @Test + public void testFindAll() { + + PaginationContext actualContext = PowerMock.createMock(PaginationContext.class); + expect(actualContext.getPagination(Contact.class)).andReturn(null); + @SuppressWarnings("unchecked") + Instance paginationContext = PowerMock.createMock(Instance.class); + expect(paginationContext.get()).andReturn(actualContext); + setInternalState(this.contactDAO, "paginationContext", paginationContext); + + Query query = EasyMock.createMock(Query.class); + // expect(query.setFirstResult(EasyMock.anyInt())).andReturn(query); + // expect(query.setMaxResults(EasyMock.anyInt())).andReturn(query); + expect(this.entityManager.createQuery("select this from Contact this")).andReturn(query); + expect(query.getResultList()).andReturn(createContacts(1)); + + replayAll(query, this.entityManager, paginationContext); + + List find = this.contactDAO.findAll(); + + assertEquals(1, find.size()); + assertTrue(find.iterator().next().getId().equals(1L)); + + verifyAll(); + } + + @Test + public void testFailFindAll() { + + PaginationContext actualContext = PowerMock.createMock(PaginationContext.class); + expect(actualContext.getPagination(Contact.class)).andReturn(null); + @SuppressWarnings("unchecked") + Instance paginationContext = PowerMock.createMock(Instance.class); + expect(paginationContext.get()).andReturn(actualContext); + setInternalState(this.contactDAO, "paginationContext", paginationContext); + + Query query = EasyMock.createMock(Query.class); + expect(this.entityManager.createQuery("select this from Contact this")).andReturn(query); + expect(query.getResultList()).andThrow(new DemoiselleException("")); + + replayAll(query, this.entityManager, paginationContext); + + try { + this.contactDAO.findAll(); + fail(); + } catch (DemoiselleException exception) { + } + + verifyAll(); + } + + private List createContacts(int quantity) { + List contacts = new ArrayList(); + for (int i = 0; i < quantity; i++) { + Contact contact = new Contact(); + contact.setId((long) quantity); + contacts.add(contact); + } + return contacts; + } + + @Test + public void testFailInsert() { + this.entityManager.persist(null); + EasyMock.expectLastCall().andThrow(new DemoiselleException("")); + replay(this.entityManager); + try { + this.contactDAO.insert(null); + fail(); + } catch (DemoiselleException exc) { + } + verify(this.entityManager); + } + + @Test + public void testInsert() { + this.entityManager.persist(this.contact); + replay(this.entityManager); + setInternalState(this.contactDAO, EntityManager.class, this.entityManager); + this.contactDAO.insert(this.contact); + verify(this.entityManager); + } + + @Test + public void testLoad() { + Contact contact = new Contact(); + expect(this.entityManager.find(Contact.class, 1L)).andReturn(contact); + replay(this.entityManager); + Contact returnedContact = this.contactDAO.load(1L); + assertEquals(contact.hashCode(), returnedContact.hashCode()); + verify(this.entityManager); + } + + @Test + public void testFailLoad() { + expect(this.entityManager.find(Contact.class, 1L)).andThrow(new DemoiselleException("")); + replay(this.entityManager); + try { + this.contactDAO.load(1L); + fail(); + } catch (DemoiselleException exc) { + } + verify(this.entityManager); + } + + @Test + public void testUpdate() { + expect(this.entityManager.merge(this.contact)).andReturn(null); + replay(this.entityManager); + setInternalState(this.contactDAO, EntityManager.class, this.entityManager); + this.contactDAO.update(this.contact); + verify(this.entityManager); + } + + @Test + public void testFailUpdate() { + this.entityManager.merge(null); + EasyMock.expectLastCall().andThrow(new DemoiselleException("")); + replay(this.entityManager); + try { + this.contactDAO.update(null); + fail(); + } catch (DemoiselleException exc) { + } + verify(this.entityManager); + } + +} diff --git a/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/transaction/JPATransactionTest.java b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/transaction/JPATransactionTest.java new file mode 100644 index 0000000..a50324f --- /dev/null +++ b/extension/jpa/src/test/java/br/gov/frameworkdemoiselle/transaction/JPATransactionTest.java @@ -0,0 +1,224 @@ +///* +// * 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 br.gov.frameworkdemoiselle.transaction; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; +import static org.powermock.reflect.Whitebox.setInternalState; + +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.SystemException; + +import br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer; + +/** + * @author SERPRO + * @see JPATransaction + */ + +public class JPATransactionTest { + + private JPATransaction tx; + + private EntityManager em; + + private EntityTransaction et; + + private Map cache; + + private EntityManagerProducer producer; + + @Before + public void setUp() { + et = createMock(EntityTransaction.class); + em = createMock(EntityManager.class); + cache = new HashMap(); + producer = EasyMock.createMock(EntityManagerProducer.class); + + tx = new JPATransaction(); + setInternalState(tx, EntityManagerProducer.class, producer); + } + + @After + public void tearDown() { + tx = null; + em = null; + et = null; + cache = null; + producer = null; + } + + @Test + public void testBegin() throws SystemException { + et.begin(); + expect(et.isActive()).andReturn(false); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + tx.begin(); + verifyAll(); + } + + @Test + public void testCommit() throws Exception { + et.commit(); + expect(et.isActive()).andReturn(true); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + tx.commit(); + verifyAll(); + } + + @Test + public void testRollback() throws Exception { + et.rollback(); + expect(et.isActive()).andReturn(true); + expect(em.getTransaction()).andReturn(et).anyTimes(); + em.clear(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + tx.rollback(); + verifyAll(); + } + + @Test + public void testSetRollbackOnly() throws Exception { + et.setRollbackOnly(); + expect(et.isActive()).andReturn(true); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + tx.setRollbackOnly(); + verifyAll(); + } + + @Test + public void testIsActiveTrue() throws Exception { + expect(et.isActive()).andReturn(true).anyTimes(); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + assertEquals(true, tx.isActive()); + verifyAll(); + } + + @Test + public void testIsActiveFalse() throws Exception { + expect(et.isActive()).andReturn(false).anyTimes(); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + assertEquals(false, tx.isActive()); + verifyAll(); + } + + @Test + public void testIsMarkedRollbackTrue() throws Exception { + expect(et.isActive()).andReturn(true); + expect(et.getRollbackOnly()).andReturn(true).anyTimes(); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + assertEquals(true, tx.isMarkedRollback()); + verifyAll(); + } + + @Test + public void testIsMarkedRollbackFalse() throws Exception { + expect(et.isActive()).andReturn(true); + expect(et.getRollbackOnly()).andReturn(false).anyTimes(); + expect(em.getTransaction()).andReturn(et).anyTimes(); + cache.put("teste", em); + expect(producer.getCache()).andReturn(cache); + replay(producer); + replayAll(); + replay(em); + replay(et); + + assertEquals(false, tx.isMarkedRollback()); + verifyAll(); + } +} diff --git a/extension/jpa/src/test/resources/META-INF/persistence.xml b/extension/jpa/src/test/resources/META-INF/persistence.xml new file mode 100644 index 0000000..2fde4f6 --- /dev/null +++ b/extension/jpa/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/test/resources/demoiselle-jpa-bundle.properties b/extension/jpa/src/test/resources/demoiselle-jpa-bundle.properties new file mode 100644 index 0000000..9dde8ee --- /dev/null +++ b/extension/jpa/src/test/resources/demoiselle-jpa-bundle.properties @@ -0,0 +1,44 @@ +# 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. + +entity-manager-was-created=Gerenciador de entidades criado a partir da unidade de persist\u00EAncia "{0}". +operation-not-supported=Esta operação não é suportada. +getting-persistence-unit-from-properties=Obtendo a unidade de persist\u00EAncia a partir do arquivo de configura\u00E7\u00E3o "{0}". +getting-persistence-unit-from-persistence=Obtendo a unidade de persist\u00EAncia a partir do arquivo "persistence.xml". +can-not-get-persistence-unit-from-persistence=N\u00E3o foi poss\u00EDvel obter a unidade de persist\u00EAncia a partir do arquivo "persistence.xml". +more-than-one-persistence-unit-defined=Existe mais de uma unidade de persist\u00EAncia definida. Utilize @{0} no ponto de inje\u00E7\u00E3o ou defina o atributo "frameworkdemoiselle.persistence.unit.name" no arquivo demoiselle.properties. +persistence-unit-name-found=Unidade de persist\u00EAncia "{0}" encontrada. +entity-manager-closed=O gerenciador de entidades foi fechado. +no-transaction-active=Nenhuma transa\u00E7\u00E3o est\u00E1 ativa, verifique a configura\u00E7\u00E3o "{0}" no arquivo "{1}" e defina a sua estrat\u00E9gia de transa\u00E7\u00E3o. \ No newline at end of file diff --git a/extension/jpa/src/test/resources/demoiselle.properties b/extension/jpa/src/test/resources/demoiselle.properties new file mode 100644 index 0000000..1f00cd6 --- /dev/null +++ b/extension/jpa/src/test/resources/demoiselle.properties @@ -0,0 +1,36 @@ +# 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. + +frameworkdemoiselle.persistence.unit.name=PersistenceUnitName \ No newline at end of file diff --git a/extension/jpa/src/test/resources/empty-persistence.xml b/extension/jpa/src/test/resources/empty-persistence.xml new file mode 100644 index 0000000..235c333 --- /dev/null +++ b/extension/jpa/src/test/resources/empty-persistence.xml @@ -0,0 +1,40 @@ + + + + + \ No newline at end of file diff --git a/extension/jpa/src/test/resources/log4j.properties b/extension/jpa/src/test/resources/log4j.properties new file mode 100755 index 0000000..48a89ba --- /dev/null +++ b/extension/jpa/src/test/resources/log4j.properties @@ -0,0 +1,42 @@ +# 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. + +log4j.rootCategory=INFO, stdout + +log4j.logger.br.gov.frameworkdemoiselle=TRACE + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p [%c{1}] %m%n diff --git a/extension/jpa/src/test/resources/persistence-two-units.xml b/extension/jpa/src/test/resources/persistence-two-units.xml new file mode 100644 index 0000000..cfdc13f --- /dev/null +++ b/extension/jpa/src/test/resources/persistence-two-units.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/test/resources/persistence.xml b/extension/jpa/src/test/resources/persistence.xml new file mode 100644 index 0000000..2fde4f6 --- /dev/null +++ b/extension/jpa/src/test/resources/persistence.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/uml/injection-producer.ucls b/extension/jpa/src/uml/injection-producer.ucls new file mode 100644 index 0000000..9ec056e --- /dev/null +++ b/extension/jpa/src/uml/injection-producer.ucls @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/uml/pagination.ucls b/extension/jpa/src/uml/pagination.ucls new file mode 100644 index 0000000..235db77 --- /dev/null +++ b/extension/jpa/src/uml/pagination.ucls @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/uml/template.ucls b/extension/jpa/src/uml/template.ucls new file mode 100644 index 0000000..0855e1e --- /dev/null +++ b/extension/jpa/src/uml/template.ucls @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jpa/src/uml/transaction.ucls b/extension/jpa/src/uml/transaction.ucls new file mode 100644 index 0000000..1d58438 --- /dev/null +++ b/extension/jpa/src/uml/transaction.ucls @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/.gitignore b/extension/jsf/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/extension/jsf/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/extension/jsf/pom.xml b/extension/jsf/pom.xml new file mode 100644 index 0000000..43d0a1e --- /dev/null +++ b/extension/jsf/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + demoiselle-jsf + jar + + + br.gov.frameworkdemoiselle + demoiselle-extension-parent + 2.2.1-SNAPSHOT + ../../parent/extension/pom.xml + + + JSF Extension + + + + + com.sun.faces + jsf-api + + + com.sun.faces + jsf-impl + + + javax.servlet + jstl + + + javax.servlet + servlet-api + + + javax.el + el-api + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/NextView.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/NextView.java new file mode 100644 index 0000000..1827714 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/NextView.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 br.gov.frameworkdemoiselle.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.Documented; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.inject.Qualifier; + + +// TODO Este qualifier é realmente necessário? Verificar também na anotação PreviousView. +@Inherited +@Documented +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +@Retention(RUNTIME) +public @interface NextView { + + String value(); + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/PreviousView.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/PreviousView.java new file mode 100644 index 0000000..d88bd63 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/PreviousView.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 br.gov.frameworkdemoiselle.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.Documented; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.inject.Qualifier; + +@Inherited +@Documented +@Target({ TYPE, FIELD, METHOD, PARAMETER }) +@Retention(RUNTIME) +public @interface PreviousView { + + String value(); + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/Redirect.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/Redirect.java new file mode 100644 index 0000000..57aa43c --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/annotation/Redirect.java @@ -0,0 +1,59 @@ +/* + * 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 br.gov.frameworkdemoiselle.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + *

    Should be used only in exceptions classes.

    + *

    When that exceptions is thrown will force an redirect to a specific "viewId".

    + * + */ +@Target(TYPE) +@Retention(RUNTIME) +public @interface Redirect { + + /** + * Defines the view ID. + */ + String viewId() default ""; + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java new file mode 100644 index 0000000..13c286c --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java @@ -0,0 +1,49 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; + +import br.gov.frameworkdemoiselle.internal.context.ViewContext; + +public class JsfBootstrap extends AbstractBootstrap { + + public void loadContexts(@Observes final AfterBeanDiscovery event) { + addContext(new ViewContext(), event); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ExceptionHandlerConfig.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ExceptionHandlerConfig.java new file mode 100644 index 0000000..6309b0e --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ExceptionHandlerConfig.java @@ -0,0 +1,26 @@ +package br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +@Configuration(prefix = "frameworkdemoiselle.handle") +public class ExceptionHandlerConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("application.exception") + private boolean handleApplicationException = true; + + @Name("application.exception.page") + private String exceptionPage = "/application_error"; + + public String getExceptionPage() { + return exceptionPage; + } + + public boolean isHandleApplicationException() { + return handleApplicationException; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/JsfSecurityConfig.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/JsfSecurityConfig.java new file mode 100644 index 0000000..b695c99 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/JsfSecurityConfig.java @@ -0,0 +1,42 @@ +package br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +@Configuration(prefix = "frameworkdemoiselle.security") +public class JsfSecurityConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("login.page") + private String loginPage = "/login"; + + // @Name("welcome.page") + @Name("redirect.after.login") + private String redirectAfterLogin = "/index"; + + @Name("redirect.after.logout") + private String redirectAfterLogout = "/login"; + + @Name("redirect.enabled") + private boolean redirectEnabled = true; + + public String getLoginPage() { + return loginPage; + } + + public String getRedirectAfterLogin() { + return redirectAfterLogin; + } + + public String getRedirectAfterLogout() { + return redirectAfterLogout; + } + + public boolean isRedirectEnabled() { + return redirectEnabled; + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java new file mode 100644 index 0000000..3307fae --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java @@ -0,0 +1,95 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import java.lang.annotation.Annotation; +import java.util.Map; + +import javax.enterprise.context.spi.Contextual; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; + +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.util.Faces; + +public class ViewContext implements CustomContext { + + private boolean active; + + public ViewContext() { + this.active = true; + } + + @Override + public T get(final Contextual contextual) { + return get(contextual, null); + } + + @Override + @SuppressWarnings("unchecked") + public T get(final Contextual contextual, final CreationalContext creationalContext) { + T instance = null; + + Bean bean = (Bean) contextual; + Map viewMap = Faces.getViewMap(); + + if (viewMap.containsKey(bean.getName())) { + instance = (T) viewMap.get(bean.getName()); + + } else if (creationalContext != null) { + instance = bean.create(creationalContext); + viewMap.put(bean.getName(), instance); + } + + return instance; + } + + @Override + public Class getScope() { + return ViewScoped.class; + } + + @Override + public boolean isActive() { + return this.active; + } + + @Override + public void setActive(boolean active) { + this.active = active; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AbstractExceptionHandler.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AbstractExceptionHandler.java new file mode 100644 index 0000000..2fb0d9b --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AbstractExceptionHandler.java @@ -0,0 +1,92 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.util.Iterator; + +import javax.faces.FacesException; +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerWrapper; +import javax.faces.context.FacesContext; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; + +public abstract class AbstractExceptionHandler extends ExceptionHandlerWrapper { + + private ExceptionHandler wrapped; + + public AbstractExceptionHandler(final ExceptionHandler wrapped) { + this.wrapped = wrapped; + } + + @Override + public ExceptionHandler getWrapped() { + return this.wrapped; + } + + @Override + public void handle() throws FacesException { + FacesContext facesContext = FacesContext.getCurrentInstance(); + ExceptionQueuedEventContext exceptionContext; + Throwable root; + + for (Iterator iter = getUnhandledExceptionQueuedEvents().iterator(); iter.hasNext();) { + exceptionContext = (ExceptionQueuedEventContext) iter.next().getSource(); + root = getRoot(exceptionContext.getException()); + + if (handleException(root, facesContext)) { + iter.remove(); + } + } + + if (getUnhandledExceptionQueuedEvents().iterator().hasNext()) { + getWrapped().handle(); + } + } + + protected abstract boolean handleException(final Throwable cause, FacesContext facesContext); + + private Throwable getRoot(final Throwable throwable) { + Throwable root = throwable; + + while (root.getCause() != null) { + root = root.getCause(); + } + + return root; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandler.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandler.java new file mode 100644 index 0000000..b705aa1 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandler.java @@ -0,0 +1,89 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.util.HashMap; +import java.util.Map; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; +import javax.faces.event.PhaseId; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.internal.configuration.ExceptionHandlerConfig; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Exceptions; +import br.gov.frameworkdemoiselle.util.Faces; +import br.gov.frameworkdemoiselle.util.PageNotFoundException; +import br.gov.frameworkdemoiselle.util.Redirector; + +public class ApplicationExceptionHandler extends AbstractExceptionHandler { + + public ApplicationExceptionHandler(final ExceptionHandler wrapped) { + super(wrapped); + } + + protected boolean handleException(final Throwable cause, FacesContext facesContext) { + ExceptionHandlerConfig config = Beans.getReference(ExceptionHandlerConfig.class); + boolean handled = false; + + if (config.isHandleApplicationException() && Exceptions.isApplicationException(cause)) { + + if (isRendering(facesContext)) { + handled = handlingDuringRenderResponse(cause, config); + } else { + Faces.addMessage(cause); + handled = true; + } + } + + return handled; + } + + private final boolean isRendering(FacesContext context) { + return PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId()); + } + + /** + * In render response phase an exception interrupt the renderization. So this method will redirect the renderingo to + * an page configured in demoiselle.properties + * + * @see ExceptionHandlerConfig + * @param cause + * @param config + * @return + */ + private final boolean handlingDuringRenderResponse(final Throwable cause, final ExceptionHandlerConfig config) { + boolean handled = false; + try { + Map map = new HashMap(); + map.put("exception", cause.getMessage()); + Redirector.redirect(config.getExceptionPage(), map); + handled = true; + } catch (PageNotFoundException ex) { + // TODO Colocar a mensagem no bundle + throw new DemoiselleException( + "A tela de exibição de erros: \"" + + ex.getViewId() + + "\" não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" + + "frameworkdemoiselle.handle.application.exception.page" + "\"", ex); + } + return handled; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactory.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactory.java new file mode 100644 index 0000000..6dc596b --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactory.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +public class ApplicationExceptionHandlerFactory extends ExceptionHandlerFactory { + + private ExceptionHandlerFactory delegate; + + public ApplicationExceptionHandlerFactory(final ExceptionHandlerFactory delegate) { + this.delegate = delegate; + } + + @Override + public ExceptionHandler getExceptionHandler() { + return new ApplicationExceptionHandler(delegate.getExceptionHandler()); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandler.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandler.java new file mode 100644 index 0000000..4a6791e --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandler.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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; + +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.util.Beans; + +public class AuthenticationExceptionHandler extends AbstractExceptionHandler { + + public AuthenticationExceptionHandler(final ExceptionHandler wrapped) { + super(wrapped); + } + + protected boolean handleException(final Throwable cause, FacesContext facesContext) { + boolean handled = false; + + if (cause instanceof NotLoggedInException) { + handled = true; + //TODO Inter [NQ]: remover referência a SecurityObserver criando uma classe comum que faz o redirecionamento e que é compartilhada entre elas. + Beans.getReference(SecurityObserver.class).redirectToLoginPage(); + } + + return handled; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactory.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactory.java new file mode 100644 index 0000000..f3ea346 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactory.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +public class AuthenticationExceptionHandlerFactory extends ExceptionHandlerFactory { + + private ExceptionHandlerFactory delegate; + + public AuthenticationExceptionHandlerFactory(final ExceptionHandlerFactory delegate) { + this.delegate = delegate; + } + + @Override + public ExceptionHandler getExceptionHandler() { + return new AuthenticationExceptionHandler(delegate.getExceptionHandler()); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandler.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandler.java new file mode 100644 index 0000000..d142f70 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandler.java @@ -0,0 +1,63 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; +import javax.faces.event.PhaseId; + +import br.gov.frameworkdemoiselle.security.AuthorizationException; +import br.gov.frameworkdemoiselle.util.Faces; + +public class AuthorizationExceptionHandler extends AbstractExceptionHandler { + + public AuthorizationExceptionHandler(final ExceptionHandler wrapped) { + super(wrapped); + } + + protected boolean handleException(final Throwable cause, FacesContext facesContext) { + boolean handled = false; + boolean rendering = PhaseId.RENDER_RESPONSE.equals(facesContext.getCurrentPhaseId()); + + if (!rendering && cause instanceof AuthorizationException) { + Faces.addMessage(cause); + handled = true; + } + + return handled; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactory.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactory.java new file mode 100644 index 0000000..1e1ff7e --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactory.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +public class AuthorizationExceptionHandlerFactory extends ExceptionHandlerFactory { + + private ExceptionHandlerFactory delegate; + + public AuthorizationExceptionHandlerFactory(final ExceptionHandlerFactory delegate) { + this.delegate = delegate; + } + + @Override + public ExceptionHandler getExceptionHandler() { + return new AuthorizationExceptionHandler(delegate.getExceptionHandler()); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImpl.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImpl.java new file mode 100644 index 0000000..aa78006 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImpl.java @@ -0,0 +1,92 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.util.Faces; +import br.gov.frameworkdemoiselle.util.FileRenderer; + +/** + * Responsible for displaying the contents of files in the browser. + */ +public class FileRendererImpl implements FileRenderer { + + private static final long serialVersionUID = 7787266586182058798L; + + @Inject + private HttpServletResponse response; + + @Inject + private Logger logger; + + @Inject + private FacesContext context; + + @Override + public void render(final byte[] byteArray, final ContentType contentType, final String fileName) { + logger.debug("Renderizando para o arquivo " + fileName + "."); + + try { + response.setContentType(contentType.getContentType()); + response.setContentLength(byteArray.length); + response.setHeader("Content-Disposition", "filename=\"" + fileName + "\""); + + logger.debug("Escrevendo o arquivo " + fileName + " no response."); + response.getOutputStream().write(byteArray, 0, byteArray.length); + response.getOutputStream().flush(); + response.getOutputStream().close(); + } catch (IOException e) { + logger.info("Erro na geração do relatório. Incluíndo a exceção de erro em um FacesMessage", e); + Faces.addMessage(e); + } + context.responseComplete(); + } + + @Override + public void render(final InputStream stream, final ContentType contentType, final String fileName) { + logger.debug("Renderizando o arquivo " + fileName + "."); + render(getBytes(stream), contentType, fileName); + } + + @Override + public void render(File file, ContentType contentType, String fileName) { + logger.debug("Renderizando para o arquivo " + fileName + "."); + try { + render(new FileInputStream(file), contentType, fileName); + } catch (FileNotFoundException e) { + logger.info("Erro na geração do relatório. Incluíndo a exceção de erro em um FacesMessage", e); + Faces.addMessage(e); + } + } + + private byte[] getBytes(InputStream stream) { + byte[] byteArray = null; + try { + int thisLine; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + while ((thisLine = stream.read()) != -1) { + bos.write(thisLine); + } + bos.flush(); + byteArray = bos.toByteArray(); + + if (bos != null) { + bos.close(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + return byteArray; + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListener.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListener.java new file mode 100644 index 0000000..92ef057 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListener.java @@ -0,0 +1,99 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.event.PhaseEvent; +import javax.faces.event.PhaseId; +import javax.faces.event.PhaseListener; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.message.MessageContext; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Faces; + +/** + * This class is a JSF phase listener intended to transfer messages from Demoiselle Context to JSF own context. + * + * @author SERPRO + */ +public class MessagePhaseListener implements PhaseListener { + + private static final long serialVersionUID = 1L; + + // FIXME: por que não funciona injeção disso aqui? + // @Inject + // private Logger logger; + private final Logger logger = LoggerProducer.create(this.getClass()); + + // TODO: usar o bundle nas mensagens de log + // @Inject + // @Name("demoiselle-core-bundle") + // private ResourceBundle bundle; + + public void beforePhase(PhaseEvent e) { + transferMessages(e); + } + + public void afterPhase(PhaseEvent e) { + } + + /** + * Transfers messages from a context to another. + * + * @param e + * PhaseEvent + */ + private void transferMessages(PhaseEvent e) { + + logger.debug(this.getClass().getSimpleName() + " " + e.getPhaseId()); + + MessageContext messageContext = Beans.getReference(MessageContext.class); + + logger.debug("Moving " + messageContext.getMessages().size() + + " message(s) from MessageContext to FacesContext."); + + Faces.addMessages(messageContext.getMessages()); + messageContext.clear(); + } + + public PhaseId getPhaseId() { + return PhaseId.RENDER_RESPONSE; + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImpl.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImpl.java new file mode 100644 index 0000000..8f16235 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImpl.java @@ -0,0 +1,156 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; +import java.util.Map; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.faces.convert.Converter; +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.util.Faces; +import br.gov.frameworkdemoiselle.util.Parameter; +import br.gov.frameworkdemoiselle.util.Reflections; + +public class ParameterImpl implements Parameter, Serializable { + + private static final long serialVersionUID = 1L; + + private Class type; + + private Converter converter; + + private final InjectionPoint ip; + + private final HttpServletRequest request; + + private T value; + + private final String key; + + @Inject + public ParameterImpl(InjectionPoint ip, HttpServletRequest request) { + this.ip = ip; + this.request = request; + + if (ip.getAnnotated().isAnnotationPresent(Name.class)) { + this.key = ip.getAnnotated().getAnnotation(Name.class).value(); + } else { + this.key = ip.getMember().getName(); + } + + this.type = Reflections.getGenericTypeArgument(ip.getMember(), 0); + this.converter = Faces.getConverter(type); + } + + public String getKey() { + return key; + } + + private boolean isSessionScoped() { + return ip.getAnnotated().isAnnotationPresent(SessionScoped.class); + } + + private boolean isViewScoped() { + return ip.getAnnotated().isAnnotationPresent(ViewScoped.class); + } + + private boolean isRequestScoped() { + return ip.getAnnotated().isAnnotationPresent(RequestScoped.class); + } + + @SuppressWarnings("unchecked") + public T getValue() { + T result = null; + String parameterValue = request.getParameter(key); + + if (isSessionScoped()) { + if (parameterValue != null) { + request.getSession().setAttribute(key, Faces.convert(parameterValue, converter)); + } + + result = (T) request.getSession().getAttribute(key); + + } else if (isRequestScoped()) { + result = (T) Faces.convert(parameterValue, converter); + + } else if (isViewScoped()) { + Map viewMap = Faces.getViewMap(); + if (parameterValue != null) { + viewMap.put(key, Faces.convert(parameterValue, converter)); + } + + result = (T) viewMap.get(key); + + } else { + if (value == null) { + value = (T) Faces.convert(parameterValue, converter); + } + + result = value; + } + + return result; + } + + public Converter getConverter() { + return converter; + } + + @Override + public void setValue(T value) { + if (isSessionScoped()) { + this.request.getSession().setAttribute(key, value); + + } else if (isRequestScoped()) { + // FIXME Lançar exceção informando que não é possível setar parâmetros no request. + + } else if (isViewScoped()) { + Map viewMap = Faces.getViewMap(); + viewMap.put(key, value); + + } else { + this.value = value; + } + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandler.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandler.java new file mode 100644 index 0000000..4b219f3 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandler.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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; + +import br.gov.frameworkdemoiselle.annotation.Redirect; +import br.gov.frameworkdemoiselle.util.Redirector; + +public class RedirectExceptionHandler extends AbstractExceptionHandler { + + public RedirectExceptionHandler(final ExceptionHandler wrapped) { + super(wrapped); + } + + protected boolean handleException(final Throwable cause, FacesContext facesContext) { + boolean handled = false; + Redirect annotation = cause.getClass().getAnnotation(Redirect.class); + + if (annotation != null) { + handled = true; + Redirector.redirect(annotation.viewId()); + } + + return handled; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactory.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactory.java new file mode 100644 index 0000000..2f241a8 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactory.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +public class RedirectExceptionHandlerFactory extends ExceptionHandlerFactory { + + private ExceptionHandlerFactory delegate; + + public RedirectExceptionHandlerFactory(final ExceptionHandlerFactory delegate) { + this.delegate = delegate; + } + + @Override + public ExceptionHandler getExceptionHandler() { + return new RedirectExceptionHandler(delegate.getExceptionHandler()); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java new file mode 100644 index 0000000..afb161a --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java @@ -0,0 +1,129 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; +import javax.enterprise.event.Observes; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.configuration.JsfSecurityConfig; +import br.gov.frameworkdemoiselle.security.AfterLoginSuccessful; +import br.gov.frameworkdemoiselle.security.AfterLogoutSuccessful; +import br.gov.frameworkdemoiselle.util.PageNotFoundException; +import br.gov.frameworkdemoiselle.util.Redirector; + +import com.sun.faces.config.ConfigurationException; + +@SessionScoped +public class SecurityObserver implements Serializable { + + private static final long serialVersionUID = 1L; + + @Inject + private FacesContext facesContext; + + @Inject + private JsfSecurityConfig config; + + @Inject + private HttpSession session; + + private Map savedParams = new HashMap(); + + private String savedViewId; + + @Inject + private Logger logger; + + public SecurityObserver() { + clear(); + } + + private void saveCurrentState() { + clear(); + + if (!config.getLoginPage().equals(facesContext.getViewRoot().getViewId())) { + savedParams.putAll(facesContext.getExternalContext().getRequestParameterMap()); + savedViewId = facesContext.getViewRoot().getViewId(); + } + } + + public void redirectToLoginPage() { + saveCurrentState(); + + try { + Redirector.redirect(config.getLoginPage()); + + } catch (PageNotFoundException cause) { + // TODO Colocar a mensagem no bundle + throw new ConfigurationException( + "A tela de login \"" + + cause.getViewId() + + "\" não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" + + "frameworkdemoiselle.security.login.page" + "\"", cause); + } + } + + public void onLoginSuccessful(@Observes final AfterLoginSuccessful event) { + boolean redirectedFromConfig = false; + + try { + if (savedViewId != null) { + Redirector.redirect(savedViewId, savedParams); + + } else if (config.isRedirectEnabled()) { + redirectedFromConfig = true; + Redirector.redirect(config.getRedirectAfterLogin(), savedParams); + } + + } catch (PageNotFoundException cause) { + if (redirectedFromConfig) { + // TODO Colocar a mensagem no bundle + throw new ConfigurationException( + "A tela \"" + + cause.getViewId() + + "\" que é invocada após o logon não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" + + "frameworkdemoiselle.security.redirect.after.login" + "\"", cause); + } else { + throw cause; + } + + } finally { + clear(); + } + } + + public void onLogoutSuccessful(@Observes final AfterLogoutSuccessful event) { + try { + if (config.isRedirectEnabled()) { + Redirector.redirect(config.getRedirectAfterLogout()); + } + + } catch (PageNotFoundException cause) { + // TODO Colocar a mensagem no bundle + throw new ConfigurationException( + "A tela \"" + + cause.getViewId() + + "\" que é invocada após o logout não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" + + "frameworkdemoiselle.security.redirect.after.logout" + "\"", cause); + + } finally { + try { + session.invalidate(); + } catch (IllegalStateException e) { + logger.debug("Esta sessão já foi invalidada."); + } + } + } + + private void clear() { + savedViewId = null; + savedParams.clear(); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducer.java new file mode 100644 index 0000000..070ce78 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducer.java @@ -0,0 +1,61 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import javax.enterprise.context.ContextNotActiveException; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.faces.context.FacesContext; + +public class FacesContextProducer { + + @Produces + @RequestScoped + @Default + public FacesContext create() { + FacesContext ctx = FacesContext.getCurrentInstance(); + + if (ctx == null) { + // TODO Usar o bundle para a mensagem + throw new ContextNotActiveException("FacesContext isn't active"); + } + + return ctx; + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducer.java new file mode 100644 index 0000000..359ddb5 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducer.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 br.gov.frameworkdemoiselle.internal.producer; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.faces.context.FacesContext; +import javax.servlet.http.HttpServletRequest; + +public class HttpServletRequestProducer { + + @Produces + @Default + @RequestScoped + public HttpServletRequest create(final FacesContext facesContext) { + return (HttpServletRequest) facesContext.getExternalContext().getRequest(); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletResponseProducer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletResponseProducer.java new file mode 100644 index 0000000..b252efa --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletResponseProducer.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 br.gov.frameworkdemoiselle.internal.producer; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.faces.context.FacesContext; +import javax.servlet.http.HttpServletResponse; + +public class HttpServletResponseProducer { + + @Produces + @Default + @RequestScoped + public HttpServletResponse create(final FacesContext facesContext) { + return (HttpServletResponse) facesContext.getExternalContext().getResponse(); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducer.java new file mode 100644 index 0000000..8ec467b --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducer.java @@ -0,0 +1,55 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import br.gov.frameworkdemoiselle.internal.proxy.HttpSessionProxy; + +public class HttpSessionProducer { + + @Produces + @Default + @SessionScoped + public HttpSession create(final HttpServletRequest request) { + return new HttpSessionProxy(request.getSession()); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducer.java new file mode 100644 index 0000000..fb8f58f --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducer.java @@ -0,0 +1,69 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import java.io.Serializable; +import java.util.Locale; + +import javax.enterprise.context.ContextNotActiveException; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Alternative; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.Produces; +import javax.faces.context.FacesContext; +import javax.inject.Named; +import javax.servlet.http.HttpServletRequest; + +import br.gov.frameworkdemoiselle.util.Beans; + +@SessionScoped +@Alternative +public class JsfLocaleProducer implements Serializable { + + private static final long serialVersionUID = 1L; + + private boolean loaded = false; + + @Produces + @Default + @Named("currentLocale") + public Locale create() { + Locale locale; + + try { + FacesContext facesContext = Beans.getReference(FacesContext.class); + + if (!loaded) { + if (facesContext != null) { + HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); + locale = request.getLocale(); + facesContext.getApplication().setDefaultLocale(locale); + } + + loaded = true; + } + locale = facesContext.getApplication().getDefaultLocale(); + + } catch (ContextNotActiveException cause) { + locale = Locale.getDefault(); + } + + return locale; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxy.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxy.java new file mode 100644 index 0000000..4880f20 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxy.java @@ -0,0 +1,147 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import java.io.Serializable; +import java.util.Enumeration; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionContext; + +@SuppressWarnings("deprecation") +public class HttpSessionProxy implements HttpSession, Serializable { + + private static final long serialVersionUID = 1L; + + private transient final HttpSession delegate; + + public HttpSessionProxy(HttpSession httpSession) { + this.delegate = httpSession; + } + + @Override + public long getCreationTime() { + return this.delegate.getCreationTime(); + } + + @Override + public String getId() { + return this.delegate.getId(); + } + + @Override + public long getLastAccessedTime() { + return this.delegate.getLastAccessedTime(); + } + + @Override + public ServletContext getServletContext() { + return this.delegate.getServletContext(); + } + + @Override + public void setMaxInactiveInterval(int interval) { + this.delegate.setMaxInactiveInterval(interval); + } + + @Override + public int getMaxInactiveInterval() { + return this.delegate.getMaxInactiveInterval(); + } + + @Override + @Deprecated + public HttpSessionContext getSessionContext() { + return this.delegate.getSessionContext(); + } + + @Override + public Object getAttribute(String name) { + return this.delegate.getAttribute(name); + } + + @Override + @Deprecated + public Object getValue(String name) { + return this.delegate.getValue(name); + } + + @Override + public Enumeration getAttributeNames() { + return this.delegate.getAttributeNames(); + } + + @Override + @Deprecated + public String[] getValueNames() { + return this.delegate.getValueNames(); + } + + @Override + public void setAttribute(String name, Object value) { + this.delegate.setAttribute(name, value); + } + + @Override + @Deprecated + public void putValue(String name, Object value) { + this.delegate.putValue(name, value); + } + + @Override + public void removeAttribute(String name) { + this.delegate.removeAttribute(name); + } + + @Override + @Deprecated + public void removeValue(String name) { + this.delegate.removeValue(name); + } + + @Override + public void invalidate() { + this.delegate.invalidate(); + } + + @Override + public boolean isNew() { + return this.delegate.isNew(); + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBean.java new file mode 100644 index 0000000..08b2a2a --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBean.java @@ -0,0 +1,156 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import javax.faces.context.FacesContext; +import javax.faces.convert.Converter; +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Parameter; +import br.gov.frameworkdemoiselle.util.Reflections; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +import com.sun.faces.util.Util; + +public abstract class AbstractEditPageBean extends AbstractPageBean implements EditPageBean { + + private static final long serialVersionUID = 1L; + + @Inject + private Parameter id; + + private T bean; + + private Class beanClass; + + private Class idClass; + + @Inject + @Name("demoiselle-jsf-bundle") + private ResourceBundle bundle; + + @Inject + private FacesContext facesContext; + + protected void clear() { + this.id = null; + this.bean = null; + } + + protected T createBean() { + return Beans.getReference(getBeanClass()); + } + + @Override + public T getBean() { + if (this.bean == null) { + initBean(); + } + + return this.bean; + } + + protected Class getBeanClass() { + if (this.beanClass == null) { + this.beanClass = Reflections.getGenericTypeArgument(this.getClass(), 0); + } + + return this.beanClass; + } + + protected Class getIdClass() { + if (this.idClass == null) { + this.idClass = Reflections.getGenericTypeArgument(this.getClass(), 1); + } + + return this.idClass; + } + + @Override + @SuppressWarnings("unchecked") + public I getId() { + Converter converter = getIdConverter(); + + if(converter == null && String.class.equals(getIdClass())) { + return (I) id.getValue(); + + } else if (converter == null) { + throw new DemoiselleException(bundle.getString("id-converter-not-found", getIdClass().getCanonicalName())); + + } else { + return (I) converter.getAsObject(facesContext, facesContext.getViewRoot(), id.getValue()); + } + } + + private Converter getIdConverter() { + return Util.getConverterForClass(getIdClass(), facesContext); + } + + protected abstract void handleLoad(); + + private void initBean() { + if (isUpdateMode()) { + this.bean = this.loadBean(); + } else { + setBean(createBean()); + } + } + + @Override + public boolean isUpdateMode() { + return getId() != null; + } + + private T loadBean() { + this.handleLoad(); + return this.bean; + } + + protected void setBean(final T bean) { + this.bean = bean; + } + + // protected void setId(final I id) { + // clear(); + // String value = getIdConverter().getAsString(getFacesContext(), getFacesContext().getViewRoot(), id); + // this.id.setValue(value); + // } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractListPageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractListPageBean.java new file mode 100644 index 0000000..9139802 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractListPageBean.java @@ -0,0 +1,117 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.model.DataModel; +import javax.faces.model.ListDataModel; +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.Reflections; + +public abstract class AbstractListPageBean extends AbstractPageBean implements ListPageBean { + + private static final long serialVersionUID = 1L; + + private List resultList; + + private transient DataModel dataModel; + + private Map selection = new HashMap(); + + @Inject + private PaginationContext paginationContext; + + public void clear() { + this.dataModel = null; + this.resultList = null; + } + + private Class beanClass; + + protected Class getBeanClass() { + if (this.beanClass == null) { + this.beanClass = Reflections.getGenericTypeArgument(this.getClass(), 0); + } + + return this.beanClass; + } + + @Override + public DataModel getDataModel() { + System.out.println("MODIFICADO!!!!!##@#@#@@"); + if (this.dataModel == null) { + this.dataModel = new ListDataModel(this.getResultList()); + } + + return this.dataModel; + } + + @Override + public List getResultList() { + if (this.resultList == null) { + this.resultList = handleResultList(); + } + + return this.resultList; + } + + protected abstract List handleResultList(); + + @Override + public String list() { + clear(); + return getCurrentView(); + } + + public Map getSelection() { + return selection; + } + + public void setSelection(Map selection) { + this.selection = selection; + } + + public Pagination getPagination() { + return paginationContext.getPagination(getBeanClass(), true); + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractPageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractPageBean.java new file mode 100644 index 0000000..a873768 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/AbstractPageBean.java @@ -0,0 +1,100 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import javax.faces.context.FacesContext; +import javax.inject.Inject; + +import br.gov.frameworkdemoiselle.annotation.NextView; +import br.gov.frameworkdemoiselle.annotation.PreviousView; + +public abstract class AbstractPageBean implements PageBean { + + private static final long serialVersionUID = 1L; + + @Inject + private FacesContext facesContext; + + private String nextView; + + private String previousView; + + @Override + public String getCurrentView() { + return facesContext.getViewRoot().getViewId(); + } + + @Override + public String getNextView() { + + if (nextView == null) { + NextView annotation = this.getClass().getAnnotation(NextView.class); + + if (annotation != null) { + nextView = annotation.value(); + } else { + // TODO Lançar exceção orientando o usuário a anotar sua classe com essa anotação aí ou então + // sobre-escrever este método. + } + } + + return nextView; + } + + @Override + public String getPreviousView() { + + if (previousView == null) { + PreviousView annotation = this.getClass().getAnnotation(PreviousView.class); + + if (annotation != null) { + previousView = annotation.value(); + } else { + // TODO Lançar exceção orientando o usuário a anotar sua classe com essa anotação aí ou então + // sobre-escrever este método. + } + } + + return previousView; + } + + @Override + public String getTitle() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/EditPageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/EditPageBean.java new file mode 100644 index 0000000..c76be82 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/EditPageBean.java @@ -0,0 +1,52 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +public interface EditPageBean extends PageBean { + + public String delete(); + + public T getBean(); + + public Object getId(); + + public String insert(); + + public boolean isUpdateMode(); + + public String update(); +} \ No newline at end of file diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/ListPageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/ListPageBean.java new file mode 100644 index 0000000..6770d99 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/ListPageBean.java @@ -0,0 +1,55 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.util.List; +import java.util.Map; + +import javax.faces.model.DataModel; + +public interface ListPageBean extends PageBean { + + DataModel getDataModel(); + + List getResultList(); + + String list(); + + Map getSelection(); + + void setSelection(Map selection); +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/PageBean.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/PageBean.java new file mode 100644 index 0000000..602f2f8 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/template/PageBean.java @@ -0,0 +1,50 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import java.io.Serializable; + +public interface PageBean extends Serializable { + + public String getCurrentView(); + + public String getNextView(); + + public String getPreviousView(); + + public String getTitle(); +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Faces.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Faces.java new file mode 100644 index 0000000..c34fa5d --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Faces.java @@ -0,0 +1,158 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static javax.faces.application.FacesMessage.SEVERITY_ERROR; +import static javax.faces.application.FacesMessage.SEVERITY_FATAL; +import static javax.faces.application.FacesMessage.SEVERITY_INFO; +import static javax.faces.application.FacesMessage.SEVERITY_WARN; + +import java.util.List; +import java.util.Map; + +import javax.faces.application.FacesMessage; +import javax.faces.application.FacesMessage.Severity; +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; +import javax.faces.convert.Converter; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; +import br.gov.frameworkdemoiselle.message.Message; +import br.gov.frameworkdemoiselle.message.SeverityType; + +import com.sun.faces.util.Util; + +public class Faces { + + public static void addMessages(final List messages) { + if (messages != null) { + for (Message m : messages) { + addMessage(m); + } + } + } + + public static void addMessage(final Message message) { + getFacesContext().addMessage(null, parse(message)); + } + + public static void addMessage(final String clientId, final Message message) { + getFacesContext().addMessage(clientId, parse(message)); + } + + public static void addMessage(final String clientId, final Throwable throwable) { + getFacesContext().addMessage(clientId, parse(throwable)); + } + + public static void addMessage(final Throwable throwable) { + addMessage(null, throwable); + } + + private static FacesContext getFacesContext() { + return Beans.getReference(FacesContext.class); + } + + public static Severity parse(final SeverityType severityType) { + Severity result = null; + + switch (severityType) { + case INFO: + result = SEVERITY_INFO; + break; + case WARN: + result = SEVERITY_WARN; + break; + case ERROR: + result = SEVERITY_ERROR; + break; + case FATAL: + result = SEVERITY_FATAL; + } + + return result; + } + + public static FacesMessage parse(final Throwable throwable) { + FacesMessage facesMessage = new FacesMessage(); + ApplicationException annotation = throwable.getClass().getAnnotation(ApplicationException.class); + + if (annotation != null) { + facesMessage.setSeverity(parse(annotation.severity())); + } else { + facesMessage.setSeverity(SEVERITY_ERROR); + } + + if (throwable.getMessage() != null) { + facesMessage.setSummary(throwable.getMessage()); + } else { + facesMessage.setSummary(throwable.toString()); + } + + return facesMessage; + } + + public static FacesMessage parse(final Message message) { + FacesMessage facesMessage = new FacesMessage(); + facesMessage.setSeverity(parse(message.getSeverity())); + facesMessage.setSummary(message.getText()); + return facesMessage; + } + + public static Object convert(final String value, final Converter converter) { + Object result = null; + + if (!Strings.isEmpty(value)) { + if (converter != null) { + result = converter.getAsObject(getFacesContext(), getFacesContext().getViewRoot(), value); + } else { + result = new String(value); + } + } + + return result; + } + + public static Converter getConverter(Class clazz) { + return Util.getConverterForClass(clazz, getFacesContext()); + } + + public static Map getViewMap() { + UIViewRoot viewRoot = getFacesContext().getViewRoot(); + return viewRoot.getViewMap(true); + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/FileRenderer.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/FileRenderer.java new file mode 100644 index 0000000..cccf135 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/FileRenderer.java @@ -0,0 +1,76 @@ +package br.gov.frameworkdemoiselle.util; + +import java.io.File; +import java.io.InputStream; +import java.io.Serializable; + +/** + * Defines the default behavior of the objects responsible for rendering files to the user. + * + * @author SERPRO + */ +public interface FileRenderer extends Serializable { + + /** + * Renders a byteArray for display to the user. + * + * @param byteArray Byte Array to be rendered. + * @param contentType + * @param fileName + */ + void render(final byte[] byteArray, final ContentType contentType, final String fileName); + + /** + * Renders an inputStream for display to the user. + * + * @param stream + * @param contentType + * @param fileName + */ + void render(final InputStream stream, final ContentType contentType, final String fileName); + + /** + * Renders a file for display to the user. + * + * @param file + * @param contentType + * @param fileName + */ + void render(final File file, final ContentType contentType, final String fileName); + + /** + * File content type. + * + * @author SERPRO + */ + public enum ContentType { + CSV("text/plain"), + HTML("text/html"), + ODT("application/vnd.oasis.opendocument.text"), + PDF("application/pdf"), + RTF("application/rtf"), + TXT("text/plain"), + XLS("application/vnd.ms-excel"); + + private String contentType; + + /** + * Constructor receiving the fields alias and content type. + * @param alias Alias of content type + * @param contentType Value of content type + */ + private ContentType(String contentType){ + this.contentType = contentType; + } + + /** + * Return the content type of Type + * @return Content Type + */ + public String getContentType() { + return contentType; + } + + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Locales.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Locales.java new file mode 100644 index 0000000..6b2f17f --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Locales.java @@ -0,0 +1,68 @@ +/* + * 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 General Public License version 2 + * 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 General Public License + * 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 Licença Pública Geral GNU como publicada pela Fundação + * do Software Livre (FSF); na versão 2 da Licença. + * + * 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/GPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse o Portal do Software Público + * Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software + * Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package br.gov.frameworkdemoiselle.util; + +import java.io.Serializable; +import java.util.Locale; + +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; + +@Named +public class Locales implements Serializable { + + private static final long serialVersionUID = 1L; + + private static final Locale PT_BR = new Locale("pt", "BR"); + + @Inject + private FacesContext facesContext; + + public void setEnglish() { + setLocale(Locale.US); + } + + public void setPortuguese() { + setLocale(PT_BR); + } + + protected void setLocale(Locale locale) { + facesContext.getApplication().setDefaultLocale(locale); + } + +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/PageNotFoundException.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/PageNotFoundException.java new file mode 100644 index 0000000..16ead5c --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/PageNotFoundException.java @@ -0,0 +1,20 @@ +package br.gov.frameworkdemoiselle.util; + +import br.gov.frameworkdemoiselle.DemoiselleException; + +public class PageNotFoundException extends DemoiselleException { + + private static final long serialVersionUID = 1L; + + private final String viewId; + + public PageNotFoundException(String viewId) { + // TODO Colocar a mensage no bundle + super(viewId + " not found"); + this.viewId = viewId; + } + + public String getViewId() { + return viewId; + } +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Parameter.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Parameter.java new file mode 100644 index 0000000..ff795bb --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Parameter.java @@ -0,0 +1,50 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import javax.faces.convert.Converter; + +public interface Parameter { + + void setValue(T value); + + String getKey(); + + T getValue(); + + Converter getConverter(); +} diff --git a/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Redirector.java b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Redirector.java new file mode 100644 index 0000000..a415bd4 --- /dev/null +++ b/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/util/Redirector.java @@ -0,0 +1,56 @@ +package br.gov.frameworkdemoiselle.util; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.FacesException; +import javax.faces.application.ViewHandler; +import javax.faces.context.FacesContext; + +public class Redirector implements Serializable { + + private static final long serialVersionUID = 1L; + + public static void redirect(String viewId) { + redirect(viewId, null); + } + + public static void redirect(String viewId, Map params) { + try { + if (viewId != null && !viewId.isEmpty()) { + FacesContext facesContext = Beans.getReference(FacesContext.class); + ViewHandler viewHandler = facesContext.getApplication().getViewHandler(); + String url = viewHandler.getBookmarkableURL(facesContext, viewId, parse(params), true); + + facesContext.getExternalContext().redirect(url); + } + + } catch (NullPointerException cause) { + throw new PageNotFoundException(viewId); + + } catch (IOException cause) { + throw new FacesException(cause); + } + } + + private static Map> parse(Map map) { + Map> result = null; + + if (map != null) { + ArrayList list; + result = new HashMap>(); + + for (String key : map.keySet()) { + list = new ArrayList(); + list.add(map.get(key).toString()); + result.put(key, list); + } + } + + return result; + } +} diff --git a/extension/jsf/src/main/resources/META-INF/beans.xml b/extension/jsf/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..56ff469 --- /dev/null +++ b/extension/jsf/src/main/resources/META-INF/beans.xml @@ -0,0 +1,44 @@ + + + + + br.gov.frameworkdemoiselle.internal.producer.JsfLocaleProducer + + + \ No newline at end of file diff --git a/extension/jsf/src/main/resources/META-INF/faces-config.xml b/extension/jsf/src/main/resources/META-INF/faces-config.xml new file mode 100644 index 0000000..16527b2 --- /dev/null +++ b/extension/jsf/src/main/resources/META-INF/faces-config.xml @@ -0,0 +1,63 @@ + + + + + br.gov.frameworkdemoiselle.internal.implementation.MessagePhaseListener + + + + br.gov.frameworkdemoiselle.internal.implementation.AuthenticationExceptionHandlerFactory + br.gov.frameworkdemoiselle.internal.implementation.AuthorizationExceptionHandlerFactory + br.gov.frameworkdemoiselle.internal.implementation.ApplicationExceptionHandlerFactory + br.gov.frameworkdemoiselle.internal.implementation.RedirectExceptionHandlerFactory + + + + + messages + messages + + + + pt + pt + en + + + diff --git a/extension/jsf/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/extension/jsf/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000..59c93fd --- /dev/null +++ b/extension/jsf/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1 @@ +br.gov.frameworkdemoiselle.internal.bootstrap.JsfBootstrap diff --git a/extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties b/extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties new file mode 100644 index 0000000..52a1346 --- /dev/null +++ b/extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties @@ -0,0 +1,36 @@ +# 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. + +id-converter-not-found=Voc\u00EA precisa criar um FacesConverter para a classe "{0}". \ No newline at end of file diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/FacesBootstrapTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/FacesBootstrapTest.java new file mode 100644 index 0000000..f45706a --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/bootstrap/FacesBootstrapTest.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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.enterprise.inject.spi.AfterBeanDiscovery; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.internal.context.ViewContext; + +@RunWith(PowerMockRunner.class) +public class FacesBootstrapTest { + + private JsfBootstrap bootstrap; + + @Before + public void before() { + bootstrap = new JsfBootstrap(); + } + + @Test + public void testLoadContexts() { + AfterBeanDiscovery event = createMock(AfterBeanDiscovery.class); + event.addContext(EasyMock.anyObject(ViewContext.class)); + replay(event); + bootstrap.loadContexts(event); + verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java new file mode 100644 index 0000000..f51f056 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java @@ -0,0 +1,145 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.context; + +import static junit.framework.Assert.assertEquals; + +import java.util.Map; + +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.util.Faces; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Faces.class }) +public class ViewContextTest { + + private ViewContext context; + + @Before + public void before() { + context = new ViewContext(); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetViewMapContainsInstance() { + String instance = "instance"; + + Bean bean = PowerMock.createMock(Bean.class); + EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); + + Map map = PowerMock.createMock(Map.class); + EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(true); + EasyMock.expect(map.get(EasyMock.anyObject(String.class))).andReturn(instance); + + PowerMock.mockStatic(Faces.class); + EasyMock.expect(Faces.getViewMap()).andReturn(map); + + PowerMock.replay(Faces.class, bean, map); + + assertEquals(instance, context.get(bean)); + + PowerMock.verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetViewMapDoesNotContainsInstance() { + String instance = "instance"; + + Bean bean = PowerMock.createMock(Bean.class); + EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); + EasyMock.expect(bean.create(EasyMock.anyObject(CreationalContext.class))).andReturn(instance); + + Map map = PowerMock.createMock(Map.class); + EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); + EasyMock.expect(map.put(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(null); + + PowerMock.mockStatic(Faces.class); + EasyMock.expect(Faces.getViewMap()).andReturn(map); + + CreationalContext creationalContext = PowerMock.createMock(CreationalContext.class); + + PowerMock.replay(Faces.class, bean, map, creationalContext); + + assertEquals(instance, context.get(bean, creationalContext)); + + PowerMock.verifyAll(); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetViewMapInstanceNull() { + String instance = "instance"; + + Bean bean = PowerMock.createMock(Bean.class); + EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); + + Map map = PowerMock.createMock(Map.class); + EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); + + PowerMock.mockStatic(Faces.class); + EasyMock.expect(Faces.getViewMap()).andReturn(map); + + PowerMock.replay(Faces.class, bean, map); + + assertEquals(null, context.get(bean)); + + PowerMock.verifyAll(); + } + + @Test + public void testScopeClass() { + assertEquals(ViewScoped.class, context.getScope()); + } + + @Test + public void testIsActive() { + assertEquals(true, context.isActive()); + } +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactoryTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactoryTest.java new file mode 100644 index 0000000..bddd3b4 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerFactoryTest.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 br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class ApplicationExceptionHandlerFactoryTest { + + @Test + public void testGetExceptionHandler() { + + ExceptionHandler jsfExceptionHandler = PowerMock.createMock(ExceptionHandler.class); + + ExceptionHandlerFactory jsfFactory = PowerMock.createMock(ExceptionHandlerFactory.class); + + ApplicationExceptionHandlerFactory handlerFactory = new ApplicationExceptionHandlerFactory(jsfFactory); + expect(jsfFactory.getExceptionHandler()).andReturn(jsfExceptionHandler); + + replayAll(); + + ApplicationExceptionHandler handler = (ApplicationExceptionHandler) handlerFactory.getExceptionHandler(); + + assertEquals(handler.getWrapped(), jsfExceptionHandler); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerTest.java new file mode 100644 index 0000000..e4e8a7f --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ApplicationExceptionHandlerTest.java @@ -0,0 +1,171 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; +import javax.faces.event.PhaseId; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; +import br.gov.frameworkdemoiselle.internal.configuration.ExceptionHandlerConfig; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Faces; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class, FacesContext.class, Faces.class }) +public class ApplicationExceptionHandlerTest { + + private ApplicationExceptionHandler handler; + + private ExceptionQueuedEventContext eventContext; + + private ExceptionHandlerConfig config; + + private FacesContext facesContext; + + private Collection events; + + @SuppressWarnings("serial") + @ApplicationException + class AnnotatedAppException extends RuntimeException { + } + + @SuppressWarnings("serial") + class SomeException extends RuntimeException { + } + + @Before + public void setUp() { + + mockStatic(Beans.class); + mockStatic(FacesContext.class); + + events = new ArrayList(); + ExceptionHandler jsfExceptionHandler = createMock(ExceptionHandler.class); + handler = new ApplicationExceptionHandler(jsfExceptionHandler); + eventContext = PowerMock.createMock(ExceptionQueuedEventContext.class); + ExceptionQueuedEvent event = PowerMock.createMock(ExceptionQueuedEvent.class); + config = PowerMock.createMock(ExceptionHandlerConfig.class); + facesContext = PowerMock.createMock(FacesContext.class); + + expect(event.getSource()).andReturn(eventContext); + expect(Beans.getReference(ExceptionHandlerConfig.class)).andReturn(config); + expect(FacesContext.getCurrentInstance()).andReturn(facesContext).anyTimes(); + expect(handler.getUnhandledExceptionQueuedEvents()).andReturn(events).times(2); + + events.add(event); + + } + + @Test + public void testHandleAnApplicationExceptionNotOnRenderResponse() { + + mockStatic(Faces.class); + + AnnotatedAppException exception = new AnnotatedAppException(); + PhaseId phaseId = PowerMock.createMock(PhaseId.class); + + expect(eventContext.getException()).andReturn(exception); + expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + expect(config.isHandleApplicationException()).andReturn(true); + + Faces.addMessage(exception); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertTrue(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnApplicationExceptionOnRenderResponse() { + + AnnotatedAppException exception = new AnnotatedAppException(); +// PhaseId phaseId = PhaseId.RENDER_RESPONSE; + + expect(eventContext.getException()).andReturn(exception); +// expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + expect(config.isHandleApplicationException()).andReturn(false); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnyException() { + + SomeException exception = new SomeException(); +// PhaseId phaseId = PowerMock.createMock(PhaseId.class); + + expect(eventContext.getException()).andReturn(exception); +// expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + expect(config.isHandleApplicationException()).andReturn(true); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testDoNotHandleApplicationExceptions() { + + AnnotatedAppException exception = new AnnotatedAppException(); + + expect(eventContext.getException()).andReturn(exception); + expect(config.isHandleApplicationException()).andReturn(false); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactoryTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactoryTest.java new file mode 100644 index 0000000..fd3ad29 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerFactoryTest.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 br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class AuthenticationExceptionHandlerFactoryTest { + + @Test + public void testGetExceptionHandler() { + + ExceptionHandler jsfExceptionHandler = PowerMock.createMock(ExceptionHandler.class); + + ExceptionHandlerFactory jsfFactory = PowerMock.createMock(ExceptionHandlerFactory.class); + + AuthenticationExceptionHandlerFactory handlerFactory = new AuthenticationExceptionHandlerFactory(jsfFactory); + expect(jsfFactory.getExceptionHandler()).andReturn(jsfExceptionHandler); + + replayAll(); + + AuthenticationExceptionHandler handler = (AuthenticationExceptionHandler) handlerFactory.getExceptionHandler(); + + assertEquals(handler.getWrapped(), jsfExceptionHandler); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerTest.java new file mode 100644 index 0000000..74e2d1f --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthenticationExceptionHandlerTest.java @@ -0,0 +1,98 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.faces.context.ExceptionHandler; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.security.NotLoggedInException; +import br.gov.frameworkdemoiselle.util.Beans; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class, CoreBundle.class }) +public class AuthenticationExceptionHandlerTest { + + private AuthenticationExceptionHandler handler; + + private ExceptionQueuedEventContext eventContext; + + private Collection events; + + @Before + public void setUp() { + + mockStatic(Beans.class); + + events = new ArrayList(); + ExceptionHandler jsfExceptionHandler = createMock(ExceptionHandler.class); + handler = new AuthenticationExceptionHandler(jsfExceptionHandler); + eventContext = createMock(ExceptionQueuedEventContext.class); + ExceptionQueuedEvent event = createMock(ExceptionQueuedEvent.class); + + expect(event.getSource()).andReturn(eventContext); + expect(handler.getUnhandledExceptionQueuedEvents()).andReturn(events).times(2); + + events.add(event); + + } + + @Test + public void testHandleNotLoggedInException() { + + NotLoggedInException exception = new NotLoggedInException(""); + + SecurityObserver observer = createMock(SecurityObserver.class); + expect(Beans.getReference(SecurityObserver.class)).andReturn(observer); + expect(eventContext.getException()).andReturn(exception); + + observer.redirectToLoginPage(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertTrue(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnyException() { + + Exception exception = new Exception(); + + expect(eventContext.getException()).andReturn(exception); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactoryTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactoryTest.java new file mode 100644 index 0000000..dedf7ec --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerFactoryTest.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 br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class AuthorizationExceptionHandlerFactoryTest { + + @Test + public void testGetExceptionHandler() { + + ExceptionHandler jsfExceptionHandler = PowerMock.createMock(ExceptionHandler.class); + + ExceptionHandlerFactory jsfFactory = PowerMock.createMock(ExceptionHandlerFactory.class); + + AuthorizationExceptionHandlerFactory handlerFactory = new AuthorizationExceptionHandlerFactory(jsfFactory); + expect(jsfFactory.getExceptionHandler()).andReturn(jsfExceptionHandler); + + replayAll(); + + AuthorizationExceptionHandler handler = (AuthorizationExceptionHandler) handlerFactory.getExceptionHandler(); + + assertEquals(handler.getWrapped(), jsfExceptionHandler); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerTest.java new file mode 100644 index 0000000..d834d04 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/AuthorizationExceptionHandlerTest.java @@ -0,0 +1,135 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.FacesContext; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; +import javax.faces.event.PhaseId; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.security.AuthorizationException; +import br.gov.frameworkdemoiselle.util.Faces; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ FacesContext.class, CoreBundle.class, Faces.class }) +public class AuthorizationExceptionHandlerTest { + + private AuthorizationExceptionHandler handler; + + private ExceptionQueuedEventContext eventContext; + + private Collection events; + + private FacesContext facesContext; + + @Before + public void setUp() { + + mockStatic(FacesContext.class); + + events = new ArrayList(); + ExceptionHandler jsfExceptionHandler = createMock(ExceptionHandler.class); + handler = new AuthorizationExceptionHandler(jsfExceptionHandler); + eventContext = createMock(ExceptionQueuedEventContext.class); + ExceptionQueuedEvent event = createMock(ExceptionQueuedEvent.class); + facesContext = PowerMock.createMock(FacesContext.class); + + expect(event.getSource()).andReturn(eventContext); + events.add(event); + expect(handler.getUnhandledExceptionQueuedEvents()).andReturn(events).times(2); + expect(FacesContext.getCurrentInstance()).andReturn(facesContext).anyTimes(); + + + } + + @Test + public void testHandleAnAuthorizationExceptionNotOnRenderResponse() { + + mockStatic(Faces.class); + +// ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + + AuthorizationException exception = new AuthorizationException(""); + PhaseId phaseId = PowerMock.createMock(PhaseId.class); + + expect(eventContext.getException()).andReturn(exception); + expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + + Faces.addMessage(exception); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertTrue(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnAuthorizationExceptionOnRenderResponse() { + +// ResourceBundle bundle = new ResourceBundle(ResourceBundle.getBundle("demoiselle-core-bundle")); + + AuthorizationException exception = new AuthorizationException(""); + PhaseId phaseId = PhaseId.RENDER_RESPONSE; + + expect(eventContext.getException()).andReturn(exception); + expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnyException() { + + Exception exception = new Exception(); + PhaseId phaseId = PowerMock.createMock(PhaseId.class); + + expect(eventContext.getException()).andReturn(exception); + expect(facesContext.getCurrentPhaseId()).andReturn(phaseId); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImplTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImplTest.java new file mode 100644 index 0000000..126420f --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/FileRendererImplTest.java @@ -0,0 +1,130 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import java.io.IOException; + +import javax.faces.context.FacesContext; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.Assert; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.util.Faces; +import br.gov.frameworkdemoiselle.util.FileRenderer; +import br.gov.frameworkdemoiselle.util.FileRenderer.ContentType; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Faces.class }) +public class FileRendererImplTest { + + private Logger logger; + + private FileRenderer renderer; + + private FacesContext facesContext; + + private HttpServletResponse response; + + @Before + public void before() { + renderer = new FileRendererImpl(); + + logger = PowerMock.createMock(Logger.class); + Whitebox.setInternalState(renderer, "logger", logger); + + facesContext = PowerMock.createMock(FacesContext.class); + Whitebox.setInternalState(renderer, "context", facesContext); + + response = PowerMock.createMock(HttpServletResponse.class); + Whitebox.setInternalState(renderer, "response", response); + } + + @Test + public void testRenderBytesFail() { + byte[] bytes = "Test".getBytes(); + String fileName = "fileName.pdf"; + + logger.debug(EasyMock.anyObject(String.class)); + EasyMock.expectLastCall().anyTimes(); + + IOException exception = new IOException(); + logger.info("Erro na geração do relatório. Incluíndo a exceção de erro em um FacesMessage", exception); + EasyMock.expectLastCall().anyTimes(); + + response.setContentType(ContentType.PDF.getContentType()); + EasyMock.expectLastCall().times(1); + + response.setContentLength(bytes.length); + EasyMock.expectLastCall().times(1); + + response.setHeader("Content-Disposition", "filename=\"" + fileName + "\""); + EasyMock.expectLastCall().times(1); + + facesContext.responseComplete(); + EasyMock.expectLastCall().times(1); + + try { + EasyMock.expect(response.getOutputStream()).andThrow(exception); + } catch (IOException e) { + Assert.fail(); + } + + PowerMock.mockStatic(Faces.class); + Faces.addMessage(exception); + + PowerMock.replayAll(); + renderer.render(bytes, ContentType.PDF, fileName); + PowerMock.verifyAll(); + } + + @Test + public void testRenderBytesSuccess() { + byte[] bytes = "Test".getBytes(); + String fileName = "fileName.pdf"; + + logger.debug(EasyMock.anyObject(String.class)); + EasyMock.expectLastCall().anyTimes(); + + facesContext.responseComplete(); + EasyMock.expectLastCall().times(1); + + response.setContentType(ContentType.PDF.getContentType()); + EasyMock.expectLastCall().times(1); + + response.setContentLength(bytes.length); + EasyMock.expectLastCall().times(1); + + response.setHeader("Content-Disposition", "filename=\"" + fileName + "\""); + EasyMock.expectLastCall().times(1); + + ServletOutputStream stream = PowerMock.createMock(ServletOutputStream.class); + try { + stream.write(bytes, 0, bytes.length); + EasyMock.expectLastCall().times(1); + + stream.flush(); + EasyMock.expectLastCall().times(1); + + stream.close(); + EasyMock.expectLastCall().times(1); + + EasyMock.expect(response.getOutputStream()).andReturn(stream).times(3); + } catch (IOException e) { + Assert.fail(); + } + + PowerMock.replayAll(); + renderer.render(bytes, ContentType.PDF, fileName); + PowerMock.verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListenerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListenerTest.java new file mode 100644 index 0000000..a35e1f2 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/MessagePhaseListenerTest.java @@ -0,0 +1,115 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.List; + +import javax.faces.event.PhaseEvent; +import javax.faces.event.PhaseId; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; +import br.gov.frameworkdemoiselle.message.Message; +import br.gov.frameworkdemoiselle.message.MessageContext; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Faces; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ LoggerProducer.class, Beans.class, Faces.class }) +public class MessagePhaseListenerTest { + + private MessagePhaseListener m; + + private Logger logger; + + @Before + public void before() { + PowerMock.mockStatic(LoggerProducer.class); + logger = PowerMock.createMock(Logger.class); + expect(LoggerProducer.create(MessagePhaseListener.class)).andReturn(logger); + } + + @Test + public void testGetPhaseId() { + m = new MessagePhaseListener(); + Assert.assertEquals(PhaseId.RENDER_RESPONSE, m.getPhaseId()); + } + + @Test + public void testBeforePhase() { + + mockStatic(Beans.class); + mockStatic(Faces.class); + + PhaseEvent event = PowerMock.createMock(PhaseEvent.class); + MessageContext mc = PowerMock.createMock(MessageContext.class); + + logger.debug(EasyMock.anyObject(String.class)); + logger.debug(EasyMock.anyObject(String.class)); + + List list = new ArrayList(); + + expect(event.getPhaseId()).andReturn(PhaseId.RENDER_RESPONSE); + expect(Beans.getReference(MessageContext.class)).andReturn(mc); + expect(mc.getMessages()).andReturn(list).anyTimes(); + + mc.clear(); + Faces.addMessages(list); + + replayAll(); + m = new MessagePhaseListener(); + m.beforePhase(event); + m.afterPhase(event); + verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImplTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImplTest.java new file mode 100644 index 0000000..ab0e232 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/ParameterImplTest.java @@ -0,0 +1,325 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.implementation; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.lang.reflect.Member; +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.spi.Annotated; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.faces.convert.Converter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.util.Faces; +import br.gov.frameworkdemoiselle.util.Reflections; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Reflections.class, Faces.class }) +public class ParameterImplTest { + + private ParameterImpl param; + + private HttpServletRequest request; + + private InjectionPoint ip; + + private Converter converter; + + private Annotated annotated; + + private Name name; + + private HttpSession session; + + private Member member; + + @Before + public void before() { + ip = createMock(InjectionPoint.class); + request = createMock(HttpServletRequest.class); + session = createMock(HttpSession.class); + annotated = createMock(Annotated.class); + name = createMock(Name.class); + converter = createMock(Converter.class); + member = createMock(Member.class); + + mockStatic(Reflections.class); + mockStatic(Faces.class); + } + + private void prepareForTestWithKeyFromNameAnnotation() { + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + expect(ip.getMember()).andReturn(null); + expect(annotated.isAnnotationPresent(Name.class)).andReturn(true); + expect(annotated.getAnnotation(Name.class)).andReturn(name); + expect(name.value()).andReturn("name"); + expect(Reflections.getGenericTypeArgument(EasyMock.anyObject(Member.class), EasyMock.anyInt())).andReturn( + Object.class); + expect(Faces.getConverter(EasyMock.anyObject(Class.class))).andReturn(converter); + } + + @Test + public void testConstructorCase1() { + this.prepareForTestWithKeyFromNameAnnotation(); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("name", param.getKey()); + assertEquals(Object.class, Whitebox.getInternalState(param, "type")); + assertEquals(converter, param.getConverter()); + verifyAll(); + } + + @Test + public void testConstructorCase2() { + expect(member.getName()).andReturn("memberName"); + expect(ip.getAnnotated()).andReturn(annotated).anyTimes(); + expect(ip.getMember()).andReturn(member).anyTimes(); + expect(annotated.isAnnotationPresent(Name.class)).andReturn(false); + expect(Reflections.getGenericTypeArgument(EasyMock.anyObject(Member.class), EasyMock.anyInt())).andReturn( + Object.class); + expect(Faces.getConverter(EasyMock.anyObject(Class.class))).andReturn(converter); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("memberName", param.getKey()); + assertEquals(Object.class, Whitebox.getInternalState(param, "type")); + assertEquals(converter, param.getConverter()); + verifyAll(); + } + + @Test + public void testGetValueWhenSessionScopedAndParameterValueNotNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(Faces.convert("1", converter)).andReturn("return"); + expect(request.getSession()).andReturn(session).anyTimes(); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn("1"); + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(true); + expect(session.getAttribute("name")).andReturn("return"); + + session.setAttribute("name", "return"); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("return", param.getValue()); + verifyAll(); + } + + @Test + public void testGetValueWhenSessionScopedAndParameterValueNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(request.getSession()).andReturn(session).anyTimes(); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn(null); + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(true); + expect(session.getAttribute("name")).andReturn("return"); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("return", param.getValue()); + verifyAll(); + } + + @Test + public void testGetValueWhenRequestScoped() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(true); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn("1"); + expect(Faces.convert("1", converter)).andReturn("return"); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("return", param.getValue()); + verifyAll(); + } + + @Test + public void testGetValueWhenViewScopedWithParamValueNotNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + Map map = new HashMap(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(true); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn("1"); + expect(Faces.getViewMap()).andReturn(map); + expect(Faces.convert("1", converter)).andReturn("return"); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("return", param.getValue()); + assertEquals("return", map.get("name")); + verifyAll(); + } + + @Test + public void testGetValueWhenViewScopedWithParamValueNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + Map map = new HashMap(); + map.put("name", "ops"); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(true); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn(null); + expect(Faces.getViewMap()).andReturn(map); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("ops", param.getValue()); + assertEquals("ops", map.get("name")); + verifyAll(); + } + + @Test + public void testGetValueElseWithValueNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(false); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn("1"); + expect(Faces.convert("1", converter)).andReturn("return"); + + replayAll(); + param = new ParameterImpl(ip, request); + assertEquals("return", param.getValue()); + verifyAll(); + } + + @Test + public void testGetValueElseWithValueNotNull() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(false); + expect(request.getParameter(EasyMock.anyObject(String.class))).andReturn("1"); + + replayAll(); + param = new ParameterImpl(ip, request); + Whitebox.setInternalState(param, "value", "myvalue"); + assertEquals("myvalue", param.getValue()); + verifyAll(); + } + + @Test + public void testSetValueIsSessionScoped() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(true); + expect(request.getSession()).andReturn(session); + + session.setAttribute("name", 1L); + + replayAll(); + param = new ParameterImpl(ip, request); + param.setValue(1L); + verifyAll(); + } + + @Test + public void testSetValueIsViewScoped() { + this.prepareForTestWithKeyFromNameAnnotation(); + + Map map = new HashMap(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(true); + expect(Faces.getViewMap()).andReturn(map); + + replayAll(); + param = new ParameterImpl(ip, request); + param.setValue(1L); + assertEquals(1L, map.get("name")); + verifyAll(); + } + + @Test + public void testSetValueElse() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(ViewScoped.class)).andReturn(false); + + replayAll(); + param = new ParameterImpl(ip, request); + param.setValue(1L); + assertEquals(1L, Whitebox.getInternalState(param, "value")); + verifyAll(); + } + + @Test + public void testOthers() { + this.prepareForTestWithKeyFromNameAnnotation(); + + expect(annotated.isAnnotationPresent(SessionScoped.class)).andReturn(false); + expect(annotated.isAnnotationPresent(RequestScoped.class)).andReturn(true); + + replayAll(); + param = new ParameterImpl(ip, request); + param.setValue(1L); + verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactoryTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactoryTest.java new file mode 100644 index 0000000..8982a1a --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerFactoryTest.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 br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.context.ExceptionHandler; +import javax.faces.context.ExceptionHandlerFactory; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class RedirectExceptionHandlerFactoryTest { + + @Test + public void testGetExceptionHandler() { + + ExceptionHandler jsfExceptionHandler = PowerMock.createMock(ExceptionHandler.class); + + ExceptionHandlerFactory jsfFactory = PowerMock.createMock(ExceptionHandlerFactory.class); + + RedirectExceptionHandlerFactory handlerFactory = new RedirectExceptionHandlerFactory(jsfFactory); + expect(jsfFactory.getExceptionHandler()).andReturn(jsfExceptionHandler); + + replayAll(); + + RedirectExceptionHandler handler = (RedirectExceptionHandler) handlerFactory.getExceptionHandler(); + + assertEquals(handler.getWrapped(), jsfExceptionHandler); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerTest.java new file mode 100644 index 0000000..ee5d4bf --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/RedirectExceptionHandlerTest.java @@ -0,0 +1,91 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.faces.context.ExceptionHandler; +import javax.faces.event.ExceptionQueuedEvent; +import javax.faces.event.ExceptionQueuedEventContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.annotation.Redirect; + +@RunWith(PowerMockRunner.class) +public class RedirectExceptionHandlerTest { + + private RedirectExceptionHandler handler; + + private ExceptionQueuedEventContext eventContext; + + private Collection events; + + @SuppressWarnings("serial") + @Redirect + class AnnotatedException extends RuntimeException { + } + + @Before + public void setUp() { + + ExceptionHandler jsfExceptionHandler = createMock(ExceptionHandler.class); + ExceptionQueuedEvent event = createMock(ExceptionQueuedEvent.class); + eventContext = createMock(ExceptionQueuedEventContext.class); + handler = new RedirectExceptionHandler(jsfExceptionHandler); + events = new ArrayList(); + + expect(event.getSource()).andReturn(eventContext); + events.add(event); + expect(handler.getUnhandledExceptionQueuedEvents()).andReturn(events).times(2); + + } + + @Test + public void testHandleAnAnnotatedException() { + + AnnotatedException exception = new AnnotatedException(); + + expect(eventContext.getException()).andReturn(exception); + + replayAll(); + + handler.handle(); + + assertTrue(events.isEmpty()); + + verifyAll(); + + } + + @Test + public void testHandleAnyException() { + + Exception exception = new Exception(); + + expect(eventContext.getException()).andReturn(exception); + + handler.getWrapped().handle(); + expectLastCall(); + + replayAll(); + + handler.handle(); + + assertFalse(events.isEmpty()); + + verifyAll(); + + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducerTest.java new file mode 100644 index 0000000..430f892 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/FacesContextProducerTest.java @@ -0,0 +1,88 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.enterprise.context.ContextNotActiveException; +import javax.faces.context.FacesContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ FacesContext.class }) +public class FacesContextProducerTest { + + private FacesContextProducer producer; + + @Before + public void before() { + this.producer = new FacesContextProducer(); + } + + @Test + public void createOK() { + mockStatic(FacesContext.class); + FacesContext facesContext = PowerMock.createMock(FacesContext.class); + expect(FacesContext.getCurrentInstance()).andReturn(facesContext); + replay(facesContext, FacesContext.class); + assertEquals(facesContext, producer.create()); + verifyAll(); + } + + @Test + public void createNOK() { + mockStatic(FacesContext.class); + expect(FacesContext.getCurrentInstance()).andReturn(null); + replay(FacesContext.class); + try { + this.producer.create(); + fail(); + } catch(ContextNotActiveException exception) {} + verifyAll(); + } +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducerTest.java new file mode 100644 index 0000000..1056dc3 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpServletRequestProducerTest.java @@ -0,0 +1,81 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpServletRequest.class }) +public class HttpServletRequestProducerTest { + + private HttpServletRequestProducer producer; + + @Before + public void before() { + this.producer = new HttpServletRequestProducer(); + } + + @Test + public void testCreate() { + FacesContext facesContext = PowerMock.createMock(FacesContext.class); + ExternalContext externalContext = PowerMock.createMock(ExternalContext.class); + HttpServletRequest request = PowerMock.createMock(HttpServletRequest.class); + + expect(externalContext.getRequest()).andReturn(request); + expect(facesContext.getExternalContext()).andReturn(externalContext); + replay(facesContext, externalContext, request); + + assertEquals(request, producer.create(facesContext)); + + verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducerTest.java new file mode 100644 index 0000000..f9dfd8a --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/HttpSessionProducerTest.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 br.gov.frameworkdemoiselle.internal.producer; + +import javax.servlet.http.HttpServletRequest; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.internal.proxy.HttpSessionProxy; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpServletRequest.class }) +public class HttpSessionProducerTest { + + private HttpSessionProducer producer; + + @Before + public void before() { + producer = new HttpSessionProducer(); + } + + @Test + public void testCreate() { + HttpServletRequest request = PowerMock.createMock(HttpServletRequest.class); + EasyMock.expect(request.getSession()).andReturn(null); + Assert.assertTrue(producer.create(request).getClass().equals(HttpSessionProxy.class)); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducerTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducerTest.java new file mode 100644 index 0000000..036c19c --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/producer/JsfLocaleProducerTest.java @@ -0,0 +1,109 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.producer; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.Locale; + +import javax.enterprise.context.ContextNotActiveException; +import javax.faces.application.Application; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.util.Beans; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class }) +public class JsfLocaleProducerTest { + + private JsfLocaleProducer producer; + + @Before + public void before() { + producer = new JsfLocaleProducer(); + } + + @Test + public void testCreateOK() { + mockStatic(Beans.class); + + Locale locale = PowerMock.createMock(Locale.class); + Application application = PowerMock.createMock(Application.class); + FacesContext facesContext = PowerMock.createMock(FacesContext.class); + ExternalContext externalContext = PowerMock.createMock(ExternalContext.class); + HttpServletRequest httpServletRequest = PowerMock.createMock(HttpServletRequest.class); + + expect(Beans.getReference(FacesContext.class)).andReturn(facesContext); + expect(facesContext.getExternalContext()).andReturn(externalContext); + expect(externalContext.getRequest()).andReturn(httpServletRequest); + expect(httpServletRequest.getLocale()).andReturn(locale); + expect(facesContext.getApplication()).andReturn(application).anyTimes(); + application.setDefaultLocale(locale); + expect(application.getDefaultLocale()).andReturn(locale); + + replayAll(); + + Locale returned = producer.create(); + assertEquals(returned, locale); + + verifyAll(); + } + + @Test + public void testCreateNOK() { + mockStatic(Beans.class); + expect(Beans.getReference(FacesContext.class)).andThrow(new ContextNotActiveException()); + replayAll(); + Locale returned = producer.create(); + assertEquals(Locale.getDefault(), returned); + verifyAll(); + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxyTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxyTest.java new file mode 100644 index 0000000..317e26c --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/proxy/HttpSessionProxyTest.java @@ -0,0 +1,126 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.proxy; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; + +import java.util.Enumeration; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@SuppressWarnings("deprecation") +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpSession.class, ServletContext.class, Enumeration.class, HttpSessionContext.class }) +public class HttpSessionProxyTest { + + private HttpSessionProxy proxy; + + private ServletContext servletContext; + + private Enumeration enumeration; + + private HttpSession session; + + private HttpSessionContext sessionContext; + + @Before + public void before() { + session = PowerMock.createMock(HttpSession.class); + servletContext = PowerMock.createMock(ServletContext.class); + enumeration = PowerMock.createMock(Enumeration.class); + sessionContext = PowerMock.createMock(HttpSessionContext.class); + + expect(session.getValueNames()).andReturn(new String[] {"abcdef"}); + expect(session.getValue("value")).andReturn("value"); + expect(session.getSessionContext()).andReturn(sessionContext); + expect(session.getCreationTime()).andReturn(10L); + expect(session.getId()).andReturn("ID"); + expect(session.getLastAccessedTime()).andReturn(1L); + expect(session.getServletContext()).andReturn(servletContext); + expect(session.getMaxInactiveInterval()).andReturn(2); + expect(session.getAttribute("attribute")).andReturn("attribute-1"); + expect(session.getAttributeNames()).andReturn(enumeration); + expect(session.isNew()).andReturn(true); + + session.removeValue("removeValue"); + session.putValue("put", "it"); + session.invalidate(); + session.removeAttribute("remove"); + session.setAttribute("name", "object"); + session.setMaxInactiveInterval(1); + + replay(session); + + proxy = new HttpSessionProxy(session); + } + + @Test + public void testDelegation() { + assertEquals(sessionContext, proxy.getSessionContext()); + assertEquals("value", proxy.getValue("value")); + assertEquals("abcdef", proxy.getValueNames()[0]); + assertEquals(10L, proxy.getCreationTime()); + assertEquals("ID", proxy.getId()); + assertEquals(1L, proxy.getLastAccessedTime()); + assertEquals(servletContext, proxy.getServletContext()); + assertEquals(2, proxy.getMaxInactiveInterval()); + assertEquals("attribute-1", proxy.getAttribute("attribute")); + assertEquals(enumeration, proxy.getAttributeNames()); + assertEquals(true, proxy.isNew()); + + proxy.removeValue("removeValue"); + proxy.putValue("put","it"); + proxy.invalidate(); + proxy.removeAttribute("remove"); + proxy.setAttribute("name", "object"); + proxy.setMaxInactiveInterval(1); + + verify(session); + } +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBeanTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBeanTest.java new file mode 100644 index 0000000..48dc0ca --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractEditPageBeanTest.java @@ -0,0 +1,323 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; +import static org.powermock.reflect.Whitebox.setInternalState; + +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; +import javax.faces.convert.Converter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.DemoiselleException; +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.Parameter; +import br.gov.frameworkdemoiselle.util.Reflections; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +import com.sun.faces.util.Util; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Parameter.class, Beans.class, Reflections.class, Converter.class, FacesContext.class, Util.class }) +public class AbstractEditPageBeanTest { + + private AbstractEditPageBean pageBean; + + private ResourceBundle bundle; + + @Before + public void before() { + bundle = new ResourceBundleProducer().create("demoiselle-jsf-bundle"); + + pageBean = new AbstractEditPageBean() { + + private static final long serialVersionUID = 1L; + + @Override + public String update() { + return null; + } + + @Override + public String insert() { + return null; + } + + @Override + public String delete() { + return null; + } + + @Override + protected void handleLoad() { + } + }; + } + + @Test + public void testClear() { + Parameter param = PowerMock.createMock(Parameter.class); + + assertNull(Whitebox.getInternalState(pageBean, "bean")); + assertNull(Whitebox.getInternalState(pageBean, "id")); + + setInternalState(pageBean, "bean", new Contact()); + setInternalState(pageBean, "id", param); + + pageBean.clear(); + + assertNull(Whitebox.getInternalState(pageBean, "bean")); + assertNull(Whitebox.getInternalState(pageBean, "id")); + } + + @Test + public void testCreateBean() { + mockStatic(Beans.class); + Contact c = new Contact(); + expect(Beans.getReference(Contact.class)).andReturn(c); + + replayAll(); + assertEquals(c, pageBean.createBean()); + verifyAll(); + } + + @Test + public void testGetBean() { + + pageBean = new AbstractEditPageBean() { + + private static final long serialVersionUID = 1L; + + private boolean updateMode = false; + + @Override + public String update() { + return null; + } + + @Override + public String insert() { + return null; + } + + @Override + public String delete() { + return null; + } + + @Override + protected void handleLoad() { + this.setBean(new Contact(200L)); + } + + public boolean isUpdateMode() { + return updateMode; + } + + }; + + Contact c = new Contact(); + assertNull(Whitebox.getInternalState(pageBean, "bean")); + setInternalState(pageBean, "bean", c); + assertEquals(c, pageBean.getBean()); + + mockStatic(Beans.class); + expect(Beans.getReference(Contact.class)).andReturn(c); + + pageBean.clear(); + + replayAll(); + assertEquals(c, pageBean.getBean()); + verifyAll(); + + pageBean.clear(); + + setInternalState(pageBean, "updateMode", true); + assertEquals(Long.valueOf(200), pageBean.getBean().getId()); + } + + @Test + public void testGetBeanClass() { + mockStatic(Reflections.class); + expect(Reflections.getGenericTypeArgument(pageBean.getClass(), 0)).andReturn(Object.class); + + assertNull(Whitebox.getInternalState(pageBean, "beanClass")); + + replayAll(); + assertEquals(Object.class, pageBean.getBeanClass()); + verifyAll(); + + setInternalState(pageBean, "beanClass", Contact.class, AbstractEditPageBean.class); + assertEquals(Contact.class, pageBean.getBeanClass()); + } + + @Test + public void testGetIdClass() { + mockStatic(Reflections.class); + expect(Reflections.getGenericTypeArgument(pageBean.getClass(), 1)).andReturn(Object.class); + + assertNull(Whitebox.getInternalState(pageBean, "idClass")); + + replayAll(); + assertEquals(Object.class, pageBean.getIdClass()); + verifyAll(); + + Whitebox.setInternalState(pageBean, "idClass", Long.class, AbstractEditPageBean.class); + assertEquals(Long.class, pageBean.getIdClass()); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetStringId() { + mockStatic(Util.class); + + FacesContext facesContext = createMock(FacesContext.class); + Parameter parameter = createMock(Parameter.class); + + setInternalState(pageBean, "facesContext", facesContext); + setInternalState(pageBean, "id", parameter); + setInternalState(pageBean, "idClass", String.class, AbstractEditPageBean.class); + + String value = "1"; + expect(parameter.getValue()).andReturn(value); + expect(Util.getConverterForClass(String.class, facesContext)).andReturn(null); + + replayAll(); + assertEquals(value, pageBean.getId()); + verifyAll(); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetLongId() { + mockStatic(Util.class); + + FacesContext facesContext = createMock(FacesContext.class); + UIViewRoot viewRoot = createMock(UIViewRoot.class); + Converter converter = createMock(Converter.class); + Parameter parameter = createMock(Parameter.class); + + setInternalState(pageBean, "facesContext", facesContext); + setInternalState(pageBean, "id", parameter); + setInternalState(pageBean, "idClass", Long.class, AbstractEditPageBean.class); + + String value = "1"; + expect(parameter.getValue()).andReturn(value); + expect(facesContext.getViewRoot()).andReturn(viewRoot); + expect(Util.getConverterForClass(Long.class, facesContext)).andReturn(converter); + expect(converter.getAsObject(facesContext, viewRoot, value)).andReturn(Long.valueOf(value)); + + replayAll(); + assertEquals(Long.valueOf(value), pageBean.getId()); + verifyAll(); + } + + @Test + public void testGetNotStringIdWithNullConverter() { + FacesContext facesContext = createMock(FacesContext.class); + + setInternalState(pageBean, "facesContext", facesContext); + setInternalState(pageBean, "idClass", Contact.class, AbstractEditPageBean.class); + setInternalState(pageBean, "bundle", bundle); + expect(Util.getConverterForClass(Contact.class, facesContext)).andReturn(null); + + replayAll(); + try { + pageBean.getId(); + } catch (DemoiselleException cause) { + assertEquals(bundle.getString("id-converter-not-found", Contact.class.getCanonicalName()), cause.getMessage()); + } + + verifyAll(); + } + + @SuppressWarnings("serial") + @Test + public void testUpdateMode() { + + pageBean = new AbstractEditPageBean() { + + private Long id = null; + + @Override + public String update() { + return null; + } + + @Override + public String insert() { + return null; + } + + @Override + public String delete() { + return null; + } + + @Override + protected void handleLoad() { + this.setBean(new Contact(200L)); + } + + public Long getId() { + return id; + } + + }; + + assertFalse(pageBean.isUpdateMode()); + setInternalState(pageBean, "id", 1L); + assertTrue(pageBean.isUpdateMode()); + } +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractListPageBeanTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractListPageBeanTest.java new file mode 100644 index 0000000..9cc5f1f --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractListPageBeanTest.java @@ -0,0 +1,183 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.model.ListDataModel; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.internal.implementation.PaginationImpl; +import br.gov.frameworkdemoiselle.pagination.Pagination; +import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.Reflections; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Reflections.class, PaginationContext.class, Pagination.class }) +public class AbstractListPageBeanTest { + + private MySimplePageBean pageBean; + + @Before + public void before() { + pageBean = new MySimplePageBean(); + } + + @SuppressWarnings("rawtypes") + @Test + public void testClear() { + assertNull(Whitebox.getInternalState(pageBean, "dataModel")); + assertNull(Whitebox.getInternalState(pageBean, "resultList")); + + Whitebox.setInternalState(pageBean, "resultList", new ArrayList()); + Whitebox.setInternalState(pageBean, "dataModel", new ListDataModel()); + + pageBean.clear(); + + assertNull(Whitebox.getInternalState(pageBean, "dataModel")); + assertNull(Whitebox.getInternalState(pageBean, "resultList")); + } + + @Test + public void testGetBeanClass() { + assertNull(Whitebox.getInternalState(pageBean, "beanClass")); + + PowerMock.mockStatic(Reflections.class); + expect(Reflections.getGenericTypeArgument(pageBean.getClass(), 0)).andReturn(Object.class); + + PowerMock.replayAll(); + assertEquals(Object.class, pageBean.getBeanClass()); + PowerMock.verifyAll(); + + Whitebox.setInternalState(pageBean, "beanClass", Contact.class, AbstractListPageBean.class); + + assertEquals(Contact.class, pageBean.getBeanClass()); + } + + @Test + public void testGetDataModel() { + assertNull(Whitebox.getInternalState(pageBean, "dataModel")); + assertEquals(ListDataModel.class, pageBean.getDataModel().getClass()); + + ListDataModel ldm = new ListDataModel(); + Whitebox.setInternalState(pageBean, "dataModel", ldm); + + assertEquals(ldm, pageBean.getDataModel()); + } + + @Test + public void testGetResultList() { + assertNull(Whitebox.getInternalState(pageBean, "resultList")); + + List list = pageBean.getResultList(); + assertTrue(list.size() == 2); + + list = new ArrayList(); + Whitebox.setInternalState(pageBean, "resultList", list); + assertTrue(list.size() == 0); + assertEquals(list, pageBean.getResultList()); + } + + @Test + public void testList() { + this.testClear(); + assertEquals(pageBean.getCurrentView(), pageBean.list()); + } + + @Test + public void testSelection() { + Map map = new HashMap(); + map.put(1L, true); + Whitebox.setInternalState(pageBean, "selection", map); + assertEquals(map, pageBean.getSelection()); + assertEquals(true, pageBean.getSelection().get(1L)); + + pageBean.setSelection(null); + assertNull(Whitebox.getInternalState(pageBean, "selection")); + pageBean.setSelection(map); + assertEquals(map, pageBean.getSelection()); + assertEquals(true, pageBean.getSelection().get(1L)); + } + + @Test + public void testPagination() { + Pagination pagination = new PaginationImpl(); + PaginationContext pc = PowerMock.createMock(PaginationContext.class); + expect(pc.getPagination(Contact.class, true)).andReturn(pagination); + + replayAll(); + Whitebox.setInternalState(pageBean, "paginationContext", pc); + assertEquals(pageBean.getPagination(), pagination); + verifyAll(); + } + +} + +@SuppressWarnings("serial") +class MySimplePageBean extends AbstractListPageBean { + + @Override + protected List handleResultList() { + List list = new ArrayList(); + list.add(new Contact()); + list.add(new Contact()); + return list; + } + + @Override + public String getCurrentView() { + return "currentView"; + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractPageTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractPageTest.java new file mode 100644 index 0000000..51183a8 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/AbstractPageTest.java @@ -0,0 +1,160 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import br.gov.frameworkdemoiselle.annotation.NextView; +import br.gov.frameworkdemoiselle.annotation.PreviousView; +import br.gov.frameworkdemoiselle.message.MessageContext; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MessageContext.class }) +public class AbstractPageTest { + + private AbstractPageBean abstractPage; + + private FacesContext facesContext; + + private UIViewRoot viewRoot; + + @Before + public void before() { + facesContext = PowerMock.createMock(FacesContext.class); + viewRoot = PowerMock.createMock(UIViewRoot.class); + expect(facesContext.getViewRoot()).andReturn(viewRoot).anyTimes(); + expect(viewRoot.getViewId()).andReturn("viewId").anyTimes(); + } + + @Test + public void testGetCurrentView() { + abstractPage = new MyAbstractPage(); + Whitebox.setInternalState(abstractPage, "facesContext", facesContext); + + replayAll(); + assertEquals(abstractPage.getCurrentView(), "viewId"); + verifyAll(); + } + + @Test + public void testGetNextViewOK() { + abstractPage = new MyAbstractPage(); + + replayAll(); + assertEquals(abstractPage.getNextView(), "next_view"); + verifyAll(); + } + + @Test + public void testGetNextViewWhenNoAnnotation() { + abstractPage = new MyAbstractPageNoAnnotations(); + + replayAll(); + assertEquals(abstractPage.getNextView(), null); + verifyAll(); + } + + @Test + public void testGetNextViewAlreadySet() { + abstractPage = new MyAbstractPageNoAnnotations(); + Whitebox.setInternalState(abstractPage, "nextView", "next"); + + replayAll(); + assertEquals(abstractPage.getNextView(), "next"); + verifyAll(); + } + + @Test + public void testGetPreviousViewOK() { + abstractPage = new MyAbstractPage(); + + replayAll(); + assertEquals(abstractPage.getPreviousView(), "prevs"); + verifyAll(); + } + + @Test + public void testGetPreviousViewAlreadySet() { + abstractPage = new MyAbstractPageNoAnnotations(); + Whitebox.setInternalState(abstractPage, "previousView", "previous"); + + replayAll(); + assertEquals(abstractPage.getPreviousView(), "previous"); + verifyAll(); + } + + @Test + public void testGetPreviousViewWhenNoAnnotation() { + abstractPage = new MyAbstractPageNoAnnotations(); + + replayAll(); + assertEquals(abstractPage.getPreviousView(), null); + verifyAll(); + } + + @Test + public void testOtherTests() { + abstractPage = new MyAbstractPageNoAnnotations(); + assertEquals(null, abstractPage.getTitle()); + } +} + +@SuppressWarnings("serial") +@NextView("next_view") +@PreviousView("prevs") +class MyAbstractPage extends AbstractPageBean { + +} + +@SuppressWarnings("serial") +class MyAbstractPageNoAnnotations extends AbstractPageBean { + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/Contact.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/Contact.java new file mode 100644 index 0000000..381b639 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/template/Contact.java @@ -0,0 +1,58 @@ +/* + * 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 br.gov.frameworkdemoiselle.template; + + +public class Contact { + private Long id; + + public Contact() { + } + + public Contact(Long id) { + this.id = id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + +} diff --git a/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/util/FacesTest.java b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/util/FacesTest.java new file mode 100644 index 0000000..adf67a3 --- /dev/null +++ b/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/util/FacesTest.java @@ -0,0 +1,216 @@ +/* + * 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 br.gov.frameworkdemoiselle.util; + +import static junit.framework.Assert.assertEquals; +import static org.easymock.EasyMock.expect; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.faces.application.FacesMessage; +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; +import javax.faces.convert.Converter; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.exception.ApplicationException; +import br.gov.frameworkdemoiselle.message.DefaultMessage; +import br.gov.frameworkdemoiselle.message.Message; +import br.gov.frameworkdemoiselle.message.SeverityType; + +import com.sun.faces.util.Util; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class, Strings.class, Converter.class, Util.class, ResourceBundle.class }) +public class FacesTest { + + private FacesContext facesContext; + + private Faces faces; + + @Before + public void before() { + faces = new Faces(); + + PowerMock.mockStatic(Beans.class); + facesContext = PowerMock.createMock(FacesContext.class); + } + + @SuppressWarnings("static-access") + @Test + public void testAddMessage() { + expect(Beans.getReference(ResourceBundle.class)).andReturn(null).anyTimes(); + expect(Beans.getReference(FacesContext.class)).andReturn(facesContext).anyTimes(); + + facesContext.addMessage(EasyMock.anyObject(String.class), EasyMock.anyObject(FacesMessage.class)); + EasyMock.expectLastCall().times(5); + + replayAll(); + + DefaultMessage message = new DefaultMessage("text") { + + @Override + public String toString() { + return "Message"; + } + + }; + + List messages = new ArrayList(); + messages.add(message); + + faces.addMessages(null); + faces.addMessages(messages); + faces.addMessage(message); + faces.addMessage("clientId", message); + faces.addMessage("clientId", new MyException()); + faces.addMessage(new MyException()); + verifyAll(); + } + + @SuppressWarnings("static-access") + @Test + public void testParseSeverity() { + assertEquals(faces.parse(SeverityType.ERROR), FacesMessage.SEVERITY_ERROR); + assertEquals(faces.parse(SeverityType.FATAL), FacesMessage.SEVERITY_FATAL); + assertEquals(faces.parse(SeverityType.INFO), FacesMessage.SEVERITY_INFO); + assertEquals(faces.parse(SeverityType.WARN), FacesMessage.SEVERITY_WARN); + } + + @SuppressWarnings("static-access") + @Test + public void testParseThrowable() { + FacesMessage facesMessage = faces.parse(new MyException()); + assertEquals(facesMessage.getSeverity(), FacesMessage.SEVERITY_INFO); + assertEquals(facesMessage.getSummary(), "MESSAGE"); + + facesMessage = faces.parse(new Exception()); + assertEquals(facesMessage.getSeverity(), FacesMessage.SEVERITY_ERROR); + assertEquals(facesMessage.getSummary(), "java.lang.Exception"); + } + + @SuppressWarnings("static-access") + @Test + public void testConvertNull() { + PowerMock.mockStatic(Strings.class); + + Converter converter = PowerMock.createMock(Converter.class); + expect(Strings.isEmpty(EasyMock.anyObject(String.class))).andReturn(true); + + replayAll(); + String object = (String) faces.convert("value", converter); + assertEquals(null, object); + verifyAll(); + } + + @SuppressWarnings("static-access") + @Test + public void testConvert() { + PowerMock.mockStatic(Strings.class); + + expect(Beans.getReference(FacesContext.class)).andReturn(facesContext).times(2); + + Converter converter = PowerMock.createMock(Converter.class); + expect(Strings.isEmpty(EasyMock.anyObject(String.class))).andReturn(false).times(2); + expect( + converter.getAsObject(EasyMock.anyObject(FacesContext.class), EasyMock.anyObject(UIViewRoot.class), + EasyMock.anyObject(String.class))).andReturn("THAT"); + expect(facesContext.getViewRoot()).andReturn(null); + + replayAll(); + String object = (String) faces.convert("value", converter); + assertEquals("THAT", object); + + object = (String) faces.convert("value", null); + assertEquals("value", object); + + verifyAll(); + } + + @SuppressWarnings("static-access") + @Test + public void testGetConverter() { + Converter converter = PowerMock.createMock(Converter.class); + PowerMock.mockStatic(Util.class); + + expect(Beans.getReference(FacesContext.class)).andReturn(facesContext); + expect(Util.getConverterForClass(getClass(), facesContext)).andReturn(converter); + + replayAll(); + assertEquals(converter, faces.getConverter(getClass())); + verifyAll(); + } + + @SuppressWarnings("static-access") + @Test + public void testGetViewMap() { + UIViewRoot uiViewRoot = PowerMock.createMock(UIViewRoot.class); + expect(Beans.getReference(FacesContext.class)).andReturn(facesContext); + expect(facesContext.getViewRoot()).andReturn(uiViewRoot); + + Map map = new HashMap(); + expect(uiViewRoot.getViewMap(true)).andReturn(map); + + replayAll(); + assertEquals(map, faces.getViewMap()); + verifyAll(); + } + + @SuppressWarnings("serial") + @ApplicationException(severity = SeverityType.INFO) + class MyException extends Exception { + + @Override + public String getMessage() { + return "MESSAGE"; + } + + } + +} diff --git a/extension/jsf/src/uml/exception.ucls b/extension/jsf/src/uml/exception.ucls new file mode 100644 index 0000000..b21db2f --- /dev/null +++ b/extension/jsf/src/uml/exception.ucls @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/injection-bootstrap.ucls b/extension/jsf/src/uml/injection-bootstrap.ucls new file mode 100644 index 0000000..a834a74 --- /dev/null +++ b/extension/jsf/src/uml/injection-bootstrap.ucls @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/injection-producer.ucls b/extension/jsf/src/uml/injection-producer.ucls new file mode 100644 index 0000000..6a79959 --- /dev/null +++ b/extension/jsf/src/uml/injection-producer.ucls @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/message.ucls b/extension/jsf/src/uml/message.ucls new file mode 100644 index 0000000..ea011ce --- /dev/null +++ b/extension/jsf/src/uml/message.ucls @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/security-exception-handler.ucls b/extension/jsf/src/uml/security-exception-handler.ucls new file mode 100644 index 0000000..2cdafb8 --- /dev/null +++ b/extension/jsf/src/uml/security-exception-handler.ucls @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/security-observer.ucls b/extension/jsf/src/uml/security-observer.ucls new file mode 100644 index 0000000..3e5f9bd --- /dev/null +++ b/extension/jsf/src/uml/security-observer.ucls @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/template.ucls b/extension/jsf/src/uml/template.ucls new file mode 100644 index 0000000..253b809 --- /dev/null +++ b/extension/jsf/src/uml/template.ucls @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jsf/src/uml/util.ucls b/extension/jsf/src/uml/util.ucls new file mode 100644 index 0000000..a4273e4 --- /dev/null +++ b/extension/jsf/src/uml/util.ucls @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/jta/.gitignore b/extension/jta/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/extension/jta/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/extension/jta/pom.xml b/extension/jta/pom.xml new file mode 100644 index 0000000..e78d960 --- /dev/null +++ b/extension/jta/pom.xml @@ -0,0 +1,68 @@ + + + + 4.0.0 + + demoiselle-jta + jar + + + br.gov.frameworkdemoiselle + demoiselle-extension-parent + 2.2.1-SNAPSHOT + ../../parent/extension/pom.xml + + + JTA Extension + + + + + javax.transaction + jta + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + \ No newline at end of file diff --git a/extension/jta/src/main/java/br/gov/frameworkdemoiselle/transaction/JTATransaction.java b/extension/jta/src/main/java/br/gov/frameworkdemoiselle/transaction/JTATransaction.java new file mode 100644 index 0000000..05e13df --- /dev/null +++ b/extension/jta/src/main/java/br/gov/frameworkdemoiselle/transaction/JTATransaction.java @@ -0,0 +1,123 @@ +/* + * 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 br.gov.frameworkdemoiselle.transaction; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Alternative; +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +import br.gov.frameworkdemoiselle.util.Beans; + +@Alternative +@RequestScoped +public class JTATransaction implements Transaction { + + private static final long serialVersionUID = 1L; + + private UserTransaction delegate; + + public UserTransaction getDelegate() { + + if (delegate == null) { + delegate = Beans.getReference(UserTransaction.class); + } + + return delegate; + } + + @Override + public boolean isActive() { + try { + return getDelegate().getStatus() == Status.STATUS_ACTIVE || isMarkedRollback(); + + } catch (SystemException cause) { + throw new TransactionException(cause); + } + } + + @Override + public boolean isMarkedRollback() { + try { + return getDelegate().getStatus() == Status.STATUS_MARKED_ROLLBACK; + + } catch (SystemException cause) { + throw new TransactionException(cause); + } + } + + @Override + public void begin() { + try { + getDelegate().begin(); + + } catch (Exception cause) { + throw new TransactionException(cause); + } + } + + @Override + public void commit() { + try { + getDelegate().commit(); + + } catch (Exception cause) { + throw new TransactionException(cause); + } + } + + @Override + public void rollback() { + try { + getDelegate().rollback(); + + } catch (SystemException cause) { + throw new TransactionException(cause); + } + } + + @Override + public void setRollbackOnly() { + try { + getDelegate().setRollbackOnly(); + + } catch (SystemException cause) { + throw new TransactionException(cause); + } + } +} diff --git a/extension/jta/src/main/resources/META-INF/beans.xml b/extension/jta/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..527e828 --- /dev/null +++ b/extension/jta/src/main/resources/META-INF/beans.xml @@ -0,0 +1,40 @@ + + + + \ No newline at end of file diff --git a/extension/jta/src/main/resources/demoiselle-jta-bundle.properties b/extension/jta/src/main/resources/demoiselle-jta-bundle.properties new file mode 100644 index 0000000..3f1fa2e --- /dev/null +++ b/extension/jta/src/main/resources/demoiselle-jta-bundle.properties @@ -0,0 +1,34 @@ +# 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. diff --git a/extension/jta/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java b/extension/jta/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java new file mode 100644 index 0000000..87835a2 --- /dev/null +++ b/extension/jta/src/test/java/br/gov/frameworkdemoiselle/transaction/JTATransactionTest.java @@ -0,0 +1,194 @@ +package br.gov.frameworkdemoiselle.transaction; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verify; +import static org.powermock.reflect.Whitebox.setInternalState; + +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import br.gov.frameworkdemoiselle.util.Beans; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Beans.class }) +public class JTATransactionTest { + + private UserTransaction userTransaction; + + private JTATransaction jtaTransaction; + + @Before + public void setUp() { + + userTransaction = createMock(UserTransaction.class); + jtaTransaction = new JTATransaction(); + + setInternalState(jtaTransaction, UserTransaction.class, userTransaction); + } + + @Test + public void testGetDElegateWithUserTransactionNull() throws SystemException { + mockStatic(Beans.class); + userTransaction = null; + setInternalState(jtaTransaction, UserTransaction.class, userTransaction); + userTransaction = createMock(UserTransaction.class); + expect(Beans.getReference(UserTransaction.class)).andReturn(userTransaction); + replayAll(); + + Assert.assertEquals(userTransaction, jtaTransaction.getDelegate()); + } + + @Test + public void testGetDElegateWithUserTransactionIsNotNull() throws SystemException { + Assert.assertEquals(userTransaction, jtaTransaction.getDelegate()); + } + + @Test + public void testIsActiveWithStatusEqualsActive() throws SystemException { + expect(userTransaction.getStatus()).andReturn(Integer.valueOf(0)); + replay(userTransaction); + Assert.assertTrue(this.jtaTransaction.isActive()); + } + + @Test + public void testIsActiveWithStatusEqualsMarkedRollback() throws SystemException { + expect(userTransaction.getStatus()).andReturn(Integer.valueOf(1)).times(2); + replay(userTransaction); + Assert.assertTrue(this.jtaTransaction.isActive()); + } + + @Test + public void testIsMarkedRollback() throws SystemException { + expect(userTransaction.getStatus()).andReturn(Integer.valueOf(1)); + replay(userTransaction); + Assert.assertTrue(this.jtaTransaction.isMarkedRollback()); + } + + @Test + public void testBegin() throws SystemException, NotSupportedException { + userTransaction.begin(); + replay(userTransaction); + this.jtaTransaction.begin(); + verify(); + } + + @Test + public void testCommit() throws SystemException, NotSupportedException, SecurityException, IllegalStateException, + RollbackException, HeuristicMixedException, HeuristicRollbackException { + userTransaction.commit(); + replay(userTransaction); + this.jtaTransaction.commit(); + verify(); + } + + @Test + public void testRollback() throws SystemException, NotSupportedException { + userTransaction.rollback(); + replay(userTransaction); + this.jtaTransaction.rollback(); + verify(); + } + + @Test + public void testSetRollbackOnly() throws SystemException, NotSupportedException { + userTransaction.setRollbackOnly(); + replay(userTransaction); + this.jtaTransaction.setRollbackOnly(); + verify(); + } + + @Test + public void testIsActiveThrowsSystemException() throws SystemException { + expect(userTransaction.getStatus()).andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.isActive(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testIsMarkedRollbackThrowsSystemException() throws SystemException { + expect(userTransaction.getStatus()).andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.isMarkedRollback(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testBeginThrowsException() throws SystemException, NotSupportedException { + userTransaction.begin(); + expectLastCall().andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.begin(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testCommitThrowsException() throws SystemException, SecurityException, IllegalStateException, + RollbackException, HeuristicMixedException, HeuristicRollbackException { + userTransaction.commit(); + expectLastCall().andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.commit(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testRollbackThrowsSystemException() throws SystemException { + userTransaction.rollback(); + expectLastCall().andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.rollback(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + + @Test + public void testSetRollbackOnlyThrowsSystemException() throws SystemException { + userTransaction.setRollbackOnly(); + expectLastCall().andThrow(new SystemException()); + replay(userTransaction); + try { + this.jtaTransaction.setRollbackOnly(); + Assert.fail(); + } catch (TransactionException cause) { + Assert.assertTrue(true); + } + } + +} diff --git a/extension/jta/src/uml/transaction.ucls b/extension/jta/src/uml/transaction.ucls new file mode 100644 index 0000000..b5263f5 --- /dev/null +++ b/extension/jta/src/uml/transaction.ucls @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/extension/pom.xml b/extension/pom.xml new file mode 100644 index 0000000..5c7cdf9 --- /dev/null +++ b/extension/pom.xml @@ -0,0 +1,87 @@ + + + + 4.0.0 + + demoiselle-extension-build-aggregator + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../parent/root/pom.xml + + + Extensions Build Aggregator + Demoiselle Extensions Build Aggregator (JPA, JSF, Swing) + + + jta + jsf + se + jpa + + + + + + org.codehaus.mojo + wagon-maven-plugin + + true + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/extension/se/.gitignore b/extension/se/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/extension/se/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/extension/se/pom.xml b/extension/se/pom.xml new file mode 100644 index 0000000..33d318e --- /dev/null +++ b/extension/se/pom.xml @@ -0,0 +1,73 @@ + + + + 4.0.0 + + demoiselle-se + jar + + + br.gov.frameworkdemoiselle + demoiselle-extension-parent + 2.2.1-SNAPSHOT + ../../parent/extension/pom.xml + + + SE Extension + Extensão para aplicações SE + + + + org.jboss.weld.se + weld-se-core + + + org.hibernate + hibernate-validator + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + + diff --git a/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java b/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java new file mode 100644 index 0000000..82ed588 --- /dev/null +++ b/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java @@ -0,0 +1,54 @@ +/* + * 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 br.gov.frameworkdemoiselle.internal.bootstrap; + +import javax.enterprise.context.RequestScoped; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; + +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; + +public class SeBootstrap extends AbstractBootstrap { + + public void loadContext(@Observes final AfterBeanDiscovery event) { + addContext(new ThreadLocalContext(RequestScoped.class), event); + addContext(new ThreadLocalContext(SessionScoped.class), event); + addContext(new ThreadLocalContext(ViewScoped.class), event); + } +} \ No newline at end of file diff --git a/extension/se/src/main/resources/META-INF/beans.xml b/extension/se/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..aa084ce --- /dev/null +++ b/extension/se/src/main/resources/META-INF/beans.xml @@ -0,0 +1,41 @@ + + + + + \ No newline at end of file diff --git a/extension/se/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/extension/se/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000..fbc97e8 --- /dev/null +++ b/extension/se/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1 @@ +br.gov.frameworkdemoiselle.internal.bootstrap.SeBootstrap diff --git a/extension/se/src/main/resources/demoiselle-swing-bundle.properties b/extension/se/src/main/resources/demoiselle-swing-bundle.properties new file mode 100644 index 0000000..2d3d565 --- /dev/null +++ b/extension/se/src/main/resources/demoiselle-swing-bundle.properties @@ -0,0 +1,35 @@ +# 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. + diff --git a/extension/se/src/uml/injection-bootstrap.ucls b/extension/se/src/uml/injection-bootstrap.ucls new file mode 100644 index 0000000..1c2db79 --- /dev/null +++ b/extension/se/src/uml/injection-bootstrap.ucls @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/parent/.gitignore b/parent/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/archetype/.gitignore b/parent/archetype/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/archetype/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/archetype/pom.xml b/parent/archetype/pom.xml new file mode 100644 index 0000000..ca1812d --- /dev/null +++ b/parent/archetype/pom.xml @@ -0,0 +1,82 @@ + + + + 4.0.0 + + demoiselle-archetype-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../root/pom.xml + + + Archetype Parent + + Contém configurações comuns a todos os projetos geradores de arquétipos. + + + + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-resources-plugin + + + #{*} + + false + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/parent/extension/.gitignore b/parent/extension/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/extension/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/extension/pom.xml b/parent/extension/pom.xml new file mode 100644 index 0000000..c39e4d7 --- /dev/null +++ b/parent/extension/pom.xml @@ -0,0 +1,119 @@ + + + + 4.0.0 + + demoiselle-extension-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../root/pom.xml + + + Extension Parent + + Configurações gerais para as extensões do framework. + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.codehaus.mojo + cobertura-maven-plugin + + + + + + + br.gov.frameworkdemoiselle + demoiselle-core + compile + + + + + junit + junit + test + + + org.easymock + easymock + test + + + org.powermock + powermock-module-junit4 + test + + + org.powermock + powermock-api-easymock + test + + + org.slf4j + slf4j-log4j12 + test + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + \ No newline at end of file diff --git a/parent/jsf/.gitignore b/parent/jsf/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/jsf/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/jsf/pom.xml b/parent/jsf/pom.xml new file mode 100644 index 0000000..1009350 --- /dev/null +++ b/parent/jsf/pom.xml @@ -0,0 +1,215 @@ + + + + 4.0.0 + + demoiselle-jsf-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-minimal-parent + 2.2.1-SNAPSHOT + ../minimal/pom.xml + + + JSF Parent + + Especialização do POM demoiselle-web-parent, contendo configurações úteis para todas as aplicações JSF que + utilizam o framework. + + + + + br.gov.frameworkdemoiselle + demoiselle-jsf + compile + + + javax.servlet + servlet-api + provided + + + javax.el + el-api + provided + + + + + + + tomcat6 + + + org.jboss.weld + weld-core + runtime + + + org.jboss.weld.servlet + weld-servlet-core + runtime + + + org.eclipse.persistence + eclipselink + runtime + + + org.hibernate + hibernate-validator + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + hsqldb + hsqldb + compile + + + + + tomcat7 + + + org.jboss.weld + weld-core + runtime + + + org.jboss.weld.servlet + weld-servlet-core + runtime + + + org.eclipse.persistence + eclipselink + runtime + + + org.hibernate + hibernate-validator + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + hsqldb + hsqldb + compile + + + + + jboss6 + + true + + + + javax.enterprise + cdi-api + provided + + + javax.servlet + jstl + provided + + + validation-api + javax.validation + provided + + + javax.transaction + jta + provided + + + org.slf4j + slf4j-log4j12 + runtime + + + org.eclipse.persistence + javax.persistence + provided + + + com.sun.faces + jsf-api + provided + + + com.sun.faces + jsf-impl + provided + + + hsqldb + hsqldb + provided + + + + org.hibernate + hibernate-entitymanager + test + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/parent/minimal/.gitignore b/parent/minimal/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/minimal/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/minimal/pom.xml b/parent/minimal/pom.xml new file mode 100644 index 0000000..ef1a48a --- /dev/null +++ b/parent/minimal/pom.xml @@ -0,0 +1,94 @@ + + + + 4.0.0 + + demoiselle-minimal-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + ../root/pom.xml + + + App Parent + + Configurações úteis para todas as aplicações que utilizam o framework. O ideal é que toda aplicação que + utiliza o Demoiselle herde deste POM ou de uma de suas especializações. + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + + + + + br.gov.frameworkdemoiselle + demoiselle-core + compile + + + br.gov.frameworkdemoiselle.component + demoiselle-junit + test + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/parent/pom.xml b/parent/pom.xml new file mode 100644 index 0000000..adcacd2 --- /dev/null +++ b/parent/pom.xml @@ -0,0 +1,91 @@ + + + + 4.0.0 + + demoiselle-parent-build-aggregator + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + + + Parent Build Aggregator + + + + + root + archetype + minimal + extension + web + jsf + se + + + + + + org.codehaus.mojo + wagon-maven-plugin + + true + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + + diff --git a/parent/root/.gitignore b/parent/root/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/root/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/root/pom.xml b/parent/root/pom.xml new file mode 100644 index 0000000..09b3fdb --- /dev/null +++ b/parent/root/pom.xml @@ -0,0 +1,687 @@ + + + 4.0.0 + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + pom + + Demoiselle Parent + + Contém as informações de build comum a todos os projetos do Framework Demoiselle. + Se você é usuário do framework, certamente este POM não servirá para você. + + http://www.frameworkdemoiselle.gov.br/ + + + SERPRO - Serviço Federal de Processamento de Dados + http://www.frameworkdemoiselle.gov.br/ + + + + + Demoiselle Users + https://sourceforge.net/mailarchive/forum.php?forum_name=demoiselle-users + demoiselle-users@lists.sourceforge.net + https://lists.sourceforge.net/lists/listinfo/demoiselle-users + https://lists.sourceforge.net/lists/listinfo/demoiselle-users + + + + + + + + javax.enterprise + cdi-api + ${cdi.version} + + + jsr250-api + javax.annotation + + + + + + + org.jboss.weld + weld-core + ${weld.version} + + + org.jboss.weld.servlet + weld-servlet-core + ${weld.version} + + + org.jboss.weld.se + weld-se-core + ${weld.version} + + + jsr250-api + javax.annotation + + + + + + + validation-api + javax.validation + ${validation.version} + + + + + org.hibernate + hibernate-validator + 4.2.0.Final + + + javax.xml.bind + jaxb-api + + + com.sun.xml.bind + jaxb-impl + + + + + + + javax.el + el-api + 2.2 + + + + + org.glassfish.web + el-impl + 2.1.2-b04 + + + javax.el + el-api + + + + + + + com.sun.faces + jsf-api + ${jsf.version} + + + + + com.sun.faces + jsf-impl + ${jsf.version} + + + org.primefaces + primefaces + ${primefaces.version} + + + + + javax + javaee-api + ${javaee.version} + + + javax + javaee-web-api + ${javaee.version} + + + + + javax.servlet + servlet-api + ${servlet.version} + + + javax.servlet + jstl + 1.2 + + + + + org.eclipse.persistence + javax.persistence + ${persistence.version} + + + + + org.eclipse.persistence + eclipselink + 2.1.0 + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + + + javax.jdo + jdo2-api + 2.3-eb + + + + + javax.transaction + jta + ${transaction.version} + + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + + + + + commons-configuration + commons-configuration + ${commons.configuration.version} + + + + + hsqldb + hsqldb + ${hsqldb.version} + + + + + org.vaadin.addons.lazyquerycontainer + vaadin-lazyquerycontainer + 1.2.8 + + + org.vaadin.addons + refresher + 1.1.0 + + + com.vaadin + vaadin + ${vaadin.version} + + + org.vaadin.addons + confirmdialog + 1.1.0 + + + org.vaadin.addons + collectioncontainer + 0.9.3 + + + com.vaadin.addon + beanvalidation-addon + 0.6.1 + + + org.vaadin.addons + easyuploads + 0.4.3 + + + + + com.google.gwt + gwt-user + ${gwt.version} + + + + + org.apache.shiro + shiro-core + ${shiro.version} + + + + + junit + junit + ${junit.version} + + + org.powermock + powermock-module-junit4 + ${powermock.version} + + + org.powermock + powermock-api-easymock + ${powermock.version} + + + org.easymock + easymock + ${easymock.version} + + + org.jboss.arquillian + arquillian-junit + ${arquillian.junit.version} + + + org.jboss.arquillian.container + arquillian-weld-embedded + ${arquillian.weld.embdedded.version} + + + + + br.gov.frameworkdemoiselle + demoiselle-core + 2.2.1-SNAPSHOT + + + br.gov.frameworkdemoiselle + demoiselle-jta + 2.2.1-SNAPSHOT + + + br.gov.frameworkdemoiselle + demoiselle-jpa + 2.2.1-SNAPSHOT + + + br.gov.frameworkdemoiselle + demoiselle-jsf + 2.2.1-SNAPSHOT + + + br.gov.frameworkdemoiselle + demoiselle-se + 2.2.1-SNAPSHOT + + + + + br.gov.frameworkdemoiselle.component + demoiselle-junit + ${demoiselle.junit} + + + br.gov.frameworkdemoiselle.component + demoiselle-shiro + ${demoiselle.shiro} + + + br.gov.frameworkdemoiselle.component + demoiselle-vaadin + ${demoiselle.vaadin} + + + br.gov.frameworkdemoiselle.component + demoiselle-validation + ${demoiselle.valitation} + + + br.gov.frameworkdemoiselle.component + demoiselle-report + ${demoiselle.report.version} + + + xml-apis + xml-apis + + + + + br.gov.frameworkdemoiselle.component + demoiselle-authorization + ${demoiselle.authorization.version} + + + + + + Continuum + + + mail + true + true + true + true + +
    demoiselle-devel@lists.sourceforge.net
    +
    +
    +
    +
    + + + Mantis + http://sourceforge.net/apps/mantisbt/demoiselle/main_page.php + + + + + demoiselle.sourceforge.net + file://${project.build.directory}/tmp + + + demoiselle.sourceforge.net + ${repository.url} + false + + + demoiselle.sourceforge.net + ${snapshot.url} + false + + + + + + + src/main/resources + true + + + + + org.codehaus.mojo + wagon-maven-plugin + + . + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven.war.plugin.version} + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven.deploy.plugin.version} + + + org.apache.maven.plugins + maven-source-plugin + ${maven.source.plugin.version} + + + package + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-resources-plugin + ${maven.resources.plugin.version} + + + org.apache.maven.plugins + maven-site-plugin + ${maven.site.plugin.version} + + ${project.build.sourceEncoding} + ${project.build.sourceEncoding} + pt_BR + + + + org.apache.maven.plugins + maven-assembly-plugin + ${maven.assembly.plugin.version} + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven.javadoc.plugin.version} + + + jar + package + + jar + + + + + + + + + + + + + + + + + org.codehaus.mojo + cobertura-maven-plugin + ${maven.cobertura.plugin.version} + + + + + + + + + + + + + + + + + org.apache.maven.wagon + wagon-ssh + 1.0-beta-7 + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.3.1 + + false + false + + + + + summary + + + + + + + + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + snapshot.demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/snapshot + + + repository.jboss.org + JBoss Maven Repository + https://repository.jboss.org/nexus/content/groups/public-jboss + + false + + + + nexus.jboss.org + JBoss Maven Repository + http://repository.jboss.org/nexus/content/groups/public + + false + + + + java.net.m2 + java.net m2 repo + http://download.java.net/maven/2 + + false + + + + prime-repo + Prime Technology Maven Repository + http://repository.primefaces.org + + false + + + + eclipselink-repo + EclipseLink Maven Repo + http://eclipse.ialto.org/rt/eclipselink/maven.repo/ + + false + + + + glassfish-repo + Glassfish Maven Repo + http://download.java.net/maven/glassfish + + false + + + + atlassian-repo + Atlassian Maven Repo + https://maven.atlassian.com/content/groups/public + + false + + + + datanucleus-repo + DataNucleus Maven Repo + http://www.datanucleus.org/downloads/maven2 + + false + + + + vaadin-addons + http://maven.vaadin.com/vaadin-addons + + + + + sftp://web.sourceforge.net/home/groups/d/de/demoiselle/htdocs + ${htdocs.url}/framework/${project.version}/parent/${project.name} + ${htdocs.url}/repository/release + ${htdocs.url}/repository/snapshot + demoiselle.svn.sourceforge.net + UTF-8 + + 2.1 + 2.1.1 + 2.5 + 2.2 + 2.2-beta-5 + 2.7 + 2.1.2 + 2.5 + 2.4 + 2.2 + + 1.6 + 6.0 + 1.0-SP4 + 1.0.0.GA + 1.1 + 2.0.3 + 2.5 + 2.0.1 + + 6.5.2 + 2.1.1 + 1.1.0 + 3.6.0.Final + + 4.8.1 + 3.0 + 1.0.0.Alpha4.SP2 + 1.0.0.Alpha2 + 1.4.6 + 2.2.1 + 1.5.10 + 1.1.2.Final + 1.5 + 1.8.0.10 + + 2.2.1 + 2.2.1 + 2.2.1 + 2.0.0 + 2.0.1 + 2.0.1 + +
    diff --git a/parent/se/.gitignore b/parent/se/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/se/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/se/pom.xml b/parent/se/pom.xml new file mode 100644 index 0000000..5380c4a --- /dev/null +++ b/parent/se/pom.xml @@ -0,0 +1,71 @@ + + + + 4.0.0 + + demoiselle-se-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-minimal-parent + 2.2.1-SNAPSHOT + ../minimal/pom.xml + + + SE Parent + + Especialização do POM mínimo, contendo configurações úteis para todas as aplicações SE que utilizam o framework. + + + + + br.gov.frameworkdemoiselle + demoiselle-se + compile + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/parent/web/.gitignore b/parent/web/.gitignore new file mode 100644 index 0000000..221c8fc --- /dev/null +++ b/parent/web/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.classpath +/.settings +/.externalToolBuilders diff --git a/parent/web/pom.xml b/parent/web/pom.xml new file mode 100644 index 0000000..b3db031 --- /dev/null +++ b/parent/web/pom.xml @@ -0,0 +1,151 @@ + + + + 4.0.0 + + demoiselle-web-parent + pom + + + br.gov.frameworkdemoiselle + demoiselle-minimal-parent + 2.2.1-SNAPSHOT + ../minimal/pom.xml + + + Web Parent + + Especialização do POM mínimo, contendo configurações úteis para todas as aplicações Web que utilizam o framework. + + + + + + + + + + + + + + + + tomcat6 + + + org.jboss.weld + weld-core + runtime + + + org.jboss.weld.servlet + weld-servlet-core + runtime + + + org.eclipse.persistence + eclipselink + runtime + + + org.hibernate + hibernate-validator + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + + + tomcat7 + + + org.jboss.weld + weld-core + runtime + + + org.jboss.weld.servlet + weld-servlet-core + runtime + + + org.eclipse.persistence + eclipselink + runtime + + + org.hibernate + hibernate-validator + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + + + jboss6 + + true + + + + javax.enterprise + cdi-api + provided + + + javax.servlet + jstl + provided + + + validation-api + javax.validation + provided + + + javax.transaction + jta + provided + + + + + + + + org.eclipse.persistence + javax.persistence + provided + + + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6d698cd --- /dev/null +++ b/pom.xml @@ -0,0 +1,142 @@ + + + + 4.0.0 + + demoiselle + pom + + + br.gov.frameworkdemoiselle + demoiselle-parent + 2.2.1-SNAPSHOT + parent/root/pom.xml + + + Demoiselle Framework + + A liberação de versões do framework deve ser feita a partir deste build, que fará automaticamente o build + de todos os artefatos com versionamento sincronizado. Jamais gere uma versão do framework sem utilizar este build. + + + + parent + core + extension + archetype + + + + scm:svn:http://demoiselle.svn.sourceforge.net/svnroot/demoiselle/framework/tags/demoiselle-2.1.2 + scm:svn:https://demoiselle.svn.sourceforge.net/svnroot/demoiselle/framework/tags/demoiselle-2.1.2 + scm:svn:http://demoiselle.svn.sourceforge.net/viewvc/demoiselle/demoiselle/framework/tags/demoiselle-2.1.2 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + demoiselle-${project.version} + ${project.build.directory}/assembly + + src/assembly/src.xml + src/assembly/bin.xml + + + + + package + + assembly + + + + + + org.codehaus.mojo + wagon-maven-plugin + + demoiselle.sourceforge.net + ${upload.url} + ${project.build.directory}/assembly + framework/${project.version} + false + + + + org.apache.maven.plugins + maven-release-plugin + + true + clean install + deploy wagon:upload site site:deploy + ${project.nextVersion} + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + demoiselle.sourceforge.net + ${htdocs.url}/framework/${project.version} + + + + + + demoiselle.sourceforge.net + Demoiselle Maven Repository + http://demoiselle.sourceforge.net/repository/release + + + + + sftp://web.sourceforge.net/home/frs/project/d/de/demoiselle + 2.2.1-SNAPSHOT + + diff --git a/src/assembly/bin.xml b/src/assembly/bin.xml new file mode 100644 index 0000000..95c3620 --- /dev/null +++ b/src/assembly/bin.xml @@ -0,0 +1,75 @@ + + + bin + + zip + + + + + *parent* + *aggregator* + *archetype* + + + ${module.artifactId} + false + + + /${module.artifactId}/lib + true + + + + + + + *parent* + *aggregator* + *archetype* + + + javadoc + ${module.artifactId} + false + false + + + + diff --git a/src/assembly/src.xml b/src/assembly/src.xml new file mode 100644 index 0000000..c556e49 --- /dev/null +++ b/src/assembly/src.xml @@ -0,0 +1,63 @@ + + + src + + zip + + + + + *parent* + *aggregator* + *archetype* + + + + + + pom.xml + src/**/* + + true + + + + + + diff --git a/src/site/apt/core.apt b/src/site/apt/core.apt new file mode 100644 index 0000000..66681f8 --- /dev/null +++ b/src/site/apt/core.apt @@ -0,0 +1,47 @@ +~~ 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. + + ------ + Core + +Core + + O core do Demoiselle contém aquelas funcionalidades que são comuns a todas as extensões e aplicações. + Ele é simples, leve e formado majoritariamente por interfaces e poucas implementações, e é a base do framework. + Sem ele, as extensões e a própria aplicação não funcionam. + + É o core que possibilita a integração entre as camadas, criação de estereótipos, utilização de + recursos transacionais, tratamento de exceção, mensagens entre outras funcionalidades importantes em uma aplicação + tradicional. diff --git a/src/site/apt/documentation.apt b/src/site/apt/documentation.apt new file mode 100644 index 0000000..67e4750 --- /dev/null +++ b/src/site/apt/documentation.apt @@ -0,0 +1,47 @@ +~~ 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. + + ------ + Documentação + +Documentação + +*-----------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------+------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------* +| {{{http://demoiselle.sourceforge.net/docs/quickstart}QuickStart}} | Tutorial do tipo "passo a passo" que ilustra de forma rápida e prática o Demoiselle Framework 2.0 | {{{http://demoiselle.sourceforge.net/docs/quickstart/2.0.3/html/}HTML}} | {{{http://demoiselle.sourceforge.net/docs/quickstart/2.0.3/html_single/}HTML simples}} | {{{http://demoiselle.sourceforge.net/docs/quickstart/2.0.3/pdf/demoiselle-quickstart.pdf}PDF}} | +*-----------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------+------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------* +| {{{http://demoiselle.sourceforge.net/docs/reference}Reference Guide}} | Guia de referência destinado a todos que desejem conhecer melhor o framework e suas funcionalidades | {{{http://demoiselle.sourceforge.net/docs/reference/2.1.1/html/}HTML}} | {{{http://demoiselle.sourceforge.net/docs/reference/2.1.1/html_single/}HTML simples}} | {{{http://demoiselle.sourceforge.net/docs/reference/2.1.1/pdf/demoiselle-reference.pdf}PDF}} | +*-----------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------+------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------* +| {{{http://demoiselle.sourceforge.net/docs/what-is-new}O que mudou?}} | Documento que exemplifica as mudanças nas funcionalidades do framework | {{{http://demoiselle.sourceforge.net/docs/what-is-new/2.0.1/html/}HTML}} | {{{http://demoiselle.sourceforge.net/docs/what-is-new/2.0.1/html_single/}HTML simples}} | {{{http://demoiselle.sourceforge.net/docs/what-is-new/2.0.1/pdf/demoiselle-what-is-new.pdf}PDF}} | +*-----------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------+------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------* diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt new file mode 100644 index 0000000..96ef26d --- /dev/null +++ b/src/site/apt/index.apt @@ -0,0 +1,43 @@ +~~ 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. + + ------ + Sobre o Demoiselle 2 + +Sobre o Demoiselle 2 + + A versão 2 do framework Demoiselle não possui um core monolítico, onde todas as funcionalidades estão concentradas em um único pacote, + pois não queremos que os desenvolvedores que utilizam o Demoiselle sejam obrigados a ter em seus projetos funcionalidades que não vão + utilizar. Por esse motivo, esta versão do framework foi dividida em Core, Extensões e componentes. diff --git a/src/site/apt/jpa.apt b/src/site/apt/jpa.apt new file mode 100644 index 0000000..919d497 --- /dev/null +++ b/src/site/apt/jpa.apt @@ -0,0 +1,42 @@ +~~ 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. + + ------ + JPA extension + +JPA extension + + Esta extensão habilita o uso de JPA para tratar a persistência. Nela são disponibilidos uma fábrica de EntityManager, + um mecanismo de transação para JPA e um template para o DAO. diff --git a/src/site/apt/jsf.apt b/src/site/apt/jsf.apt new file mode 100644 index 0000000..879b3e5 --- /dev/null +++ b/src/site/apt/jsf.apt @@ -0,0 +1,42 @@ +~~ 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. + + ------ + JSF extension + +JSF extension + + Prepara a aplicação para utilizar o JSF. Disponibiliza automaticamente as configurações + necessárias para o JSF. Templates de CRUD também são disponibilizados. diff --git a/src/site/apt/jta.apt b/src/site/apt/jta.apt new file mode 100644 index 0000000..12379b5 --- /dev/null +++ b/src/site/apt/jta.apt @@ -0,0 +1,43 @@ +~~ 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. + + ------ + JTA extension + +JTA extension + + Esta extensão é destinada à aplicações que utilizem JTA como estratégia de transação. + + diff --git a/src/site/apt/release-notes.apt b/src/site/apt/release-notes.apt new file mode 100755 index 0000000..6fc0f39 --- /dev/null +++ b/src/site/apt/release-notes.apt @@ -0,0 +1,188 @@ +~~ 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. + + ------ + Notas de Versão + +Notas de Versão + +* v2.2.0 + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=711}0000711}} [Bug] FileRenderer implementando Serializable. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=697}0000697}} [Bug] Correção do Nullpointer ao executar Beans.getReference(Logger.class). + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=693}0000693}} [Bug] SecurityContext criava várias instâncias de Authenticator e Authorizer. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=721}0000721}} [Improvement] Criação de casos de teste unitário no arquétipo jsf-jpa. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=673}0000673}} [Improvement] SecurityContext.isLoggedIn() verifica se authenticator.getUser() está nulo. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=680}0000680}} [Improvement] As extensões JUnit, Vaadin, Shiro viraram componentes. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=681}0000681}} [Improvement] Arquétipo Vaadin migrado para componente. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=682}0000682}} [Improvement] Parent POM Vaadin migrado para componente. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=683}0000683}} [Improvement] Remoção do código depreciado na versão 2.1. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=706}0000706}} [Improvement] Atualização da versão do hibernate-validator. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=703}0000703}} [Improvement] Atualização do repositório do primefaces. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=696}0000696}} [Improvement] Correção da mensagem de sessão invalidada anteriormente. + + +* {{{../2.1.2/}v2.1.2}} + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=667}0000667}} [Bug] Correção na renderização de tabelas JSF do arquétipo demoiselle-jsf-jpa. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=654}0000654}} [Bug] Erro no arquétipo jsf-jpa: Property 'label.confirm.delete' not found. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=663}0000663}} [Bug] Comandos JPA em ambientes JTA não se uniam à transação antes de executar o comando. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=666}0000666}} [Bug] Correção do erro "You cannot set autocommit during a managed transaction!". + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=661}0000661}} [Improvement] Depreciação do pacote "br.gov.frameworkdemoiselle.event". + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=664}0000664}} [Improvement] Depreciação do estereótipo @Presenter da extensão Vaadin. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=662}0000662}} [Improvement] Depreciação das exceções do pacote "br.gov.frameworkdemoiselle.exception". + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=660}0000660}} [Task] Organização do código interno. + +* {{{../2.1.1/}v2.1.1}} + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=621}0000621}} [Bug] Erro em Classe que usa @Configuration. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=623}0000623}} [Bug] Telas de edição com Id do tipo String. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=624}0000624}} [Bug] Erros em arquivos do Arquétipo JPA-JSF. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=625}0000625}} [Bug] Correção do erro ao executar Maven Test no demoiselle-junit. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=638}0000638}} [Bug] Ambiguidade em classes de configuração. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=643}0000643}} [Bug] Mudança de URL no repositório JBoss. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=651}0000651}} [Bug] Correção do nome da interface Authorizator para Authorizer. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=636}0000636}} [Improvement] Possibilidade de desabilitar o redirecionamento no login e logout. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=637}0000637}} [Improvement] Mudança no redirecionamento ao realizar logout. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=641}0000641}} [Improvement] Substituição da propriedade frameworkdemoiselle.security.welcome.page. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=646}0000646}} [Improvement] Melhorias de Testes e Código. + +* {{{../2.1.0/}v2.1.0}} + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=601}0000601}} [Bug] Falha ao realizar operações no banco de dados com JPATransaction. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=598}0000598}} [Bug] ClassNotFoundException: br.gov.frameworkdemoiselle.transaction.JTATransaction. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=597}0000597}} [Bug] Unsatisfied dependencies for type UserTransaction. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=584}0000584}} [Bug] Falha no tratamento de exceção no MB quando em método com retorno String. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=582}0000582}} [Bug] Erro "No active contexts" ao reiniciar uma aplicação contendo @Shutdown. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=596}0000596}} [Improvement] Mudança no nome dos eventos LoginSuccessful e LogoutSuccessful. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=595}0000595}} [Improvement] Fechamento automático dos EntityManager e EntityManagerFactory. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=594}0000594}} [Improvement] Flush automático do EntityManager no commit da transação JTA. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=593}0000593}} [Improvement] Criação da extensão JTA. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=592}0000592}} [Improvement] Renomear Classes de Eventos da extensão Vaadin. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=591}0000591}} [Improvement] Mudança na Estrutura de Pacotes da extensão Vaadin. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=577}0000577}} [Improvement] Novo arquétipo demoiselle-minimal. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=579}0000579}} [Improvement] Inclusão do demoiselle-junit no arquétipo jsf-jpa. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=578}0000578}} [Improvement] Classe utilitária para redirecionamento JSF2 no demoiselle-jsf. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=573}0000573}} [Improvement] Fábrica para obter Response. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=457}0000457}} [New Feature] Especificação Demoiselle 2.0 - Segurança. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=583}0000583}} [New Feature] Extensão para controle de acesso com o Apache Shiro. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=524}0000524}} [New Feature] Extensão para camada de apresentação com Vaadin + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=580}0000580}} [Task] Parent POM demoiselle-app-parent renomeado para demoiselle-minimal-parent. + +* {{{../2.0.2/}v2.0.2}} + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=558}0000558}} [Bug] Abafando Exception do JPA ConfigurationException("??????????????????????"). + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=557}0000557}} [Bug] NullPointerException ao executar Beans.getReference(EntityManager.class). + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=566}0000566}} [Bug] Erro ao utilizar o demoiselle-junit com o demoiselle-jsf. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=563}0000563}} [Bug] Não é possível trabalhar com duas persistence-unit. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=562}0000562}} [Improvement] Alterar o arquétipo para suportar o Tomcat. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=560}0000560}} [Task] Criar Testes Unitários para a fábrica de EntityManager. + +* {{{../2.0.1/}v2.0.1}} + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=538}0000538}} [Bug] Possível loop infinito em ResourceBundleFactory. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=521}0000521}} [Bug] Dependencia indevida do componente demoiselle-validation-1.0.0-SNAPSHOT. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=517}0000517}} [Bug] Tratamento de exceções não funciona com o Weld 1.1.0-CR4. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=523}0000523}} [Improvement] Possibilitar injeção com jUnit. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=522}0000522}} [Improvement] Renomear a extensão Swing para SE. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=518}0000518}} [Improvement] Possibilitar o deploy de aplicações JSF em servidores Tomcat 6 e 7. + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=534}0000534}} [Task] Disponibilizar o site do framework. + +* v2.0.0 + + * {{{http://sourceforge.net/apps/mantisbt/demoiselle/view.php?id=456}0000456}} [New Feature] Especificação Demoiselle 2.0. + +* {{{../latest1x.php}v1.x.x}} + + * Para versões anteriores {{{../latest1x.php}clique aqui}}. + + \ No newline at end of file diff --git a/src/site/apt/se.apt b/src/site/apt/se.apt new file mode 100644 index 0000000..b434adc --- /dev/null +++ b/src/site/apt/se.apt @@ -0,0 +1,41 @@ +~~ 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. + + ------ + SE extension + +SE extension + + Extende o framework para uso em plataformas SE, o famoso mundo desktop. diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100755 index 0000000..12cf25e --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,77 @@ + + + + ${project.name} + images/logo-l.png + ${project.url} + + + + images/logo-r.png + + + + + + + br.gov.frameworkdemoiselle.component + demoiselle-default-skin + 2.0.1 + + + + + + + + + + + + + + + + + + + + + + + -- libgit2 0.21.2