<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that 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 this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.seam.faces.context;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.enterprise.context.ContextNotActiveException;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.BeanManager;
import javax.faces.bean.FlashScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.inject.Named;

import org.jboss.seam.faces.util.BeanManagerUtils;
import org.jboss.weld.extensions.beanManager.BeanManagerAccessor;

/**
 * This class provides the lifecycle for the new JSF 2 Flash Context
 * 
 * @author <a href="mailto:<EMAIL>"><NAME>, III</a>
 */
@RequestScoped
public class FlashScopedContext implements Context, PhaseListener, Serializable
{
   private static final long serialVersionUID = -1580689204988513798L;

   private static final String SESSION_KEY_PREFIX = FlashScopedContext.class.getName() + ".context";
   private final static String COMPONENT_MAP_NAME = FlashScopedContext.class.getName() + ".componentInstanceMap";
   private final static String CREATIONAL_MAP_NAME = FlashScopedContext.class.getName() + ".creationalInstanceMap";

   String requestParameterName = "fid";

   FlashContext currentContext = null;

   @Produces
   @Named
   @RequestScoped
   public FlashContext getFlashContext()
   {
      return currentContext;
   }

   private FlashContext getCurrentFlashContext()
   {
      BeanManager manager = BeanManagerAccessor.getManager();
      return BeanManagerUtils.getContextualInstance(manager, FlashContext.class);
   }

   private void assertActive()
   {
      if (!isActive())
      {
         throw new ContextNotActiveException("Seam context with scope annotation @FlashScoped is not active with respect to the current thread");
      }
   }

   /*
    * PhaseListener Methods
    */
   public void beforePhase(final PhaseEvent event)
   {
      if (PhaseId.RESTORE_VIEW.equals(event.getPhaseId()))
      {
         String currentId = getCurrentId();
         if (savedContextExists(currentId))
         {
            FlashContext context = (FlashContext) getSessionMap().get(getSessionKey(currentId));
            currentContext = context;
         }
         else
         {
            FlashContextImpl context = new FlashContextImpl();
            context.setId(getNextFlashId());
            getSessionMap().put(getSessionKey(context.getId()), context);
            currentContext = context;
         }
      }
   }

   private String getNextFlashId()
   {
      String result = null;

      Map<String, Object> sessionMap = getSessionMap();
      int i = 0;
      while (result == null)
      {
         if (!sessionMap.containsKey(getSessionKey(result)))
         {
            result = String.valueOf(i);
         }
      }

      return result;
   }

   private boolean savedContextExists(final String id)
   {
      return getSessionMap().get(getSessionKey(id)) instanceof FlashContext;
   }

   private String getCurrentId()
   {
      Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
      String currentId = requestParameterMap.get(requestParameterName);
      return currentId;
   }

   /**
    * Destroy the current context since Render Response has completed.
    */
   @SuppressWarnings("unchecked")
   public void afterPhase(final PhaseEvent event)
   {
      if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId()))
      {
         getSessionMap().remove(getSessionKey(currentContext.getId()));

         Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
         Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalContextMap();

         if ((componentInstanceMap != null) && (creationalContextMap != null))
         {
            for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet())
            {
               Contextual contextual = componentEntry.getKey();
               Object instance = componentEntry.getValue();
               CreationalContext creational = creationalContextMap.get(contextual);

               contextual.destroy(instance, creational);
            }
         }
      }
   }

   public PhaseId getPhaseId()
   {
      return PhaseId.ANY_PHASE;
   }

   /*
    * Context Methods
    */
   @SuppressWarnings("unchecked")
   public <T> T get(final Contextual<T> component)
   {
      assertActive();
      return (T) getComponentInstanceMap().get(component);
   }

   @SuppressWarnings("unchecked")
   public <T> T get(final Contextual<T> component, final CreationalContext<T> creationalContext)
   {
      assertActive();

      T instance = get(component);

      if (instance == null)<commit_msg>Applied patch for SEAMFACES-42 (NullPointer wrapping External Context)<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that 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 this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.seam.faces.context;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.enterprise.context.ContextNotActiveException;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.BeanManager;
import javax.faces.bean.FlashScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.inject.Named;

import org.jboss.seam.faces.util.BeanManagerUtils;
import org.jboss.weld.extensions.beanManager.BeanManagerAccessor;

/**
 * This class provides the lifecycle for the new JSF 2 Flash Context
 * 
 * @author <a href="mailto:<EMAIL>"><NAME>, III</a>
 */
@RequestScoped
public class FlashScopedContext implements Context, PhaseListener, Serializable
{
   private static final long serialVersionUID = -1580689204988513798L;

   private static final String SESSION_KEY_PREFIX = FlashScopedContext.class.getName() + ".context";
   private final static String COMPONENT_MAP_NAME = FlashScopedContext.class.getName() + ".componentInstanceMap";
   private final static String CREATIONAL_MAP_NAME = FlashScopedContext.class.getName() + ".creationalInstanceMap";

   String requestParameterName = "fid";

   FlashContext currentContext = null;

   @Produces
   @Named
   @RequestScoped
   public FlashContext getFlashContext()
   {
      if (currentContext == null)
      {
         initializeCurrentContext();
      }
      return currentContext;
   }

   private FlashContext getCurrentFlashContext()
   {
      BeanManager manager = BeanManagerAccessor.getManager();
      return BeanManagerUtils.getContextualInstance(manager, FlashContext.class);
   }

   private void assertActive()
   {
      if (!isActive())
      {
         throw new ContextNotActiveException("Seam context with scope annotation @FlashScoped is not active with respect to the current thread");
      }
   }

   private void initializeCurrentContext()
   {
      String currentId = getCurrentId();
      if (savedContextExists(currentId))
      {
         FlashContext context = (FlashContext) getSessionMap().get(getSessionKey(currentId));
         currentContext = context;
      }
      else
      {
         FlashContextImpl context = new FlashContextImpl();
         context.setId(getNextFlashId());
         getSessionMap().put(getSessionKey(context.getId()), context);
         currentContext = context;
      }
   }

   private String getNextFlashId()
   {
      String result = null;

      Map<String, Object> sessionMap = getSessionMap();
      int i = 0;
      while (result == null)
      {
         if (!sessionMap.containsKey(getSessionKey(result)))
         {
            result = String.valueOf(i);
         }
      }

      return result;
   }

   private boolean savedContextExists(final String id)
   {
      return getSessionMap().get(getSessionKey(id)) instanceof FlashContext;
   }

   private String getCurrentId()
   {
      Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
      String currentId = requestParameterMap.get(requestParameterName);
      return currentId;
   }

   /**
    * Destroy the current context since Render Response has completed.
    */
   @SuppressWarnings("unchecked")
   public void afterPhase(final PhaseEvent event)
   {
      if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId()))
      {
         getSessionMap().remove(getSessionKey(currentContext.getId()));

         Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
         Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalContextMap();

         if ((componentInstanceMap != null) && (creationalContextMap != null))
         {
            for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet())
            {
               Contextual contextual = componentEntry.getKey();
               Object instance = componentEntry.getValue();
               CreationalContext creational = creationalContextMap.get(contextual);

               contextual.destroy(instance, creational);
            }
         }
      }
   }

   public void beforePhase(PhaseEvent arg0)
   {
      /* intentionally empty */
   }

   public PhaseId getPhaseId()
   {
      return PhaseId.ANY_PHASE;
   }

   /*
    * Context Methods
    */
   @SuppressWarnings("unchecked")
   public <T> T get(final Contextual<T> component)
   {
      assertActive();
      return (T) getComponentInstanceMap().get(component);
   }

   @SuppressWarnings("unchecked")
   public <T> T get(final Contextual<T> component, final CreationalContext<T> creationalContext)
   {
      assertActive();

      T instance = get(component);

      if (instance == null)
{'fraction_non_alphanumeric': 0.09312067021105204, 'fraction_numerical': 0.006363782825841792, 'mean_word_length': 3.407170749023784, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4906730', 'n_tokens_mistral': 3388, 'n_tokens_neox': 3267, 'n_words': 906}