diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/CustomContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/CustomContext.java new file mode 100644 index 0000000..2b15cb3 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/CustomContext.java @@ -0,0 +1,27 @@ +package br.gov.frameworkdemoiselle.context; + +import javax.enterprise.context.spi.Context; + +/** + * + * Base interface for contexts managed by the framework. + * + * @author serpro + * + */ +public interface CustomContext extends Context { + + /** + * Activates a custom context + * + * @return true if context was activated, false if there was already another active + * context for the same scope and the activation of this scope failed. + */ + boolean activate(); + + /** + * Deactivates this context, it will clear all beans stored on this context. + */ + void deactivate(); + +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/RequestContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/RequestContext.java new file mode 100644 index 0000000..9342667 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/RequestContext.java @@ -0,0 +1,5 @@ +package br.gov.frameworkdemoiselle.context; + + +public interface RequestContext extends CustomContext { +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/SessionContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/SessionContext.java new file mode 100644 index 0000000..54906ba --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/SessionContext.java @@ -0,0 +1,6 @@ +package br.gov.frameworkdemoiselle.context; + + + +public interface SessionContext extends CustomContext { +} \ No newline at end of file diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/StaticContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/StaticContext.java new file mode 100644 index 0000000..17810cf --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/StaticContext.java @@ -0,0 +1,6 @@ +package br.gov.frameworkdemoiselle.context; + + + +public interface StaticContext extends CustomContext { +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/ViewContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/ViewContext.java new file mode 100644 index 0000000..185f372 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/context/ViewContext.java @@ -0,0 +1,6 @@ +package br.gov.frameworkdemoiselle.context; + + + +public interface ViewContext extends CustomContext { +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractLifecycleBootstrap.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractLifecycleBootstrap.java index f8a0634..92aa532 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractLifecycleBootstrap.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/AbstractLifecycleBootstrap.java @@ -42,11 +42,7 @@ import java.util.Collections; import java.util.Iterator; 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.Extension; @@ -55,9 +51,9 @@ import javax.enterprise.inject.spi.ProcessAnnotatedType; import org.slf4j.Logger; import br.gov.frameworkdemoiselle.DemoiselleException; -import br.gov.frameworkdemoiselle.annotation.ViewScoped; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.internal.context.RequestContextImpl; +import br.gov.frameworkdemoiselle.internal.context.SessionContextImpl; +import br.gov.frameworkdemoiselle.internal.context.ThreadLocalViewContextImpl; import br.gov.frameworkdemoiselle.internal.implementation.AnnotatedMethodProcessor; import br.gov.frameworkdemoiselle.util.Beans; import br.gov.frameworkdemoiselle.util.NameQualifier; @@ -109,7 +105,7 @@ public abstract class AbstractLifecycleBootstrap implement } } - public void loadTempContexts(@Observes final AfterBeanDiscovery event) { + /*public void loadTempContexts(@Observes final AfterBeanDiscovery event) { // Caso este bootstrap rode antes do CoreBootstrap. Não há problemas em chamar este método várias vezes, ele // ignora chamadas adicionais. ContextManager.initialize(event); @@ -119,7 +115,7 @@ public abstract class AbstractLifecycleBootstrap implement ContextManager.add(new ThreadLocalContext(SessionScoped.class), event); ContextManager.add(new ThreadLocalContext(ConversationScoped.class), event); ContextManager.add(new ThreadLocalContext(RequestScoped.class), event); - } + }*/ @SuppressWarnings({ "unchecked", "rawtypes" }) protected synchronized void proccessEvent() { @@ -127,12 +123,15 @@ public abstract class AbstractLifecycleBootstrap implement Collections.sort(processors); Exception failure = null; + + RequestContextImpl tempRequestContext = Beans.getReference(RequestContextImpl.class); + SessionContextImpl tempSessionContext = Beans.getReference(SessionContextImpl.class); + ThreadLocalViewContextImpl tempViewContext = Beans.getReference(ThreadLocalViewContextImpl.class); if (!registered) { - ContextManager.activate(ThreadLocalContext.class, ViewScoped.class); - ContextManager.activate(ThreadLocalContext.class, SessionScoped.class); - ContextManager.activate(ThreadLocalContext.class, ConversationScoped.class); - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + tempRequestContext.activate(); + tempSessionContext.activate(); + tempViewContext.activate(); registered = true; } @@ -155,10 +154,9 @@ public abstract class AbstractLifecycleBootstrap implement } if (processors.isEmpty()) { - ContextManager.deactivate(ThreadLocalContext.class, ViewScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, SessionScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, ConversationScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + tempRequestContext.deactivate(); + tempSessionContext.deactivate(); + tempViewContext.deactivate(); } if (failure != null) { diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java index 2bcda1a..eb24925 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/CoreBootstrap.java @@ -39,7 +39,6 @@ package br.gov.frameworkdemoiselle.internal.bootstrap; import java.util.Locale; import javax.enterprise.event.Observes; -import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.AfterDeploymentValidation; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.BeforeBeanDiscovery; @@ -48,9 +47,6 @@ import javax.enterprise.inject.spi.Extension; import org.slf4j.Logger; -import br.gov.frameworkdemoiselle.annotation.StaticScoped; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.StaticContext; import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; import br.gov.frameworkdemoiselle.util.Beans; import br.gov.frameworkdemoiselle.util.ResourceBundle; @@ -60,7 +56,7 @@ public class CoreBootstrap implements Extension { private Logger logger; private transient ResourceBundle bundle; - + private Logger getLogger() { if (this.logger == null) { this.logger = LoggerProducer.create(CoreBootstrap.class); @@ -84,16 +80,13 @@ public class CoreBootstrap implements Extension { getLogger().info(getBundle().getString("setting-up-bean-manager", Beans.class.getCanonicalName())); } - public void initializeCustomContexts(@Observes final AfterBeanDiscovery event) { - // StaticContext já é criado e gerenciado por esta chamada - ContextManager.initialize(event); - - ContextManager.activate(StaticContext.class, StaticScoped.class); - } + /*public void initializeCustomContexts(@Observes final AfterBeanDiscovery event) { + Beans.getReference(ContextManager2.class); + }*/ - public void terminateCustomContexts(@Observes final BeforeShutdown event) { + /*public void terminateCustomContexts(@Observes final BeforeShutdown event) { ContextManager.shutdown(); - } + }*/ public void takeOff(@Observes final AfterDeploymentValidation event) { getLogger().info(getBundle().getString("taking-off")); diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java index a6f32a4..86231e1 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java @@ -8,7 +8,6 @@ import java.util.Locale; import java.util.Set; 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.Bean; @@ -17,8 +16,6 @@ import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; import br.gov.frameworkdemoiselle.DemoiselleException; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ManagedContext; import br.gov.frameworkdemoiselle.internal.management.ManagedType; import br.gov.frameworkdemoiselle.internal.management.Management; import br.gov.frameworkdemoiselle.lifecycle.AfterShutdownProccess; @@ -40,10 +37,10 @@ public class ManagementBootstrap implements Extension { } } - public void activateContexts(@Observes final AfterBeanDiscovery event) { + /*public void activateContexts(@Observes final AfterBeanDiscovery event) { ContextManager.initialize(event); ContextManager.add(new ManagedContext(), event); - } + }*/ @SuppressWarnings("unchecked") public void registerAvailableManagedTypes(@Observes final AfterDeploymentValidation event, BeanManager beanManager) { diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractCustomContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractCustomContext.java index f52b2a8..fb73408 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractCustomContext.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractCustomContext.java @@ -42,9 +42,18 @@ import java.util.HashMap; import java.util.Map; import javax.enterprise.context.ContextNotActiveException; +import javax.enterprise.context.spi.Context; 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.slf4j.Logger; + +import br.gov.frameworkdemoiselle.context.CustomContext; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.NameQualifier; +import br.gov.frameworkdemoiselle.util.ResourceBundle; public abstract class AbstractCustomContext implements CustomContext { @@ -52,7 +61,7 @@ public abstract class AbstractCustomContext implements CustomContext { private final Class scope; - public AbstractCustomContext(final Class scope) { + AbstractCustomContext(final Class scope) { this.scope = scope; this.active = false; } @@ -97,14 +106,47 @@ public abstract class AbstractCustomContext implements CustomContext { return this.active; } - public void setActive(boolean active) { - if (!active && this.active) { - // Limpando contexto + @Override + public boolean activate() { + if (!this.active){ + Logger logger = getLogger(); + ResourceBundle bundle = getBundle(); + + BeanManager beanManager = Beans.getBeanManager(); + if (beanManager!=null){ + try{ + Context ctx = beanManager.getContext(this.getScope()); + if (ctx!=null){ + logger.debug( bundle.getString("custom-context-already-activated" , this.getClass().getCanonicalName() , this.getScope().getSimpleName() , ctx.getClass().getCanonicalName() ) ); + } + } + catch(ContextNotActiveException ce){ + this.active = true; + logger.debug( bundle.getString("custom-context-was-activated" , this.getClass().getCanonicalName() , this.getScope().getSimpleName() ) ); + } + } + else{ + this.active = true; + logger.debug( bundle.getString("custom-context-was-activated" , this.getClass().getCanonicalName() , this.getScope().getSimpleName() ) ); + } + } + + return this.active; + } + + @Override + public void deactivate(){ + if (this.active){ if (isStoreInitialized()){ getStore().clear(); } + + this.active = false; + + Logger logger = getLogger(); + ResourceBundle bundle = getBundle(); + logger.debug( bundle.getString("custom-context-was-deactivated" , this.getClass().getCanonicalName() , this.getScope().getSimpleName() ) ); } - this.active = active; } @Override @@ -115,6 +157,14 @@ public abstract class AbstractCustomContext implements CustomContext { protected static Store createStore() { return new Store(); } + + private ResourceBundle getBundle(){ + return Beans.getReference(ResourceBundle.class , new NameQualifier("demoiselle-core-bundle")); + } + + private Logger getLogger(){ + return Beans.getReference(Logger.class); + } static class Store { diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractThreadLocalContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractThreadLocalContext.java new file mode 100644 index 0000000..67958e9 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractThreadLocalContext.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. + */ +/* + * 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; + +/** + * This context keeps a separated store for beans for each running thread. It is intended + * to keep beans of short lived scopes like the Request scope, on environments that lack + * those scopes by default. + * + * @author serpro + */ +public abstract class AbstractThreadLocalContext extends AbstractCustomContext { + + private final ThreadLocal threadLocal = new ThreadLocal(); + + AbstractThreadLocalContext(final Class scope) { + super(scope); + } + + @Override + protected boolean isStoreInitialized() { + return threadLocal.get()!=null; + } + + @Override + protected Store getStore() { + if (this.threadLocal.get() == null) { + this.threadLocal.set(createStore()); + } + + return this.threadLocal.get(); + } +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager.java deleted file mode 100644 index 934d97f..0000000 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager.java +++ /dev/null @@ -1,324 +0,0 @@ -package br.gov.frameworkdemoiselle.internal.context; - -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.ContextNotActiveException; -import javax.enterprise.context.spi.Context; -import javax.enterprise.inject.spi.AfterBeanDiscovery; -import javax.enterprise.inject.spi.BeanManager; - -import org.slf4j.Logger; - -import br.gov.frameworkdemoiselle.DemoiselleException; -import br.gov.frameworkdemoiselle.annotation.StaticScoped; -import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; -import br.gov.frameworkdemoiselle.util.Beans; -import br.gov.frameworkdemoiselle.util.ResourceBundle; - -/** - *

- * Manage custom contexts relevant to Demoiselle operations. - *

- *

- * When starting, the ContextManager must be initialized by calling {@link #initialize(AfterBeanDiscovery event)} inside - * any methods observing the {@link AfterBeanDiscovery} event. Upon initialization a {@link StaticContext} will be - * created to handle {@link StaticScoped} beans (but not activated, you must call - * {@link #activate(Class customContextClass, Class scope)} to activate this context). - *

- *

- * If an extension wants to manage another custom context, it must first call - * {@link #add(CustomContext context, AfterBeanDiscovery event)} to add it's context to the list of managed contexts and - * then call {@link #activate(Class customContextClass, Class scope)} whenever it wants to activate this added context - * (contexts added through the {@link #add(CustomContext context, AfterBeanDiscovery event)} method are also not - * activated upon adding). - *

- * - * @author serpro - */ -public final class ContextManager { - - private static final Map> contextsCache = Collections - .synchronizedMap(new HashMap>()); - - private static final Map initializedCache = Collections - .synchronizedMap(new HashMap()); - - private ContextManager() { - } - - private synchronized static List getContexts() { - List contexts = contextsCache.get(getCurrentClassLoader()); - - if (contexts == null) { - contexts = Collections.synchronizedList(new ArrayList()); - contextsCache.put(getCurrentClassLoader(), contexts); - } - - return contexts; - } - - private synchronized static boolean isInitialized() { - Boolean initialized = initializedCache.get(getCurrentClassLoader()); - - if (initialized == null) { - initialized = false; - initializedCache.put(getCurrentClassLoader(), initialized); - } - - return initialized; - } - - private static void setInitialized(boolean initialized) { - initializedCache.put(getCurrentClassLoader(), initialized); - } - - private static ClassLoader getCurrentClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - - /** - *

- * Initializes this manager and adds the {@link StaticContext} context to the list of managed contexts. Other - * contexts must be added before they can be activated. - *

- *

- * It's OK to call this method multiple times, it will be initialized only once. - *

- * - * @param event - * The CDI event indicating all beans have been discovered. - */ - public static void initialize(AfterBeanDiscovery event) { - if (isInitialized()) { - return; - } - - add(new StaticContext(), event); - setInitialized(true); - } - - /** - *

- * Adds a context to the list of managed contexts. - *

- *

- * A context added through this method will be deactivated before management can start. Only after calling - * {@link #activate(Class customContextClass, Class scope)} the context will be activated. - *

- *

- * Trying to add a context already managed will result in this method call being ignored. - *

- * - * @param context - * The context to be added - * @param event - * The CDI event indicating all beans have been discovered. - */ - public static void add(CustomContext context, AfterBeanDiscovery event) { - for (CustomContextCounter contextCounter : getContexts()) { - if (contextCounter.isSame(context.getClass(), context.getScope())) { - - ContextManager.getLogger().trace( - ContextManager.getBundle().getString("bootstrap-context-already-managed", - context.getClass().getCanonicalName(), context.getScope().getCanonicalName())); - - return; - } - } - - ContextManager.getLogger().trace( - ContextManager.getBundle().getString("bootstrap-context-added", context.getClass().getCanonicalName(), - context.getScope().getCanonicalName())); - - context.setActive(false); - event.addContext(context); - getContexts().add(new CustomContextCounter(context)); - } - - /** - *

- * Activates a managed context. - *

- *

- * To be activated, a context must fulfill the following requisites: - *

    - *
  • Must be managed by this class (be of type {@link StaticScoped} or be added with - * {@link #add(CustomContext context, AfterBeanDiscovery event)})
  • - *
  • Must be of a scope not already attached to another active context
  • - *
- *

- * - * @param customContextClass - * Type of context to activate - * @param scope - * The scope to activate this context for - * @return true if there is a managed context of the provided type and scope and no other context is - * active for the provided scope, false if there is a managed context of the provided type and - * scope but another context is active for the provided scope. - * @throws DemoiselleException - * if there is no managed context of the provided type and scope. - */ - public static synchronized void activate(Class customContextClass, - Class scope) { - if (!isInitialized()) { - throw new DemoiselleException(getBundle().getString("custom-context-manager-not-initialized")); - } - - for (CustomContextCounter context : getContexts()) { - if (context.isSame(customContextClass, scope)) { - context.activate(); - return; - } - } - - throw new DemoiselleException(getBundle().getString("custom-context-not-found", - customContextClass.getCanonicalName(), scope.getSimpleName())); - } - - /** - *

- * Deactivates a managed context. - *

- *

- * To be deactivated, a context must fulfill the following requisites: - *

    - *
  • Must be managed by this class (be of type {@link StaticScoped} or be added with - * {@link #add(CustomContext context, AfterBeanDiscovery event)})
  • - *
  • Must have been activated by a previous call to {@link #activate(Class customContextClass, Class scope)}
  • - *
  • This previous call must have returned true. - *
- *

- * - * @param customContextClass - * Type of context to deactivate - * @param scope - * The scope the context controled when it was active - * @return true if there was an active context of this type and scope and it was activated by a - * previous call to {@link #activate(Class customContextClass, Class scope)} - * @throws DemoiselleException - * if there is no managed context of the provided type and scope. - */ - public static synchronized void deactivate(Class customContextClass, - Class scope) { - if (!isInitialized()) { - throw new DemoiselleException(getBundle().getString("custom-context-manager-not-initialized")); - } - - for (CustomContextCounter context : getContexts()) { - if (context.isSame(customContextClass, scope)) { - context.deactivate(); - return; - } - } - - throw new DemoiselleException(getBundle().getString("custom-context-not-found", - customContextClass.getCanonicalName(), scope.getSimpleName())); - } - - /** - *

- * This method should be called when the application is shutting down. - *

- */ - public static synchronized void shutdown() { - for (CustomContextCounter context : getContexts()) { - context.shutdown(); - } - - getContexts().clear(); - setInitialized(false); - } - - static Logger getLogger() { - return LoggerProducer.create(ContextManager.class); - } - - static ResourceBundle getBundle() { - return new ResourceBundle("demoiselle-core-bundle", Locale.getDefault()); - } -} - -/** - * Class that counts how many attemps to activate and deactivate this context received, avoiding cases where one client - * activates given context and another one deactivates it, leaving the first client with no active context before - * completion. - * - * @author serpro - */ -class CustomContextCounter { - - private CustomContext context; - - private int activationCounter = 0; - - public CustomContextCounter(CustomContext customContext) { - this.context = customContext; - } - - public boolean isSame(Class customContextClass, Class scope) { - if (context.getClass().getCanonicalName().equals(customContextClass.getCanonicalName()) - && context.getScope().equals(scope)) { - return true; - } - - return false; - } - - public CustomContext getInternalContext() { - return this.context; - } - - public void setInternalContext(CustomContext context) { - this.context = context; - } - - public synchronized void activate() { - try { - BeanManager beanManager = Beans.getReference(BeanManager.class); - Context c = beanManager.getContext(context.getScope()); - - if (c == context) { - activationCounter++; - } else { - ContextManager.getLogger().trace( - ContextManager.getBundle().getString("custom-context-already-activated", - context.getClass().getCanonicalName(), c.getScope().getCanonicalName(), - c.getClass().getCanonicalName())); - } - } catch (ContextNotActiveException ce) { - context.setActive(true); - activationCounter++; - ContextManager.getLogger().trace( - ContextManager.getBundle().getString("custom-context-was-activated", - context.getClass().getCanonicalName(), context.getScope().getCanonicalName())); - } - } - - public synchronized void deactivate() { - try { - Context c = Beans.getBeanManager().getContext(context.getScope()); - if (c == context) { - activationCounter--; - if (activationCounter == 0) { - context.setActive(false); - ContextManager.getLogger().trace( - ContextManager.getBundle().getString("custom-context-was-deactivated", - context.getClass().getCanonicalName(), context.getScope().getCanonicalName())); - } - } - } catch (ContextNotActiveException ce) { - } - } - - public synchronized void shutdown() { - context.setActive(false); - context = null; - activationCounter = 0; - } -} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager2.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager2.java new file mode 100644 index 0000000..4198b77 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ContextManager2.java @@ -0,0 +1,109 @@ +package br.gov.frameworkdemoiselle.internal.context; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; + +import org.slf4j.Logger; + +import br.gov.frameworkdemoiselle.context.CustomContext; +import br.gov.frameworkdemoiselle.internal.implementation.StrategySelector; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.NameQualifier; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@ApplicationScoped +public class ContextManager2 { + + private List contexts; + + @PostConstruct + private void initialize(){ + if (contexts==null || contexts.isEmpty()){ + Logger logger = getLogger(); + ResourceBundle bundle = getBundle(); + + CustomContext ctx; + + contexts = new ArrayList(); + + ctx = new RequestContextImpl(); + contexts.add(ctx); + logger.debug( bundle.getString("bootstrap-context-added", RequestContextImpl.class.getCanonicalName() , ctx.getScope().getSimpleName() ) ); + + ctx = new SessionContextImpl(); + contexts.add(ctx); + logger.debug( bundle.getString("bootstrap-context-added", SessionContextImpl.class.getCanonicalName() , ctx.getScope().getSimpleName() ) ); + + ctx = new StaticContextImpl(); + contexts.add(ctx); + logger.debug( bundle.getString("bootstrap-context-added", StaticContextImpl.class.getCanonicalName() , ctx.getScope().getSimpleName() ) ); + + ctx = new ThreadLocalViewContextImpl(); + contexts.add(ctx); + logger.debug( bundle.getString("bootstrap-context-added", ThreadLocalViewContextImpl.class.getCanonicalName() , ctx.getScope().getSimpleName() ) ); + } + } + + @PreDestroy + private void closeContexts(){ + for (CustomContext context : contexts){ + context.deactivate(); + } + + contexts.clear(); + } + + public void addCustomContext(CustomContext context){ + Logger logger = getLogger(); + ResourceBundle bundle = getBundle(); + + if (!contexts.contains(context)){ + contexts.add(context); + logger.debug( bundle.getString("bootstrap-context-added", context.getClass().getCanonicalName() , context.getScope().getSimpleName() ) ); + } + else{ + logger.debug( bundle.getString("bootstrap-context-already-managed", context.getClass().getCanonicalName() , context.getScope().getSimpleName() ) ); + } + } + + @Produces + public CustomContext getContext(InjectionPoint ip){ + CustomContext producedContext = null; + + if (ip!=null){ + Class beanClass = ip.getBean().getBeanClass(); + ArrayList selectableContexts = new ArrayList(); + + for (CustomContext context : contexts){ + if ( beanClass.isAssignableFrom( context.getClass() ) ){ + if (context.isActive()){ + producedContext = context; + break; + } + else{ + selectableContexts.add(context); + } + } + } + + producedContext = StrategySelector.selectInstance(CustomContext.class, selectableContexts); + } + + return producedContext; + } + + private ResourceBundle getBundle(){ + return Beans.getReference(ResourceBundle.class , new NameQualifier("demoiselle-core-bundle")); + } + + private Logger getLogger(){ + return Beans.getReference(Logger.class); + } + +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java deleted file mode 100644 index f1528eb..0000000 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/CustomContext.java +++ /dev/null @@ -1,9 +0,0 @@ -package br.gov.frameworkdemoiselle.internal.context; - -import javax.enterprise.context.spi.Context; - -public interface CustomContext extends Context { - - void setActive(boolean active); - -} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ManagedContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ManagedContext.java deleted file mode 100644 index 404069e..0000000 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ManagedContext.java +++ /dev/null @@ -1,22 +0,0 @@ -package br.gov.frameworkdemoiselle.internal.context; - -import javax.enterprise.context.RequestScoped; - -import br.gov.frameworkdemoiselle.stereotype.ManagementController; - -/** - * Context that stores {@link RequestScoped} beans during client calls to {@link ManagementController} classes. This - * context is only activated when no other context is active for {@link RequestScoped}. - * - * @author serpro - */ -public class ManagedContext extends ThreadLocalContext { - - /** - * Constructs a new context. - */ - public ManagedContext() { - super(RequestScoped.class); - } - -} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/RequestContextImpl.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/RequestContextImpl.java new file mode 100644 index 0000000..0b4d967 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/RequestContextImpl.java @@ -0,0 +1,21 @@ +package br.gov.frameworkdemoiselle.internal.context; + +import javax.enterprise.context.RequestScoped; + +import br.gov.frameworkdemoiselle.annotation.Priority; +import br.gov.frameworkdemoiselle.context.RequestContext; + +/** + * Custom request context that stores beans in a thread local store. + * + * @author serpro + * + */ +@Priority(Priority.MIN_PRIORITY) +public class RequestContextImpl extends AbstractThreadLocalContext implements RequestContext { + + RequestContextImpl() { + super(RequestScoped.class); + } + +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/SessionContextImpl.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/SessionContextImpl.java new file mode 100644 index 0000000..073ea80 --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/SessionContextImpl.java @@ -0,0 +1,21 @@ +package br.gov.frameworkdemoiselle.internal.context; + +import javax.enterprise.context.SessionScoped; + +import br.gov.frameworkdemoiselle.annotation.Priority; +import br.gov.frameworkdemoiselle.context.SessionContext; + + +/** + * + * @author serpro + * + */ +@Priority(Priority.MIN_PRIORITY) +public class SessionContextImpl extends StaticContextImpl implements SessionContext { + + SessionContextImpl() { + super(SessionScoped.class); + } + +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContext.java deleted file mode 100644 index eb91ad2..0000000 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContext.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package br.gov.frameworkdemoiselle.internal.context; - -import br.gov.frameworkdemoiselle.annotation.StaticScoped; - -public class StaticContext extends AbstractCustomContext { - - private final static Store store = createStore(); - - public StaticContext() { - super(StaticScoped.class); - } - - @Override - protected Store getStore() { - return store; - } - - @Override - protected boolean isStoreInitialized() { - return store!=null; - } -} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContextImpl.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContextImpl.java new file mode 100644 index 0000000..328dece --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/StaticContextImpl.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.internal.context; + +import java.lang.annotation.Annotation; + +import br.gov.frameworkdemoiselle.annotation.Priority; +import br.gov.frameworkdemoiselle.annotation.StaticScoped; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +/** + * + *

This context has a unified static store that keeps all scoped beans available + * to all threads of an application. It is intended to keep beans avaliable to + * long lasting scopes (like the Session scope and Application scope) on environments + * that lack those scopes by default (like desktop Swing applications).

+ * + *

This context also keeps beans of the custom {@link StaticScoped} scope, like the beans + * annotated with {@link Configuration}.

+ * + * @author serpro + * + */ +@Priority(Priority.MIN_PRIORITY) +public class StaticContextImpl extends AbstractCustomContext { + + private final static Store store = createStore(); + + /** + * Constructs this context to control the provided scope + */ + StaticContextImpl(Class scope) { + super(scope); + } + + /** + * Constructs this context to control {@link StaticScoped} beans + */ + StaticContextImpl() { + super(StaticScoped.class); + } + + @Override + protected Store getStore() { + return store; + } + + @Override + protected boolean isStoreInitialized() { + return store!=null; + } +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java deleted file mode 100644 index 232af59..0000000 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalContext.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -/* - * 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; - -/** - * Base context that has a separated store for each thread - * - * @author serpro - */ -public class ThreadLocalContext extends AbstractCustomContext { - - private final ThreadLocal threadLocal = new ThreadLocal(); - - public ThreadLocalContext(final Class scope) { - super(scope); - } - - @Override - protected boolean isStoreInitialized() { - return threadLocal.get()!=null; - } - - @Override - protected Store getStore() { - if (this.threadLocal.get() == null) { - this.threadLocal.set(createStore()); - } - - return this.threadLocal.get(); - } -} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalViewContextImpl.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalViewContextImpl.java new file mode 100644 index 0000000..992ed6f --- /dev/null +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/ThreadLocalViewContextImpl.java @@ -0,0 +1,14 @@ +package br.gov.frameworkdemoiselle.internal.context; + +import br.gov.frameworkdemoiselle.annotation.Priority; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.context.ViewContext; + +@Priority(Priority.MIN_PRIORITY) +public class ThreadLocalViewContextImpl extends AbstractThreadLocalContext implements ViewContext { + + ThreadLocalViewContextImpl() { + super(ViewScoped.class); + } + +} diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java index d35f102..5dbc76f 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java @@ -44,7 +44,6 @@ import java.util.List; import java.util.Set; import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; @@ -56,8 +55,9 @@ import org.slf4j.Logger; import br.gov.frameworkdemoiselle.annotation.ManagedProperty; import br.gov.frameworkdemoiselle.annotation.Name; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ManagedContext; +import br.gov.frameworkdemoiselle.context.RequestContext; +import br.gov.frameworkdemoiselle.context.SessionContext; +import br.gov.frameworkdemoiselle.context.ViewContext; import br.gov.frameworkdemoiselle.internal.management.ManagedType.MethodDetail; import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension; import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; @@ -301,36 +301,72 @@ public class Management implements Serializable { } private void activateContexts(Class managedType) { - logger.debug(bundle.getString("management-debug-starting-custom-context", - ManagedContext.class.getCanonicalName(), managedType.getCanonicalName())); + + RequestContext requestContext = Beans.getReference(RequestContext.class); + ViewContext viewContext = Beans.getReference(ViewContext.class); + SessionContext sessionContext = Beans.getReference(SessionContext.class); + + if (!requestContext.isActive()){ + logger.debug(bundle.getString("management-debug-starting-custom-context", + requestContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + requestContext.activate(); + } + + if (!viewContext.isActive()){ + logger.debug(bundle.getString("management-debug-starting-custom-context", + viewContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + viewContext.activate(); + } - ContextManager.activate(ManagedContext.class, RequestScoped.class); + if (!sessionContext.isActive()){ + logger.debug(bundle.getString("management-debug-starting-custom-context", + sessionContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + sessionContext.activate(); + } } private void deactivateContexts(Class managedType) { - logger.debug(bundle.getString("management-debug-stoping-custom-context", - ManagedContext.class.getCanonicalName(), managedType.getCanonicalName())); + RequestContext requestContext = Beans.getReference(RequestContext.class); + ViewContext viewContext = Beans.getReference(ViewContext.class); + SessionContext sessionContext = Beans.getReference(SessionContext.class); + + if (requestContext.isActive()){ + logger.debug(bundle.getString("management-debug-stoping-custom-context", + requestContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + requestContext.deactivate(); + } + + if (!viewContext.isActive()){ + logger.debug(bundle.getString("management-debug-stoping-custom-context", + viewContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + viewContext.deactivate(); + } - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + if (!sessionContext.isActive()){ + logger.debug(bundle.getString("management-debug-stoping-custom-context", + sessionContext.getClass().getCanonicalName(), managedType.getCanonicalName())); + + sessionContext.deactivate(); + } } public void shutdown(Collection> monitoringExtensions) { - for (Class monitoringExtensionClass : monitoringExtensions) { ManagementExtension monitoringExtension = Beans.getReference(monitoringExtensionClass); - monitoringExtension.shutdown(this.getManagedTypes()); - logger.debug(bundle.getString("management-debug-removing-management-extension", monitoringExtension .getClass().getCanonicalName())); } - } public void initialize(Collection> monitoringExtensions) { - for (Class monitoringExtensionClass : monitoringExtensions) { ManagementExtension monitoringExtension = Beans.getReference(monitoringExtensionClass); @@ -339,7 +375,6 @@ public class Management implements Serializable { monitoringExtension.initialize(this.getManagedTypes()); } - } private Validator getDefaultValidator() { diff --git a/impl/core/src/main/resources/demoiselle-core-bundle.properties b/impl/core/src/main/resources/demoiselle-core-bundle.properties index 1d1f611..8b060bd 100644 --- a/impl/core/src/main/resources/demoiselle-core-bundle.properties +++ b/impl/core/src/main/resources/demoiselle-core-bundle.properties @@ -66,8 +66,6 @@ configuration-not-conversion=N\u00E3o \u00E9 poss\u00EDvel converter o valor {0} transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a propriedade frameworkdemoiselle.transaction.class com a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo demoiselle.properties executing-all=Executando todos os \: {0} -custom-context-was-registered=O contexto {0} foi registrado -custom-context-was-unregistered=O contexto {0} foi removido custom-context-was-activated=O contexto {0} foi ativado para o escopo {1} custom-context-was-deactivated=O contexto {0} foi desativado para o escopo {1} custom-context-already-activated=N\u00E3o foi poss\u00EDvel ativar o contexto {0}, o escopo {1} j\u00E1 est\u00E1 ativo no contexto {2} diff --git a/impl/core/src/test/java/message/MessageContextTest.java b/impl/core/src/test/java/message/MessageContextTest.java index cca72ba..8eaebba 100644 --- a/impl/core/src/test/java/message/MessageContextTest.java +++ b/impl/core/src/test/java/message/MessageContextTest.java @@ -39,7 +39,6 @@ package message; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import junit.framework.Assert; @@ -51,8 +50,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import test.Tests; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ManagedContext; +import br.gov.frameworkdemoiselle.context.RequestContext; import br.gov.frameworkdemoiselle.message.DefaultMessage; import br.gov.frameworkdemoiselle.message.Message; import br.gov.frameworkdemoiselle.message.MessageContext; @@ -80,78 +78,92 @@ public class MessageContextTest { @Test public void testAddMessageWithoutParams() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Menssage without param"); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message); assertEquals(appender.getMessages().size(), 1); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testAddMessageWithoutParamsIfSeverityIsInfo() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Menssage without param"); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message); assertEquals(appender.getMessages().get(0).getSeverity(), SeverityType.INFO); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testAddMessageWitSeverityInfo() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Menssage without param", SeverityType.INFO); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message); assertEquals(appender.getMessages().get(0).getSeverity(), SeverityType.INFO); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testAddMessageWitSeverityWarn() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Menssage without param", SeverityType.WARN); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message); assertEquals(appender.getMessages().get(0).getSeverity(), SeverityType.WARN); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testAddMessageWitSeverityErro() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Menssage without param", SeverityType.ERROR); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message); assertEquals(appender.getMessages().get(0).getSeverity(), SeverityType.ERROR); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testRecoverStringMessageWithParams() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add("Message with {0} param", 1); assertTrue(appender.getMessages().get(0).getText().equals("Message with 1 param")); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testRecoverMessageWithParams() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message message = new DefaultMessage("Message with {0} param"); DummyMessageAppender appender = Beans.getReference(DummyMessageAppender.class); messageContext.add(message, 1); assertTrue(appender.getMessages().get(0).getText().equals("Message with 1 param")); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test @@ -164,21 +176,25 @@ public class MessageContextTest { @Test public void testMessageParsedText() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message MESSAGE_PARSED = new DefaultMessage("{MESSAGE_PARSED}"); String expected = "Message parsed"; String value = MESSAGE_PARSED.getText(); Assert.assertEquals(expected, value); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } @Test public void testMessageIsNull() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext context = Beans.getReference(RequestContext.class); + + context.activate(); Message NULL_MESSAGE = new DefaultMessage(null); String expected = null; String value = NULL_MESSAGE.getText(); Assert.assertEquals(expected, value); - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + context.deactivate(); } } diff --git a/impl/core/src/test/java/pagination/PaginationContextBasicTest.java b/impl/core/src/test/java/pagination/PaginationContextBasicTest.java index e128920..5019ed9 100644 --- a/impl/core/src/test/java/pagination/PaginationContextBasicTest.java +++ b/impl/core/src/test/java/pagination/PaginationContextBasicTest.java @@ -38,7 +38,6 @@ package pagination; import static junit.framework.Assert.assertEquals; -import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -51,11 +50,11 @@ import org.junit.runner.RunWith; import test.Tests; import transaction.defaultstrategy.TransactionDefaultTest; +import br.gov.frameworkdemoiselle.context.SessionContext; import br.gov.frameworkdemoiselle.internal.configuration.PaginationConfig; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; import br.gov.frameworkdemoiselle.pagination.Pagination; import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.Beans; @RunWith(Arquillian.class) public class PaginationContextBasicTest { @@ -96,13 +95,15 @@ public class PaginationContextBasicTest { @Before public void activeContext() { - ContextManager.activate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.activate(); pagination = paginationContext.getPagination(DummyEntity.class, true); } @After public void deactiveContext() { - ContextManager.deactivate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.deactivate(); } @Test diff --git a/impl/core/src/test/java/pagination/PaginationContextCache.java b/impl/core/src/test/java/pagination/PaginationContextCache.java index 6a88e72..efd78a5 100644 --- a/impl/core/src/test/java/pagination/PaginationContextCache.java +++ b/impl/core/src/test/java/pagination/PaginationContextCache.java @@ -38,7 +38,6 @@ package pagination; import static org.junit.Assert.assertEquals; -import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -51,10 +50,10 @@ import org.junit.runner.RunWith; import test.Tests; import transaction.defaultstrategy.TransactionDefaultTest; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.context.SessionContext; import br.gov.frameworkdemoiselle.pagination.Pagination; import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.Beans; @RunWith(Arquillian.class) public class PaginationContextCache { @@ -74,12 +73,14 @@ public class PaginationContextCache { @Before public void activeContext() { - ContextManager.activate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.activate(); } @After public void deactiveContext() { - ContextManager.deactivate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.deactivate(); } @Test diff --git a/impl/core/src/test/java/pagination/PaginationContextNullTest.java b/impl/core/src/test/java/pagination/PaginationContextNullTest.java index b438cd9..345bbaf 100644 --- a/impl/core/src/test/java/pagination/PaginationContextNullTest.java +++ b/impl/core/src/test/java/pagination/PaginationContextNullTest.java @@ -38,7 +38,6 @@ package pagination; import static org.junit.Assert.assertNull; -import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -51,10 +50,10 @@ import org.junit.runner.RunWith; import test.Tests; import transaction.defaultstrategy.TransactionDefaultTest; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.context.SessionContext; import br.gov.frameworkdemoiselle.pagination.Pagination; import br.gov.frameworkdemoiselle.pagination.PaginationContext; +import br.gov.frameworkdemoiselle.util.Beans; @RunWith(Arquillian.class) public class PaginationContextNullTest { @@ -72,12 +71,14 @@ public class PaginationContextNullTest { @Before public void activeContext() { - ContextManager.activate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.activate(); } @After public void deactiveContext() { - ContextManager.deactivate(ThreadLocalContext.class, SessionScoped.class); + SessionContext context = Beans.getReference(SessionContext.class); + context.deactivate(); } @Test diff --git a/impl/core/src/test/java/security/athentication/credentials/AcceptOrDenyCredentialsTest.java b/impl/core/src/test/java/security/athentication/credentials/AcceptOrDenyCredentialsTest.java index 924cfec..57d50e4 100644 --- a/impl/core/src/test/java/security/athentication/credentials/AcceptOrDenyCredentialsTest.java +++ b/impl/core/src/test/java/security/athentication/credentials/AcceptOrDenyCredentialsTest.java @@ -36,7 +36,6 @@ */ package security.athentication.credentials; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import junit.framework.Assert; @@ -48,8 +47,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import test.Tests; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.context.RequestContext; import br.gov.frameworkdemoiselle.security.AuthenticationException; import br.gov.frameworkdemoiselle.security.SecurityContext; import br.gov.frameworkdemoiselle.util.Beans; @@ -71,7 +69,8 @@ public class AcceptOrDenyCredentialsTest { @Test public void denyWrongCredentials() { - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); Credentials credentials = Beans.getReference(Credentials.class); credentials.setLogin("wronglogin"); @@ -84,14 +83,15 @@ public class AcceptOrDenyCredentialsTest { //Erro esperado } finally{ - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + ctx.deactivate(); } } @Test public void acceptRightCredentials() { - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); Credentials credentials = Beans.getReference(Credentials.class); credentials.setLogin("demoiselle"); @@ -103,7 +103,7 @@ public class AcceptOrDenyCredentialsTest { Assert.fail("Authenticator negou credenciais corretas"); } finally{ - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + ctx.deactivate(); } } diff --git a/impl/core/src/test/java/security/athentication/custom/CustomAuthenticatorTest.java b/impl/core/src/test/java/security/athentication/custom/CustomAuthenticatorTest.java index 8387bbc..2ce71ce 100644 --- a/impl/core/src/test/java/security/athentication/custom/CustomAuthenticatorTest.java +++ b/impl/core/src/test/java/security/athentication/custom/CustomAuthenticatorTest.java @@ -42,7 +42,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -52,9 +51,9 @@ import org.junit.Test; import org.junit.runner.RunWith; import test.Tests; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.context.RequestContext; import br.gov.frameworkdemoiselle.security.SecurityContext; +import br.gov.frameworkdemoiselle.util.Beans; import configuration.resource.ConfigurationResourceTest; @RunWith(Arquillian.class) @@ -82,25 +81,27 @@ public class CustomAuthenticatorTest { @Test public void loginProcess() { - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); context.login(); assertTrue(context.isLoggedIn()); assertNotNull(observer.getEvent()); assertEquals("demoiselle", context.getUser().getId()); - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + ctx.deactivate(); } @Test public void logoutProcess() { - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); context.login(); context.logout(); assertFalse(context.isLoggedIn()); assertNull(context.getUser()); - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + ctx.deactivate(); } } diff --git a/impl/core/src/test/java/template/TemplateTest.java b/impl/core/src/test/java/template/TemplateTest.java index 050e9ca..41a7254 100644 --- a/impl/core/src/test/java/template/TemplateTest.java +++ b/impl/core/src/test/java/template/TemplateTest.java @@ -43,7 +43,6 @@ import static junit.framework.Assert.assertNull; import java.util.List; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -55,8 +54,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import test.Tests; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ManagedContext; +import br.gov.frameworkdemoiselle.context.RequestContext; +import br.gov.frameworkdemoiselle.util.Beans; @RunWith(Arquillian.class) public class TemplateTest { @@ -83,7 +82,8 @@ public class TemplateTest { @Before public void initialize() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); this.crudImpl.resetEntities(); @@ -91,9 +91,8 @@ public class TemplateTest { @After public void finalize() { - - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); - + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.deactivate(); } @Test diff --git a/impl/core/src/test/java/transaction/rollback/TransactionRollbackTest.java b/impl/core/src/test/java/transaction/rollback/TransactionRollbackTest.java index 8130f18..badd963 100644 --- a/impl/core/src/test/java/transaction/rollback/TransactionRollbackTest.java +++ b/impl/core/src/test/java/transaction/rollback/TransactionRollbackTest.java @@ -40,7 +40,6 @@ import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.fail; -import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; @@ -52,9 +51,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import test.Tests; - -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ManagedContext; +import br.gov.frameworkdemoiselle.context.RequestContext; +import br.gov.frameworkdemoiselle.util.Beans; @RunWith(Arquillian.class) public class TransactionRollbackTest { @@ -76,12 +74,14 @@ public class TransactionRollbackTest { @Before public void activeContext() { - ContextManager.activate(ManagedContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.activate(); } @After public void deactiveContext() { - ContextManager.deactivate(ManagedContext.class, RequestScoped.class); + RequestContext ctx = Beans.getReference(RequestContext.class); + ctx.deactivate(); } @Test diff --git a/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/annotation/PersistenceScoped.java b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/annotation/PersistenceScoped.java new file mode 100644 index 0000000..67dbd5e --- /dev/null +++ b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/annotation/PersistenceScoped.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 PersistenceScoped { + +} diff --git a/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java index aed2a3e..e93ddf3 100644 --- a/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java +++ b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/EntityManagerConfig.java @@ -52,7 +52,7 @@ import br.gov.frameworkdemoiselle.util.Strings; public class EntityManagerConfig implements Serializable { private static final long serialVersionUID = 1L; - + /** * @deprecated */ @@ -62,6 +62,9 @@ public class EntityManagerConfig implements Serializable { @Name("default.unit.name") private String defaultPersistenceUnitName; + + @Name("entitymanager.scope") + private String entityManagerScope = "request"; /** * Getter for persistence unit name. @@ -92,4 +95,16 @@ public class EntityManagerConfig implements Serializable { return defaultPersistenceUnitName; } + + + public String getEntityManagerScope() { + return entityManagerScope; + } + + + public void setEntityManagerScope(String entityManagerScope) { + this.entityManagerScope = entityManagerScope; + } + + } diff --git a/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/context/PersistenceContext.java b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/context/PersistenceContext.java new file mode 100644 index 0000000..ae880a7 --- /dev/null +++ b/impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/context/PersistenceContext.java @@ -0,0 +1,12 @@ +package br.gov.frameworkdemoiselle.internal.context; + +import java.lang.annotation.Annotation; + + +public class PersistenceContext extends AbstractThreadLocalContext { + + public PersistenceContext(Class scope) { + super(scope); + } + +} diff --git a/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java b/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java index 324d446..5c81b83 100644 --- a/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java +++ b/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/JsfBootstrap.java @@ -41,10 +41,11 @@ import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.AfterDeploymentValidation; import javax.enterprise.inject.spi.Extension; -import br.gov.frameworkdemoiselle.annotation.ViewScoped; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ViewContext; +import br.gov.frameworkdemoiselle.context.ViewContext; +import br.gov.frameworkdemoiselle.internal.context.ContextManager2; +import br.gov.frameworkdemoiselle.internal.context.FacesViewContextImpl; import br.gov.frameworkdemoiselle.lifecycle.AfterShutdownProccess; +import br.gov.frameworkdemoiselle.util.Beans; public class JsfBootstrap implements Extension { @@ -54,17 +55,19 @@ public class JsfBootstrap implements Extension { public void storeContexts(@Observes final AfterBeanDiscovery event) { //Registra o ViewContext para controlar o escopo ViewScoped. - ContextManager.initialize(event); - ContextManager.add(new ViewContext(), event); + ContextManager2 contextManager = Beans.getReference(ContextManager2.class); + contextManager.addCustomContext(new FacesViewContextImpl()); } public void addContexts(@Observes final AfterDeploymentValidation event) { //Ativa o ViewContext - ContextManager.activate(ViewContext.class, ViewScoped.class); + ViewContext ctx = Beans.getReference(FacesViewContextImpl.class); + ctx.activate(); } public void removeContexts(@Observes AfterShutdownProccess event) { //Desativa o ViewContext - ContextManager.deactivate(ViewContext.class, ViewScoped.class); + ViewContext ctx = Beans.getReference(FacesViewContextImpl.class); + ctx.deactivate(); } } diff --git a/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/FacesViewContextImpl.java b/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/FacesViewContextImpl.java new file mode 100644 index 0000000..fb3d992 --- /dev/null +++ b/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/FacesViewContextImpl.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.context; + +import java.util.Map; + +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; + +import br.gov.frameworkdemoiselle.annotation.Priority; +import br.gov.frameworkdemoiselle.annotation.ViewScoped; +import br.gov.frameworkdemoiselle.context.ViewContext; +import br.gov.frameworkdemoiselle.util.Faces; + +/** + * + * This {@link ViewContext} implementation uses a map provided + * by {@link UIViewRoot#getViewMap()} as a store. Any beans stored on + * this store are kept as long as the view is still active. + * + * @author serpro + * + */ +@Priority(Priority.L2_PRIORITY) +public class FacesViewContextImpl extends AbstractCustomContext implements ViewContext { + + public FacesViewContextImpl() { + super(ViewScoped.class); + } + + @Override + protected boolean isStoreInitialized() { + return FacesContext.getCurrentInstance()!=null; + } + + @Override + protected Store getStore() { + Map viewMap = Faces.getViewMap(); + String key = Store.class.getName(); + + if (!viewMap.containsKey(key)) { + viewMap.put(key, createStore()); + } + + return (Store) viewMap.get(key); + } +} diff --git a/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java b/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java deleted file mode 100644 index 9bcdbe9..0000000 --- a/impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/context/ViewContext.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package br.gov.frameworkdemoiselle.internal.context; - -import java.util.Map; - -import javax.faces.context.FacesContext; - -import br.gov.frameworkdemoiselle.annotation.ViewScoped; -import br.gov.frameworkdemoiselle.util.Faces; - -public class ViewContext extends AbstractCustomContext { - - public ViewContext() { - super(ViewScoped.class); - } - - @Override - protected boolean isStoreInitialized() { - return FacesContext.getCurrentInstance()!=null; - } - - @Override - protected Store getStore() { - Map viewMap = Faces.getViewMap(); - String key = Store.class.getName(); - - if (!viewMap.containsKey(key)) { - viewMap.put(key, createStore()); - } - - return (Store) viewMap.get(key); - } -} diff --git a/impl/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java b/impl/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java index a5c03bf..28ccfe0 100644 --- a/impl/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java +++ b/impl/extension/se/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/SeBootstrap.java @@ -36,41 +36,35 @@ */ package br.gov.frameworkdemoiselle.internal.bootstrap; -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.Extension; -import br.gov.frameworkdemoiselle.annotation.ViewScoped; -import br.gov.frameworkdemoiselle.internal.context.ContextManager; -import br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext; +import br.gov.frameworkdemoiselle.context.RequestContext; +import br.gov.frameworkdemoiselle.context.SessionContext; +import br.gov.frameworkdemoiselle.context.ViewContext; import br.gov.frameworkdemoiselle.lifecycle.AfterShutdownProccess; +import br.gov.frameworkdemoiselle.util.Beans; public class SeBootstrap implements Extension { - public void storeContexts(@Observes final AfterBeanDiscovery event) { - ContextManager.initialize(event); - - ContextManager.add(new ThreadLocalContext(ViewScoped.class), event); - ContextManager.add(new ThreadLocalContext(SessionScoped.class), event); - ContextManager.add(new ThreadLocalContext(ConversationScoped.class), event); - ContextManager.add(new ThreadLocalContext(RequestScoped.class), event); - } - public void addContexts(@Observes final AfterDeploymentValidation event) { - ContextManager.activate(ThreadLocalContext.class, ViewScoped.class); - ContextManager.activate(ThreadLocalContext.class, SessionScoped.class); - ContextManager.activate(ThreadLocalContext.class, ConversationScoped.class); - ContextManager.activate(ThreadLocalContext.class, RequestScoped.class); + RequestContext requestContext = Beans.getReference(RequestContext.class); + SessionContext sessionContext = Beans.getReference(SessionContext.class); + ViewContext viewContext = Beans.getReference(ViewContext.class); + + requestContext.activate(); + sessionContext.activate(); + viewContext.activate(); } public void removeContexts(@Observes AfterShutdownProccess event) { - ContextManager.deactivate(ThreadLocalContext.class, ViewScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, SessionScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, ConversationScoped.class); - ContextManager.deactivate(ThreadLocalContext.class, RequestScoped.class); + RequestContext requestContext = Beans.getReference(RequestContext.class); + SessionContext sessionContext = Beans.getReference(SessionContext.class); + ViewContext viewContext = Beans.getReference(ViewContext.class); + + requestContext.deactivate(); + sessionContext.deactivate(); + viewContext.deactivate(); } } -- libgit2 0.21.2