You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by mf...@apache.org on 2011/05/26 23:29:20 UTC

svn commit: r1128097 [3/5] - in /myfaces/portlet-bridge/core/branches/refactored_3.0.x: controller-api/src/main/java/org/apache/myfaces/portlet/faces/bridge/ impl/src/main/java/org/apache/myfaces/portlet/faces/application/ impl/src/main/java/org/apache...

Added: myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/config/BridgeConfigImpl.java
URL: http://svn.apache.org/viewvc/myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/config/BridgeConfigImpl.java?rev=1128097&view=auto
==============================================================================
--- myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/config/BridgeConfigImpl.java (added)
+++ myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/config/BridgeConfigImpl.java Thu May 26 21:29:19 2011
@@ -0,0 +1,571 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
+ * law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
+ * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
+ * for the specific language governing permissions and limitations under the License.
+ */
+
+
+package org.apache.myfaces.portlet.faces.bridge.config;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import java.util.Map;
+
+import java.util.Vector;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.faces.FactoryFinder;
+import javax.faces.application.ApplicationFactory;
+import javax.faces.lifecycle.LifecycleFactory;
+
+import javax.portlet.PortletConfig;
+import javax.portlet.faces.Bridge;
+import javax.portlet.faces.BridgeEventHandler;
+import javax.portlet.faces.BridgePublicRenderParameterHandler;
+import javax.portlet.faces.BridgeWriteBehindResponse;
+
+import org.apache.myfaces.portlet.faces.bridge.BridgeConfig;
+import org.apache.myfaces.portlet.faces.bridge.BridgeLogger;
+import org.apache.myfaces.portlet.faces.bridge.logger.BridgeLoggerImpl;
+
+/**
+ * The <CODE>BridgeConfig</CODE> represents the set of values a portlet can configure for
+ * a given bridge instance. Currently, by spec, the portlet passes most of this
+ * configuration to the bridge using <CODE>PortletContext</CODE> attributes.  The bridge,
+ * in its <code>init()</code> method, is responsible for packaging all this configuration
+ * information into a BridgeConfig.  It must then only reference such configuation information
+ * from this object.  I.e. it no longer makes reference to the <CODE>PortletContext</CODE> attributes.
+ * This allows replacable pieces of the bridge implementation to always have a consistent
+ * object to retrieve configuration information from.
+ */
+
+public class BridgeConfigImpl implements BridgeConfig
+{
+  public static final String JSF_TARGET_VIEWID_RENDER_PARAMETER = "__jpfbJSFTARGET";
+  
+  private PortletConfig mPortletConfig;
+  private ConcurrentHashMap<String, String> mDefaultMappings;
+  private Vector<String> mFacesServletMappings;
+  private String mViewIdParameterName = JSF_TARGET_VIEWID_RENDER_PARAMETER;
+  private BridgeLogger mLogger;
+  private BridgeEventHandler mEventHandler;
+  private BridgePublicRenderParameterHandler mPRPHandler;
+  private boolean mPreserveActionParams = false;
+  private Vector<String> mExcludedRequestAttributes;
+  private ConcurrentHashMap<String, String> mPRPMappings;
+  private Class<? extends BridgeWriteBehindResponse> mWriteBehindRenderResponseWrapperClass;
+  private Class<? extends BridgeWriteBehindResponse> mWriteBehindResourceResponseWrapperClass;
+  private Vector<String> mFacesSuffixes;
+  private String mLifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
+  private ConcurrentHashMap<String, Object> mAttributes;
+
+  
+  public BridgeConfigImpl() 
+  {
+  }
+  
+  /**
+   * Sets the <code>PortletConfig</code> object of the portlet that is utilizing this bridge.
+   * 
+   * @param config
+   *          the config object.
+   */
+  public void setPortletConfig(PortletConfig config)
+  {
+    mPortletConfig = config;
+  }
+  
+  /**
+   * Gets the <code>PortletConfig</code> object of the portlet that is utilizing this bridge.
+   * 
+   * @return 
+   *          the config object.
+   */
+  public PortletConfig getPortletConfig()
+  {
+    return mPortletConfig;
+  }
+  
+
+  /**
+   * Sets the <code>Map</code> describing the mapping between each supported <code>PortletMode</code> 
+   * and its default Faces View (id).  When the bridge receives a request that isn't directly encoded
+   * with the target Faces view (such as the initial render request), the bridge relies on these
+   * default mappings to determine the target. There is one mapping per <code>PortletMode</code>
+   * supported by the portlet (and handledby Faces).  The key to the each entry in the map is the
+   * <code>String</code> name of the associated <code>PortletMode</code>;
+   * 
+   * @param defaultMappings between each supported <code>PortletMode</code> and the default
+   *          Faces target.
+   */  
+  public void setDefaultViewMappings(Map<String, String> defaultMappings)
+  {
+    mDefaultMappings = null;
+    if (defaultMappings != null)
+    {
+      // Copy the map
+      mDefaultMappings = new ConcurrentHashMap<String, String>(defaultMappings);
+    }
+  }
+
+
+  /**
+   * Gets the <code>Map</code> describing the mapping between each supported <code>PortletMode</code> 
+   * and its default Faces View (id).  When the bridge receives a request that isn't directly encoded
+   * with the target Faces view (such as the initial render request), the bridge relies on these
+   * default mappings to determine the target. There is one mapping per <code>PortletMode</code>
+   * supported by the portlet (and handledby Faces).  The key to the each entry in the map is the
+   * <code>String</code> name of the associated <code>PortletMode</code>;
+   * 
+   * @return defaultMappings between each supported <code>PortletMode</code> and the default
+   *          Faces target.
+   */  
+  public Map<String, String> getDefaultViewMappings()
+  {
+    if (mDefaultMappings == null)
+    {
+      mDefaultMappings = new ConcurrentHashMap<String, String>();
+    }
+    return mDefaultMappings;
+  }
+  
+  
+  
+  /**
+   * Sets the <code>List</code> of <code>Servlet</code> mappings to the Faces servlet (information taken
+   * from web.xml).  The bridge uses these mappings to both detect whether a given URL is handled
+   * by Faces or not and to deal with mapping between viewIds and their underlying resources.
+   * 
+   * @param mappings
+   *          the various servlet mappings for the <code>FacesServlet</code>.
+   */
+  public void setFacesServletMappings(List<String> mappings)
+  {
+    mFacesServletMappings = null;
+    
+    if (mappings != null)
+    {
+      // Copy the list
+      mFacesServletMappings = new Vector<String>(mappings);
+    }
+  }
+
+
+  /**
+   * Gets the <code>List</code> of <code>Servlet</code> mappings to the Faces servlet (information taken
+   * from web.xml).  The bridge uses these mappings to both detect whether a given URL is handled
+   * by Faces or not and to deal with mapping between viewIds and their underlying resources.
+   * 
+   * @return 
+   *          the various servlet mappings for the <code>FacesServlet</code>.
+   */  
+  public List<String> getFacesServletMappings()
+  {
+    if (mFacesServletMappings == null)
+    {
+      mFacesServletMappings = new Vector<String>();
+    }
+    return mFacesServletMappings;
+  }
+  
+  
+  /**
+   * Sets the name of the parameter used by the bridge to encode the target viewId.
+   * 
+   * @param name
+   *          parameter name that holds the bridge encoded target viewId.
+   */
+  public void setViewIdRenderParameterName(String name)
+  {
+    mViewIdParameterName = name;
+  }
+  
+  
+  /**
+   * Gets the name of the parameter used by the bridge to encode the target viewId.
+   * 
+   * @return
+   *          parameter name that holds the bridge encoded target viewId.
+   */  
+  public String getViewIdRenderParameterName()
+  {
+    return mViewIdParameterName;
+  }
+   
+  
+  /**
+   * Sets the <code>BridgeLogger</code> that the bridge uses to log diagnostic and warning messages.
+   * 
+   * @param logger
+   *          <code>BridgeLogger</code>.
+   */  
+  public void setLogger(BridgeLogger logger)
+  {
+    mLogger = logger;
+  }
+  
+  
+  /**
+   * Gets the <code>BridgeLogger</code> that the bridge uses to log diagnostic and warning messages.
+   * 
+   * @return
+   *          <code>BridgeLogger</code>.
+   */
+  public BridgeLogger getLogger()
+  {
+    if (mLogger == null)
+    {
+      // TODO: use factory mechanism to create the logger
+      setLogger(new BridgeLoggerImpl(this));
+    }
+    return mLogger;
+  }
+  
+
+  /**
+   * Sets the <code>BridgeEventHandler</code> that the bridge calls to handle any portlet event it processes.
+   * 
+   * @param handler
+   */    
+  public void setEventHandler(BridgeEventHandler handler)
+  {
+    mEventHandler = handler;
+  }
+ 
+ 
+  /**
+   * Gets the <code>BridgeEventHandler</code> that the bridge calls to handle any portlet event it processes.
+   * 
+   * @return the <code>BridgeEventHandler</code>
+   */     
+  public BridgeEventHandler getEventHandler()
+  {
+    return mEventHandler;
+  }
+  
+ 
+  /**
+   * Sets the <code>BridgePublicRenderParameterHandler</code> that the bridge calls to handle post processing recalculations
+   * following the bridge pushing incoming portlet public render parameters to their models.
+   * 
+   * @param handler
+   */  
+  public void setPublicRenderParameterHandler(BridgePublicRenderParameterHandler handler)
+  {
+    mPRPHandler = handler;
+  }
+  
+  
+  /**
+   * Gets the <code>BridgePublicRenderParameterHandler</code> that the bridge calls to handle post processing recalculations
+   * following the bridge pushing incoming portlet public render parameters to their models.
+   * 
+   * @return <code>BridgePublicRenderParameterHandler</code>
+   */ 
+  public BridgePublicRenderParameterHandler getPublicRenderParameterHandler()
+  {
+    return mPRPHandler;
+  }
+  
+  
+  
+  /**
+   * Sets whether or not the bridge should carry action parameters forward into subsequent renders.
+   * 
+   * @param preserve <code>true</code> indicates the action parameters are preserved.  
+   *                 <code>false</code> indicates they are not.
+   */
+  public void setPreserveActionParameters(boolean preserve)
+  {
+    mPreserveActionParams = preserve;
+  }
+  
+  /**
+   * Sets whether or not the bridge should carry action parameters forward into subsequent renders.
+   * 
+   * @param preserve <code>Boolean.TRUE</code> indicates the action parameters are preserved.  
+   *                 <code>Boolean.FALSE</code> indicates they are not.
+   */
+  public void setPreserveActionParameters(Boolean preserve)
+  {
+    mPreserveActionParams = false; // ensures its always reset
+    if (preserve != null)
+    {
+      mPreserveActionParams = preserve.booleanValue();
+    }
+  }
+  
+  /**
+   * Gets whether or not the bridge should carry action parameters forward into subsequent renders.
+   * If not previously set, it returns <code>false</code>.
+   * 
+   * @return <code>true</code> indicates the action parameters are preserved.  
+   *                 <code>false</code> indicates they are not.
+   */
+  public boolean hasPreserveActionParameters()
+  {
+    return mPreserveActionParams;
+  }
+  
+  
+  /**
+   * Sets the <code>List</code> of attributes to be excluded from the bridge's request scope.
+   * This list includes both the attributes configured in the portlet.xml (portlet init parameter)
+   * as well as any configured in any of this web application's faces-config.xml(s).  It doesn't
+   * include any of the predefined attributes as defined by the specification.  A list entry is
+   * either the fully qualified name of the attribute that should be excluded or a wildcard terminated
+   * (package) path.  In the latter case, all attributes whose names reside in this package
+   * (non-recusive) are excluded.
+   * 
+   * @param excludedAttributes <code>List</code> of request attribute names that are to be
+   * excluded from the bridge's managed request scope.
+   */
+  public void setExcludedRequestAttributes(List<String> excludedAttributes)
+  {
+    mExcludedRequestAttributes = null;
+    
+    if (excludedAttributes != null)
+    {
+      // Copy the list
+      mExcludedRequestAttributes = new Vector<String>(excludedAttributes);
+    }
+  }
+  
+  
+  /**
+   * Gets the <code>List</code> of attributes to be excluded from the bridge's request scope.
+   * This list includes both the attributes configured in the portlet.xml (portlet init parameter)
+   * as well as any configured in any of this web application's faces-config.xml(s).  It doesn't
+   * include any of the predefined attributes as defined by the specification.  A list entry is
+   * either the fully qualified name of the attribute that should be excluded or a wildcard terminated
+   * (package) path.  In the latter case, all attributes whose names reside in this package
+   * (non-recusive) are excluded.
+   * 
+   * @return <code>List</code> of request attribute names that are to be
+   * excluded from the bridge's managed request scope.
+   */
+  public List<String> getExcludedRequestAttributes()
+  {
+    if (mExcludedRequestAttributes == null)
+    {
+      mExcludedRequestAttributes = new Vector<String>(3);
+    }
+    return mExcludedRequestAttributes;
+  }
+  
+ 
+  /**
+   * Sets the <code>Map</code> containing the mappings between portlet public render parameter names
+   * and a corresponding Faces EL statement.  The Faces EL is expected to resolve to
+   * a managed bean property allowing the bridge to push/pull public render parameter 
+   * values directly from managed bean properties.
+   * This configuration information is extracted from the faces-config.xml(s).
+   * 
+   * 
+   * @param prpMappings <code>Map<String, String></code>.  The key is the name of the 
+   * portlet public render parameter for this mapping.  If prefixed with
+   * portletName: the mapping only pertains to the specifically named portlet, otherwise
+   * the mapping pertains to all portlets in the web application.  The value is a
+   * Faces EL that resolves to a managed bean property.
+   */
+  
+  public void setPublicRenderParameterMappings(Map<String, String> prpMappings)
+  {
+    mPRPMappings = null;
+    
+    if (prpMappings != null)
+    {
+      // Copy Map
+      mPRPMappings = new ConcurrentHashMap<String, String>(prpMappings);
+    }
+  }
+  
+  
+  /**
+   * Gets the <code>Map</code> containing the mappings between portlet public render parameter names
+   * and a corresponding Faces EL statement.  The Faces EL is expected to resolve to
+   * a managed bean property allowing the bridge to push/pull public render parameter 
+   * values directly from managed bean properties.
+   * This configuration information is extracted from the faces-config.xml(s).
+   * 
+   * 
+   * @return <code>Map<String, String></code>.  The key is the name of the 
+   * portlet public render parameter for this mapping.  If prefixed with
+   * portletName: the mapping only pertains to the specifically named portlet, otherwise
+   * the mapping pertains to all portlets in the web application.  The value is a
+   * Faces EL that resolves to a managed bean property.
+   */
+  public Map<String, String> getPublicRenderParameterMappings()
+  {
+    if (mPRPMappings == null)
+    {
+      mPRPMappings = new ConcurrentHashMap<String, String>();
+    }
+    return mPRPMappings;
+  }
+  
+  /**
+   *
+   * @return <code>true</code> if the config has public render parameter mappings.
+   */
+  public boolean hasPublicRenderParameterMappings()
+  {
+    return mPRPMappings != null && !mPRPMappings.isEmpty();
+  }
+  
+  
+  /**
+   * Sets the <code>Class</code> that the bridge uses to wrap the response when 
+   * rendering a <code>JSP</code> to implement the Faces implementation specific
+   * support for handling interleaved response writing.
+   * 
+   * @param wbrClass
+   *          <code>Class</code> that implements the <code>BridgeWritebehindResponse</code> interface
+   *          and is a proper portlet render response wrapper.
+   */
+  public void setWriteBehindRenderResponseWrapper (Class<? extends BridgeWriteBehindResponse> renderResponseWrapper)
+  {
+    mWriteBehindRenderResponseWrapperClass = renderResponseWrapper;
+  }
+  
+  
+  /**
+   * Gets the <code>Class</code> that the bridge uses to wrap the response when 
+   * rendering a <code>JSP</code> to implement the Faces implementation specific
+   * support for handling interleaved response writing.
+   * 
+   * @return 
+   *          <code>Class</code> that implements the <code>BridgeWritebehindResponse</code> interface
+   *          and is a proper portlet render response wrapper.
+   */
+  public Class<? extends BridgeWriteBehindResponse> getWriteBehindRenderResponseWrapper()
+  {
+    return mWriteBehindRenderResponseWrapperClass;
+  }
+  
+  
+  /**
+   * Sets the <code>Class</code> that the bridge uses to wrap the response when 
+   * rendering a <code>JSP</code> resource to implement the Faces implementation specific
+   * support for handling interleaved response writing.
+   * 
+   * @param wbrClass
+   *          <code>Class</code> that implements the <code>BridgeWritebehindResponse</code> interface
+   *          and is a proper portlet resource response wrapper.
+   */
+  public void setWriteBehindResourceResponseWrapper (Class<? extends BridgeWriteBehindResponse> resourceResponseWrapper)
+  {
+    mWriteBehindResourceResponseWrapperClass = resourceResponseWrapper;
+  }
+  
+  
+  /**
+   * Gets the <code>Class</code> that the bridge uses to wrap the response when 
+   * rendering a <code>JSP</code> resource to implement the Faces implementation specific
+   * support for handling interleaved response writing.
+   * 
+   * @return 
+   *          <code>Class</code> that implements the <code>BridgeWritebehindResponse</code> interface
+   *          and is a proper portlet resource response wrapper.
+   */
+  public Class<? extends BridgeWriteBehindResponse> getWriteBehindResourceResponseWrapper()
+  {
+    return mWriteBehindResourceResponseWrapperClass;
+  }
+  
+  
+  /**
+   * Sets the <code>List<String></code> of the possible suffixes that
+   * Faces recognizes as Faces processed targets.  Since JSF 2.0 the default suffix
+   * mapping Faces recognizes is a list rather than a single value.  This information
+   * comes from the web.xml and is used to help the bridge map between viewIds and
+   * their underlying resources.
+   * 
+   * @param suffixes
+   *          <code>List</code> of the suffixes Faces recognizes as Faces targets.
+   */
+  public void setFacesSuffixes(List<String> suffixes)
+  {
+    mFacesSuffixes = null;
+    
+    if (suffixes != null)
+    {
+      mFacesSuffixes = new Vector<String>(suffixes);
+    }
+  }
+  
+  
+  /**
+   * gets the <code>List<String></code> of the possible suffixes that
+   * Faces recognizes as Faces processed targets.  Since JSF 2.0 the default suffix
+   * mapping Faces recognizes is a list rather than a single value.  This information
+   * comes from the web.xml and is used to help the bridge map between viewIds and
+   * their underlying resources.
+   * 
+   * @return  <code>List</code> of the suffixes Faces recognizes as Faces targets.
+   */  
+  public List<String> getFacesSuffixes()
+  {
+    if (mFacesSuffixes == null)
+    {
+      mFacesSuffixes = new Vector<String>();
+    }
+    return mFacesSuffixes;
+  }
+  
+  /**
+   * Sets the id of the lifecycle the portlet should use for executing Faces requests.
+   * @param id
+   */
+  public void setLifecyleId(String id)
+  {
+    mLifecycleId = id;
+  }
+  
+  /**
+   * 
+   * @return the lifecycle id the portlet should use for executing Faces requests.  If not previously set the value 
+   * <code>LifecycleFactory.DEFAULT_LIFECYCLE</code> is returned.
+   */
+  public String getLifecycleId()
+  {
+    return mLifecycleId;
+  }
+  
+  
+  /**
+   * This <code>Map</code> is a place to put extra (implementation specific) bridge state
+   * or anything else whose lifetime matches this scope.
+   * @return a mutable <code>Map<String, Object></code> of bridge context scoped attributes
+   */
+  public Map<String, Object> getAttributes()
+  {
+    if (mAttributes == null)
+    {
+      mAttributes = new ConcurrentHashMap<String, Object>(10);
+    }
+    return mAttributes;
+  }  
+  
+  /**
+   * By spec, the portlet can configure the specific renderkit it uses vs others in the app as a Portlet
+   * init parameter.  This allows differeing portlets in the app to use different render kits.
+   * 
+   * @return configured renderkit id for this portlet or null if none is configured.
+   */
+  public String getDefaultRenderKitId()
+  {
+    return (String) mPortletConfig.getPortletContext().getAttribute(Bridge.BRIDGE_PACKAGE_PREFIX + mPortletConfig.getPortletName() + 
+                                              "." + Bridge.DEFAULT_RENDERKIT_ID);
+  }
+
+  
+  
+}
\ No newline at end of file

Added: myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/BridgeContextImpl.java
URL: http://svn.apache.org/viewvc/myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/BridgeContextImpl.java?rev=1128097&view=auto
==============================================================================
--- myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/BridgeContextImpl.java (added)
+++ myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/BridgeContextImpl.java Thu May 26 21:29:19 2011
@@ -0,0 +1,692 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
+ * law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
+ * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
+ * for the specific language governing permissions and limitations under the License.
+ */
+
+
+package org.apache.myfaces.portlet.faces.bridge.context;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import java.util.Map;
+
+import java.util.Set;
+
+import javax.el.ELContext;
+import javax.el.ELContextEvent;
+import javax.el.ELContextListener;
+
+import javax.faces.FactoryFinder;
+import javax.faces.application.ApplicationFactory;
+
+import javax.faces.context.FacesContext;
+
+import javax.faces.render.ResponseStateManager;
+
+import javax.portlet.PortletContext;
+import javax.portlet.PortletRequest;
+import javax.portlet.PortletResponse;
+import javax.portlet.faces.Bridge;
+
+import org.apache.myfaces.portlet.faces.bridge.BridgeConfig;
+import org.apache.myfaces.portlet.faces.bridge.BridgeContext;
+import org.apache.myfaces.portlet.faces.el.PortletELContextImpl;
+import org.apache.myfaces.portlet.faces.util.QueryString;
+
+
+/**
+ * The <CODE>BridgeContext</CODE> contains the runtime specific state the bridge
+ * makes public so its various independent pieces can work together to properly
+ * operate.  Simplistically, the bridge is a controller and a set of Faces
+ * extensions that work together execute Faces requests in a portlet container.
+ * By encapsulating state that is shared between these pieces, an extensible,
+ * pluggable bridge is supported as bridge implementors can now extend a base
+ * implementation by extending or overriding any of the Faces extensions (and
+ * other hook points) required to add their specific behaviors.<p>
+ * A new <code>BridgeContext</code> is created in each bridge request
+ * <code>doFacesRequest()</code>.  After the bridge controller has initialized
+ * the context the <code>SystemEvent BridgeContextInitializedEvent</code> is dispatched
+ * to any registered listeners for further transformation.  Once the bridge has acquired
+ * the <code>FacesContext</code>, the <code>BridgeContext</code> is added to the
+ * <code>FacesContext</code> scope making it freely available from anywhere within
+ * Faces during that request.
+ */
+public class BridgeContextImpl extends BridgeContext implements ELContextListener 
+{
+  
+  private final String BRIDGE_CONTEXT_HAS_INITED_VIEW_HISTORY = "org.apache.myfaces.portlet.faces.bridge.context.hasInitializedViewHistory";
+  
+  private PortletContext mPortletContext;
+  private PortletRequest mPortletRequest;
+  private PortletResponse mPortletResponse;
+  private Bridge.PortletPhase mPortletPhase;
+  private BridgeConfig mBridgeConfig;
+  private HashMap<String, Object> mAttributes;
+  private boolean mPreserveBridgeRequestScope = true;
+  private String mSavedViewStateParam;
+  private String mNavigationQueryString;
+  private String mRenderRedirectQueryString;
+  private boolean mHasRenderRedirect = false;
+  private boolean mRenderRedirectOcurredAfterDispatch = false;
+  private ArrayList<String> mPreExistingAttributeNames;
+  private HashMap<String, String[]> mPreservedActionParams;
+    
+  public BridgeContextImpl()
+  {
+    // Add self as ELContextListener to the Faces App so we can add the
+    // portletConfig to any newly created contexts.    
+    ((ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY))
+        .getApplication().addELContextListener(this);
+  }
+  
+  /**
+   * Called at the end of bridge request processing.  It releases associated
+   * state.
+   */
+  public void release()
+  {
+    // Add self as ELContextListener to the Faces App so we can add the
+    // portletConfig to any newly created contexts.    
+    ((ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY))
+        .getApplication().removeELContextListener(this);
+  }
+  
+  
+  /**
+   * Sets the <code>PortletContext</code> of the portlet invoking this bridge.
+   * @param context
+   */
+  public void setPortletContext(PortletContext context)
+  {
+    mPortletContext = context;
+  }
+  
+  
+  /**
+   *
+   * @return the <code>PortletContext</code> of the portlet invoking this bridge.
+   */
+  public PortletContext getPortletContext()
+  {
+    return mPortletContext;
+  }
+  
+  
+  /**
+   * Sets the <code>PortletRequest</code> that invoked the bridge.
+   * @param request
+   */
+  public void setPortletRequest(PortletRequest request)
+  {
+    mPortletRequest = request;
+    
+    // Can't Initialize the view history until we have both the config and request objects
+    if (getBridgeConfig() != null)
+    {
+      initViewHistoryWithDefaults();
+    }
+  }
+  
+  
+  /**
+   * 
+   * @return the <code>PortletRequest</code> that invoked the bridge.
+   */
+  public PortletRequest getPortletRequest()
+  {
+    return mPortletRequest;
+  }
+  
+  
+  /**
+   * Sets the <code>PortletResponse</code> that invoked the bridge.
+   * @param response
+   */
+  public void setPortletResponse(PortletResponse response)
+  {
+    mPortletResponse = response;
+  }
+  
+  /**
+   * 
+   * @return the <code>PortletResponse</code> that invoked the bridge.
+   */
+  public PortletResponse getPortletResponse()
+  {
+    return mPortletResponse;
+  }
+
+  /**
+   * Sets the request phase govering this context.  Used to both detect
+   * whether one is executing in a portlet request without referencing
+   * potential unbound classes as well as to determine the type of request
+   * and response one is dealing with as there are distinct portlet request
+   * and response objects per portlet lifecycle phase.<p>
+   * Note: as per specification, its more typical for the Faces developer to
+   * rely on the request attribute containing this same information.  Its 
+   * included in the BridgeContext primarily for bridge (extension) implementors.
+   * 
+   * @param phase
+   */
+  public void setPortletRequestPhase(Bridge.PortletPhase phase)
+  {
+    mPortletPhase = phase;
+  }
+  
+  
+  /**
+   * Gets the request phase govering this context.  Used to both detect
+   * whether one is executing in a portlet request without referencing
+   * potential unbound classes as well as to determine the type of request
+   * and response one is dealing with as there are distinct portlet request
+   * and response objects per portlet lifecycle phase.<p>
+   * Note: as per specification, its more typical for the Faces developer to
+   * rely on the request attribute containing this same information.  Its 
+   * included in the BridgeContext primarily for bridge (extension) implementors.
+   * 
+   * @return the current portlet request lifcycle phase we are executing in.
+   */
+  public Bridge.PortletPhase getPortletRequestPhase()
+  {
+    return mPortletPhase;
+  }
+  
+  
+  /**
+   * Sets the <code>BridgeConfig</code> that corresponds to this instance.
+   * @param config
+   */
+  public void setBridgeConfig(BridgeConfig config)
+  {
+    mBridgeConfig = config;
+
+    // Can't init the viewHistory until we have both the request and the config objects
+    if (getPortletRequest() != null)
+    {
+      initViewHistoryWithDefaults();
+    }
+  }
+  
+  
+  /**
+   * 
+   * @return the <code>BridgeConfig</code> that corresponds to this instance.
+   */
+  public BridgeConfig getBridgeConfig()
+  {
+    return mBridgeConfig;
+  }
+  
+  
+  /**
+   * This <code>Map</code> is a place to put extra (implementation specific) bridge state
+   * or anything else whose lifetime matches this scope.
+   * @return a mutable <code>Map<String, Object></code> of bridge context scoped attributes
+   */
+  public Map<String, Object> getAttributes()
+  {
+    if (mAttributes == null)
+    {
+      mAttributes = new HashMap<String, Object>(10);
+    }
+    return mAttributes;
+  }
+  
+  
+  // Default = true;  always parts of the bridge read/write whether bridge request scope is preserved at the end of this request
+  /**
+   * Indicates whether the controller should preserve the bridge request scope.  By specification
+   * there are a variety of reasons why the bridge shouldn't preserve a request scope.  Sometimes
+   * this is determined in one of the bridge's Faces extensions that is separate from the controller.
+   * The dectector used this method to convery to the controller its behavior when its done with the
+   * request and considers whether to save the bridge request scope or not.  <code>true</code> means the
+   * request scope should be preserved.  <code>false</code> means the request scope should not be preserved.
+   * The default is <code>true</code>
+   * @param preserve
+   */
+  public void setPreserveBridgeRequestScope(boolean preserve)
+  {
+    mPreserveBridgeRequestScope = preserve;
+  }
+  
+  
+  /**
+   * @return the <code>boolean</code> indicating whether the controller should preserve the bridge request scope or not.
+   *         <code>true</code> means the request scope should be preserved.  <code>false</code> means
+   *         the request scope should not be preserved. The default is <code>true</code>
+   */
+  public boolean getPreserveBridgeRequestScope()
+  {
+    return mPreserveBridgeRequestScope;
+  }
+  
+ 
+  /**
+   * Faces stores the current view state in a hidden field in the response.  When this is
+   * resupplied as part of the POSTBACK, Faces is able to restore the view and process the
+   * action.  In the portlet model, however, not every (following) request is a POSTBACK.  The
+   * portal can ask the portlet to redisplay itself at any time merely because something has
+   * else has occurred on the page (outside the portlet) that causes the portal to rerender the
+   * entire page.  As this isn't a POSTBACK the view state hidden field isn't supplied, yet Faces 
+   * still needs to restore the view from this state if its to properly re-render.  To support this
+   * bridge must capture the value of this hidden field and manage it in its state (often the 
+   * bridge request scope).  This capture involves using a Faces extension (<code>StateManager</code>)
+   * to extract the parameter value and the controller to manage the state.  The value is conveyed
+   * between these two subsystems through here.  This method sets the captured view state parameter
+   * value for later retrieval.
+   * @param savedViewStateParam
+   */
+  // Allows a StateManager to communicate the saved ViewState to the controller -- so controller
+  // can retain for reference on portlet redisplay
+  public void setSavedViewStateParam(String savedViewStateParam)
+  {
+    mSavedViewStateParam = savedViewStateParam;
+  }
+  
+  /**
+   * Faces stores the current view state in a hidden field in the response.  When this is
+   * resupplied as part of the POSTBACK, Faces is able to restore the view and process the
+   * action.  In the portlet model, however, not every (following) request is a POSTBACK.  The
+   * portal can ask the portlet to redisplay itself at any time merely because something has
+   * else has occurred on the page (outside the portlet) that causes the portal to rerender the
+   * entire page.  As this isn't a POSTBACK the view state hidden field isn't supplied, yet Faces 
+   * still needs to restore the view from this state if its to properly re-render.  To support this
+   * bridge must capture the value of this hidden field and manage it in its state (often the 
+   * bridge request scope).  This capture involves using a Faces extension (<code>StateManager</code>)
+   * to extract the parameter value and the controller to manage the state.  The value is conveyed
+   * between these two subsystems through here.
+   * @return  the captured view state parameter.
+   */
+  public String getSavedViewStateParam()
+  {
+    return mSavedViewStateParam;
+  }
+  
+  /**
+   * The bridge allows viewIds in the faces-config.xml to contain queryStrings.  
+   * As the <code>NavigationHandler</code> resolves such navigation and create the
+   * asscoiated view and Faces itself doesn't expect these query strings, the bridge
+   * needs to extract this query string and stash its value for later retrieval/use by 
+   * the controller which encodes these extra parameters as part of its action response.
+   * @param queryString query string portion of a viewId
+   */
+  public void setNavigationQueryString(String queryString)
+  {
+    mNavigationQueryString = queryString;
+  }
+  
+  
+  /**
+   * The bridge allows viewIds in the faces-config.xml to contain queryStrings.  
+   * As the <code>NavigationHandler</code> resolves such navigation and create the
+   * asscoiated view and Faces itself doesn't expect these query strings, the bridge
+   * needs to extract this query string and stash its value for later retrieval/use by 
+   * the controller which encodes these extra parameters as part of its action response.
+   * 
+   * @return the queryString portion associated with the viewId that created the current <code>UIViewRoot</code>
+   */
+  public String getNavigationalQueryString()
+  {
+    return mNavigationQueryString;
+  }
+  
+  /**
+   * The bridge is required to support redirects to other Faces views during render.  As the
+   * portlet model doesn't support redirects, the bridge controller must simulate the redirect 
+   * by unwinding the current lifecycle execution and restarting a new lifecycle execution
+   * based on the new target.  In addition any additional query string parameters must be
+   * represented in the request when this lifecycle is rerun.<p>
+   * Such redirects are detected in <code>ExternalContext.redirect()</code> but implemented by the
+   * controller.  This sets the query string portion of the redirect url (exclusive of the ?) so 
+   * its available to the controller in handling the render redirect.  This method automatically
+   * calls <code>setRenderRedirect(true);</code> to flag that a renderRedirect has been detected.
+   * @param queryString
+   */
+  public void setRenderRedirectQueryString(String queryString)
+  {
+    mRenderRedirectQueryString = queryString;
+  }
+  
+  
+  /**
+   * The bridge is required to support redirects to other Faces views during render.  As the
+   * portlet model doesn't support redirects, the bridge controller must simulate the redirect 
+   * by unwinding the current lifecycle execution and restarting a new lifecycle execution
+   * based on the new target.  In addition any additional query string parameters must be
+   * represented in the request when this lifecycle is rerun.<p>
+   * Such redirects are detected in <code>ExternalContext.redirect()</code> but implemented by the
+   * controller.
+   * 
+   * @return prevously set query string (exclusive of the ?) portion of the render redirect url
+   */
+  public String getRenderRedirectQueryString()
+  {
+    return mRenderRedirectQueryString;
+  }
+  
+
+  /**
+   * Sets whether a render redirect has occurred in this request.  Generally this is set
+   * automatically by <code>setRenderRedirectQueryString</code>.
+   * 
+   * @param redirect
+   */
+  public void setRenderRedirect(boolean redirect)
+  {
+    mHasRenderRedirect = redirect;
+  }
+  
+  
+  /**
+   * 
+   * @return indication of whether a render redirect has occured.  <code>true</code>
+   *         if there has been one in this request.  Default is <code>false</code>.
+   */
+  public boolean hasRenderRedirect()
+  {
+    return mHasRenderRedirect;
+  }
+  
+ 
+  /**
+   * Set if the renderRedirect occurred after the (JSP) dispatch.  Needed because 
+   * <code>dispatch.forward()</code> can't be called twice in the same request.
+   * Setting this will allow the bridge to know to use <code>dispatch.include()</code> for
+   * rendering the "redirected"  view.
+   * @param afterDispatch
+   */
+  public void setRenderRedirectAfterDispatch(boolean afterDispatch)
+  {
+    if (afterDispatch)
+    {
+      setRenderRedirect(afterDispatch);
+    }
+    mRenderRedirectOcurredAfterDispatch = afterDispatch;
+  }
+  
+  
+  /**
+   * 
+   * @return indication of whether the renderRedirect occurred before or after
+   *         the dispatch.  <code>true</code> indicates the redirect ocurred
+   *         after the dispatch.  <code>false</code> by default.
+   */
+  public boolean hasRenderRedirectAfterDispatch()
+  {
+    return mRenderRedirectOcurredAfterDispatch;
+  }
+  
+  // Holds a List of attr names that exist prior to acquriing Faces artifacts -- used
+  // to properly clean things up post Lifecycle and in support of renderredirects
+  
+  /**
+   * Sets the names of the attributes which existed before the <code>FacesContext</code>
+   * is acquired.  Used for attribute exclusion, request resetting before a render 
+   * redirect, as well as allowing the FacesContext to release request attrs during
+   * its release.
+   * @param names list of attribute names that exist in the request scope before
+   *        acquiring the <code>FacesContext</code>
+   */
+  public void setPreFacesRequestAttrNames(List<String> names)
+  {
+    mPreExistingAttributeNames = null;
+    if (names != null)
+    {
+      mPreExistingAttributeNames = new ArrayList<String>(names);
+    }
+  }
+  
+  
+  /**
+   * 
+   * @return the names of the request attributes that existed before the
+   *         <code>FacesContext</code> was acquired.
+   */
+  public List<String> getPreFacesRequestAttrNames()
+  {
+    return mPreExistingAttributeNames;
+  }
+  
+  // Set by the controller to communicate which parameters are part of the preserved ActionParameters
+  // so the encodeActionURL can excldue them when encoding a self-referencing portlet: url -- i.e
+  // one that is supposed to be a redisplay preserving the current state.
+  
+  /**
+   * <code>Map</code> of the action parameters that have been preserved for this
+   * render request.  Set by the controller when processing a render so
+   * the <code>ExternalContext.encodeActionURL()</code> can exclude them from its
+   * encoding of a self-referencing portlet: url.  I.e. one that is supposed to redisplay
+   * preserving the existing state.
+   * 
+   * @param actionParamMap <code>Map</code> of the action parameters in this render request.
+   */
+  public void setPreservedActionParams(Map<String, String[]> actionParamMap)
+  {
+    mPreservedActionParams = null;
+      
+    if (actionParamMap != null)
+    {
+      mPreservedActionParams = new HashMap<String, String[]>(actionParamMap);
+    }
+  }
+  
+  /**
+   * @return previously set <code>Map</code> of the action parameters in this render request.
+   */
+  public Map<String, String[]> getPreservedActionParams()
+  {
+    return mPreservedActionParams;
+  }
+  
+  
+  /**
+   * Bridge maintains in the session the last viewId accessed in each mode.  This allows
+   * developers to use EL access to get the viewId (with appropriate QS) to navigate back
+   * to the view that was left when a new mode was entered.  Key in the session is:
+   * javax.portlet.faces.viewIdHistory.<i>modeName</i>.  value is the corresponding viewId
+   * with an encoded QS containing the pertinent state (scope id, etc) to return you to the 
+   * state you left.  Prior to the first request the bridge sets up a default history by adding one
+   * session attribute per supported mode.  The value is the default viewId configured for this mode
+   * for this portlet.  This is done so a developers EL will always resolve to non-null.
+   * 
+   * @param mode name of the portlet mode
+   * @param viewId JSF view that we are currently in/adding to the history.  Includes a QS of the various state needed to restore this view
+   * @param preserveRenderParams indicates whether the render params are carried into the history.  Generally <code>true</code> is the view's mode
+   * hasn't changed from what the bridge finds encoded in its render params and <code>false</code> otherwise.
+   */
+  public void setViewHistory(String mode, String viewId, boolean preserveRenderParams)
+  {
+    
+    // See if viewid contains a querystring
+    int qsStart = viewId.indexOf('?');
+    QueryString qs = null;
+    
+    if (qsStart != -1)
+    {
+      qs = new QueryString(viewId.substring(qsStart+ 1), "UTF8");
+      viewId = viewId.substring(0, qsStart);
+    }
+    else
+    {
+      qs = new QueryString("UTF8");
+    }
+    
+    
+    // ViewHistory is maintained in the session as per spec -- BridgeContext facilitates setting/getting) from non-EL.
+    // always encode the mode in the viewId as this is used for mode transitions
+    qs.setParameter(Bridge.PORTLET_MODE_PARAMETER, mode);
+    
+    if (preserveRenderParams)
+    {
+        // Build a QueryString from the request's render parameters so can preserve
+      // with the viewId 
+      FacesContext fCtx = FacesContext.getCurrentInstance();
+      Map<String, String[]> m = null;
+      
+      if (fCtx != null)
+      {
+        m = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap();
+      }
+      else
+      {
+        // TODO:  Should I work around stuff that the Bridge Map's indicate by wrapping the request/response objects set in the BridgeContext?
+        //   Note: we are also thinking about abstracting these wrappers with bridge specific one's so we can avoid issues with containers that 
+        //   Don't support wrappers properly.
+        
+        // Use PortletRequest PrivateParameterMap -- unfortunately containers don't always do the right thing here so only use in the
+        // unlikely caase its needed outside a FacesContext
+        m = getPortletRequest().getPrivateParameterMap();
+      }
+      if (!m.isEmpty())
+      {
+        Set <Map.Entry<String, String[]>> set = m.entrySet();
+        Iterator <Map.Entry<String,String[]>> i = set.iterator();
+        while (i.hasNext())  
+        {
+          Map.Entry<String,String[]> e = i.next();
+          // only add if not a viewId or viewState parameter
+          if (!e.getKey().equals(mBridgeConfig.getViewIdRenderParameterName())
+          && !e.getKey().equals(ResponseStateManager.VIEW_STATE_PARAM))
+          {
+            for (String s : e.getValue())
+            {
+              qs.addParameter(e.getKey(), s);
+            }
+          }
+        }
+      }
+    }
+    
+    String toAppend = qs.toString();
+    StringBuffer sb = new StringBuffer(viewId.length() + toAppend.length() + 1);
+    viewId = sb.append(viewId).append("?").append(toAppend).toString();
+      
+    // Now add to the appropriate session attribute based on Mode
+    StringBuffer key = new StringBuffer(100);
+    getPortletRequest().getPortletSession(true).setAttribute(key.append(Bridge.VIEWID_HISTORY).append('.').append(mode).toString(), viewId);
+  }
+  
+  
+  /**
+   * Returns the last viewId rendered for a given mode.  Allows one to return to the view you left when you entered a new mode.
+   * Generally this isn't called directly other than potentially to verify that the attributes have initially been set up as the primary use
+   * case is to allow developers to access this value directly from the session object using EL.
+   * @param mode
+   * @return
+   */
+  public String getViewHistory(String mode)
+  {
+    StringBuffer key = new StringBuffer(100);
+    return (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key.append(Bridge.VIEWID_HISTORY).append('.').append(mode).toString());
+  }
+  
+  private void initViewHistoryWithDefaults()
+  {
+    // Only gets inited the first time the bridge receives a request -- we keep a flag on the BridgeConfig object to indicate 
+    // whether this has occurred or not
+    
+    Boolean hasInitializedViewHistory = (Boolean) getBridgeConfig().getAttributes().get(BRIDGE_CONTEXT_HAS_INITED_VIEW_HISTORY);
+    
+    if (hasInitializedViewHistory != null && hasInitializedViewHistory.booleanValue())
+    {
+      Map<String, String> viewIdDefaultMap = getBridgeConfig().getDefaultViewMappings();
+  
+      Set<String> keys = viewIdDefaultMap.keySet();
+      Iterator<String> i = keys.iterator();
+      
+      while (i.hasNext())
+      {
+        String mode = i.next();
+        String modeView = viewIdDefaultMap.get(mode);
+        
+        if (modeView == null || modeView.length() == 0) continue;
+        
+        setViewHistory(mode, modeView, false);
+      }
+    }
+  }
+  
+  private String encodeMode(String mode, String viewId)
+  {
+    // if the viewId doesn't otherwise contain a mode param, encode it
+    // this is done so its already encoded in the viewid when developer uses
+    // to return to the mode/view
+    StringBuffer sb = new StringBuffer(viewId.length() + 30);
+    int queryStart = viewId.indexOf('?');
+    if (queryStart < 0)
+    {
+      return sb.append(viewId)
+        .append('?')
+        .append(Bridge.PORTLET_MODE_PARAMETER)
+        .append('=')
+        .append(mode)
+        .toString();
+    }
+    else
+    {
+      QueryString qs = new QueryString(viewId.substring(queryStart + 1), "UTF8");
+      qs.setParameter(Bridge.PORTLET_MODE_PARAMETER, mode);
+      return sb.append(viewId.substring(0, queryStart + 1)).append(qs.toString()).toString();
+    }
+  }
+    
+  
+  /**
+   * ELContextListener impl
+   */
+  
+  
+  // TODO: move to BridgeContextImpl  - compare the this BridgeContext with the one stored in the FacesContext -- if a match do the work.
+  public void contextCreated(ELContextEvent ece)
+  {
+    // Add the portletConfig to the ELContext so it is evaluated
+    ELContext elContext = ece.getELContext();
+
+    // FacesContext (where the Faces/Bridge ELContext is created doesn't have
+    // access to the PortletConfig which the Bridge ELResolver needs.
+    // The config object is added as an attribute here in the ContextListener.
+    // However only add to a EL context created within Faces as the JSP
+    // ELContext/Resolver will naturally resolve the config (as long as the
+    // page devleper has used the <portlet:defineObjects> tag.
+    // Because listeners are called at app scope we must ensure that only
+    // the active portlet's config is added to the ELContext.  To do this, check
+    // the portletName previously stored as a request attribute against the config.
+    
+    // Make sure our bridge instance is handling this context
+    FacesContext fCtx = (FacesContext) elContext.getContext(FacesContext.class);
+    if (fCtx == null) return;
+    BridgeContext bCtx = BridgeContext.getCurrentInstance();
+    
+    if (this == bCtx)
+    {
+      PortletELContextImpl portletELContext;
+      if (elContext instanceof PortletELContextImpl)
+      {
+        // Grr -- turns out that by the time my resolver is called the ELContext may
+        // have been wrapped -- so mark here as a FacesResolver and then do a put context
+        portletELContext = (PortletELContextImpl) elContext;
+        portletELContext.setFacesResolved(true);
+        // Put the portletConfig object into this Map
+        portletELContext.setPortletConfig(getBridgeConfig().getPortletConfig());
+
+      }
+      else
+      {
+        // create a PortletELContext to hold future resolver state and place on this context
+        portletELContext = new PortletELContextImpl(elContext.getELResolver());
+        portletELContext.setFacesResolved(false);
+      }
+      elContext.putContext(PortletELContextImpl.class, portletELContext);
+    }
+  }
+  
+}
\ No newline at end of file

Added: myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/PreFacesFacesContext.java
URL: http://svn.apache.org/viewvc/myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/PreFacesFacesContext.java?rev=1128097&view=auto
==============================================================================
--- myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/PreFacesFacesContext.java (added)
+++ myfaces/portlet-bridge/core/branches/refactored_3.0.x/impl/src/main/java/org/apache/myfaces/portlet/faces/bridge/context/PreFacesFacesContext.java Thu May 26 21:29:19 2011
@@ -0,0 +1,535 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.myfaces.portlet.faces.bridge.context;
+
+import javax.faces.context.FacesContext;
+import javax.faces.context.ExternalContext;
+import javax.faces.context.ResponseStream;
+import javax.faces.context.ResponseWriter;
+import javax.faces.component.UIViewRoot;
+import javax.faces.application.Application;
+import javax.faces.application.ApplicationFactory;
+import javax.faces.application.FacesMessage;
+import javax.faces.application.ProjectStage;
+import javax.faces.FactoryFinder;
+import javax.faces.render.RenderKit;
+
+import javax.servlet.ServletContext;
+
+import javax.el.ELContext;
+import javax.el.ELResolver;
+import javax.el.FunctionMapper;
+import javax.el.VariableMapper;
+
+import java.util.*;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+
+import java.net.URL;
+import java.net.MalformedURLException;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.myfaces.portlet.faces.bridge.BridgeConfig;
+import org.apache.myfaces.portlet.faces.util.map.PortletApplicationMap;
+import org.apache.myfaces.portlet.faces.util.map.PortletInitParameterMap;
+
+/**
+ * A FacesContext the bridge can use for SystemEvents that are sent before Faces
+ * is activated/invoked.
+ */
+public class PreFacesFacesContext
+  extends FacesContext
+{
+
+  private ExternalContext mExternalContext;
+  private UIViewRoot mUIViewRoot;
+  private FacesContext mOriginalFacesContext;
+  private Map<Object, Object> mAttributes;
+  private ELContext mElContext = new ELContext()
+  {
+    public ELResolver getELResolver()
+    {
+      return null;
+    }
+
+    public FunctionMapper getFunctionMapper()
+    {
+      return null;
+    }
+
+    public VariableMapper getVariableMapper()
+    {
+      return null;
+    }
+  };
+
+  public PreFacesFacesContext(BridgeConfig bConfig)
+  {
+    mExternalContext = new PreFacesExternalContext(bConfig);
+    mOriginalFacesContext = FacesContext.getCurrentInstance();
+    setCurrentInstance(this);
+  }
+
+  @Override
+  public Map<Object, Object> getAttributes()
+  {
+    if (mAttributes == null)
+    {
+      mAttributes = new ConcurrentHashMap<Object, Object>();
+    }
+    return mAttributes;
+  }
+
+  public Application getApplication()
+  {
+    ApplicationFactory factory =
+      (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
+    return factory.getApplication();
+  }
+
+  public Iterator<String> getClientIdsWithMessages()
+  {
+    List<String> list = Collections.emptyList();
+    return list.iterator();
+  }
+
+  public ExternalContext getExternalContext()
+  {
+    return mExternalContext;
+  }
+
+  public FacesMessage.Severity getMaximumSeverity()
+  {
+    return FacesMessage.SEVERITY_INFO;
+  }
+
+  public Iterator<FacesMessage> getMessages()
+  {
+    List<FacesMessage> list = Collections.emptyList();
+    return list.iterator();
+  }
+
+  public Iterator<FacesMessage> getMessages(String clientId)
+  {
+    return getMessages();
+  }
+
+  public List<FacesMessage> getMessageList()
+  {
+    return Collections.EMPTY_LIST;
+  }
+
+
+  public List<FacesMessage> getMessageList(String clientId)
+  {
+    return Collections.EMPTY_LIST;
+  }
+
+
+  @Override
+  public boolean isProjectStage(ProjectStage stage)
+  {
+    if (stage == null)
+    {
+      throw new NullPointerException();
+    }
+    return stage.equals(getApplication().getProjectStage());
+  }
+
+  public RenderKit getRenderKit()
+  {
+    return null;
+  }
+
+  public boolean getRenderResponse()
+  {
+    return true;
+  }
+
+  public boolean getResponseComplete()
+  {
+    return true;
+  }
+
+  @Override
+  public boolean isValidationFailed()
+  {
+    return false;
+  }
+
+  public ResponseStream getResponseStream()
+  {
+    return null;
+  }
+
+  public void setResponseStream(ResponseStream responseStream)
+  {
+  }
+
+  public ResponseWriter getResponseWriter()
+  {
+    return null;
+  }
+
+  public void setResponseWriter(ResponseWriter responseWriter)
+  {
+  }
+
+  public UIViewRoot getViewRoot()
+  {
+    if (mUIViewRoot == null)
+    {
+      mUIViewRoot = new UIViewRoot();
+      mUIViewRoot.setLocale(Locale.getDefault());
+    }
+    return mUIViewRoot;
+  }
+
+  public void setViewRoot(UIViewRoot root)
+  {
+  }
+
+  public void addMessage(String clientId, FacesMessage message)
+  {
+  }
+
+  public void release()
+  {
+    setCurrentInstance(mOriginalFacesContext);
+    if (null != mAttributes)
+    {
+      mAttributes.clear();
+      mAttributes = null;
+    }
+  }
+
+  public void renderResponse()
+  {
+  }
+
+  public void responseComplete()
+  {
+  }
+
+  @Override
+  public void validationFailed()
+  {
+  }
+
+  @Override
+  public ELContext getELContext()
+  {
+    return mElContext;
+  }
+
+  public void setELContext(ELContext elContext)
+  {
+    this.mElContext = elContext;
+  }
+
+  private static class PreFacesExternalContext
+    extends ExternalContext
+  {
+
+    private BridgeConfig mBridgeConfig = null;
+    private Map<String, Object>  mApplicationMap = null;
+    private Map<String, String>  mInitParameterMap = null;
+
+    public PreFacesExternalContext(BridgeConfig config)
+    {
+      mBridgeConfig = config;
+    }
+
+    public void dispatch(String path)
+      throws IOException
+    {
+    }
+
+    public String encodeActionURL(String url)
+    {
+      return null;
+    }
+
+    public String encodeNamespace(String name)
+    {
+      return null;
+    }
+
+
+    public String encodeResourceURL(String url)
+    {
+      return null;
+    }
+
+    public Map<String, Object> getApplicationMap()
+    {
+      if (mApplicationMap == null)
+      {
+        mApplicationMap = new PortletApplicationMap(mBridgeConfig.getPortletConfig().getPortletContext());
+      }
+      return mApplicationMap;
+    }
+
+    public String getAuthType()
+    {
+      return null;
+    }
+
+    @Override
+    public String getMimeType(String file)
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getMimeType(file);
+    }
+
+    public Object getContext()
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext();
+    }
+
+    public String getContextName()
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getPortletContextName();
+    }
+
+
+    public String getInitParameter(String name)
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getInitParameter(name);
+    }
+
+    public Map<String, String> getInitParameterMap()
+    {
+      if (mInitParameterMap == null)
+      {
+        mInitParameterMap = new PortletInitParameterMap(mBridgeConfig.getPortletConfig().getPortletContext());
+      }
+      return mInitParameterMap;
+    }
+
+    public String getRemoteUser()
+    {
+      return null;
+    }
+
+
+    public Object getRequest()
+    {
+      return null;
+    }
+
+    @Override
+    public void setRequest(Object request)
+    {
+    }
+
+    public String getRequestContextPath()
+    {
+      return null;
+    }
+
+    public Map<String, Object> getRequestCookieMap()
+    {
+      return Collections.unmodifiableMap(Collections.<String, Object>emptyMap());
+    }
+
+    public Map<String, String> getRequestHeaderMap()
+    {
+      return Collections.unmodifiableMap(Collections.<String, String>emptyMap());
+    }
+
+
+    public Map<String, String[]> getRequestHeaderValuesMap()
+    {
+      return Collections.unmodifiableMap(Collections.<String, String[]>emptyMap());
+    }
+
+
+    public Locale getRequestLocale()
+    {
+      return null;
+    }
+
+    public Iterator<Locale> getRequestLocales()
+    {
+      return null;
+    }
+
+
+    public Map<String, Object> getRequestMap()
+    {
+      return Collections.emptyMap();
+    }
+
+
+    public Map<String, String> getRequestParameterMap()
+    {
+      return Collections.unmodifiableMap(Collections.<String, String>emptyMap());
+    }
+
+
+    public Iterator<String> getRequestParameterNames()
+    {
+      return Collections.<String>emptyList().iterator();
+    }
+
+
+    public Map<String, String[]> getRequestParameterValuesMap()
+    {
+      return Collections.unmodifiableMap(Collections.<String, String[]>emptyMap());
+    }
+
+
+    public String getRequestPathInfo()
+    {
+      return null;
+    }
+
+
+    public String getRequestServletPath()
+    {
+      return null;
+    }
+
+    @Override
+    public String getRequestContentType()
+    {
+      return null;
+    }
+
+    @Override
+    public String getResponseContentType()
+    {
+      return null;
+    }
+
+    public int getRequestContentLength()
+    {
+      return -1;
+    }
+
+    public URL getResource(String path)
+      throws MalformedURLException
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getResource(path);
+    }
+
+
+    public InputStream getResourceAsStream(String path)
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getResourceAsStream(path);
+    }
+
+    public Set<String> getResourcePaths(String path)
+    {
+      return mBridgeConfig.getPortletConfig().getPortletContext().getResourcePaths(path);
+    }
+
+    public Object getResponse()
+    {
+      return null;
+    }
+
+    @Override
+    public void setResponse(Object response)
+    {
+    }
+
+    public Object getSession(boolean create)
+    {
+      return null;
+    }
+
+    public Map<String, Object> getSessionMap()
+    {
+      return Collections.emptyMap();
+    }
+
+    public java.security.Principal getUserPrincipal()
+    {
+      return null;
+    }
+
+    public boolean isUserInRole(String role)
+    {
+      return false;
+    }
+
+    public void log(String message)
+    {
+      mBridgeConfig.getLogger().log(message);
+    }
+
+    public void log(String message, Throwable exception)
+    {
+      mBridgeConfig.getLogger().log(message, exception);
+    }
+
+    public void redirect(String url)
+      throws IOException
+    {
+    }
+
+    @Override
+    public String getRequestCharacterEncoding()
+    {
+      return null;
+    }
+
+    @Override
+    public void setRequestCharacterEncoding(String requestCharacterEncoding)
+      throws UnsupportedEncodingException
+    {
+
+    }
+
+    @Override
+    public String getResponseCharacterEncoding()
+    {
+      return null;
+    }
+
+    @Override
+    public void setResponseCharacterEncoding(String responseCharacterEncoding)
+    {
+    }
+
+    @Override
+    public void setResponseHeader(String name, String value)
+    {
+    }
+
+    @Override
+    public void addResponseHeader(String name, String value)
+    {
+    }
+
+    @Override
+    public String encodePartialActionURL(String url)
+    {
+      return null;
+    }
+
+
+  } // END ServletContextAdapter
+
+}