Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * $Id: UIViewRoot.java,v 1.49.4.1 2007/10/18 16:57:29 rlubke Exp $
   */
  
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   * 
   * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
   * 
  * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common Development
  * and Distribution License("CDDL") (collectively, the "License").  You
  * may not use this file except in compliance with the License. You can obtain
  * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
  * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  * 
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
  * Sun designates this particular file as subject to the "Classpath" exception
  * as provided by Sun in the GPL Version 2 section of the License file that
  * accompanied this code.  If applicable, add the following below the License
  * Header, with the fields enclosed by brackets [] replaced by your own
  * identifying information: "Portions Copyrighted [year]
  * [name of copyright owner]"
  * 
  * Contributor(s):
  * 
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package javax.faces.component;
 
 
 
 import java.util.List;

UIViewRoot is the UIComponent that represents the root of the UIComponent tree. This component has no rendering, it just serves as the root of the component tree, and as a place to hang per-view javax.faces.event.PhaseListeners.

For each of the following lifecycle phase methods:

Take the following action regarding PhaseListeners.

public class UIViewRoot extends UIComponentBase {
    // ------------------------------------------------------ Manifest Constants


    

The standard component type for this component.

    public static final String COMPONENT_TYPE = "javax.faces.ViewRoot";


    

The standard component family for this component.

    public static final String COMPONENT_FAMILY = "javax.faces.ViewRoot";


    

The prefix that will be used for identifiers generated by the createUniqueId() method.

    static public final String UNIQUE_ID_PREFIX = "j_id";
    private static Lifecycle lifecycle;
    private static final Logger LOGGER =
          Logger.getLogger("javax.faces""javax.faces.LogStrings");
    // ------------------------------------------------------------ Constructors


    

Create a new UIViewRoot instance with default property values.

    public UIViewRoot() {
        super();
        setRendererType(null);
    }
    // ------------------------------------------------------ Instance Variables
    private int lastId = 0;

    

Set and cleared during the lifetime of a lifecycle phase. Has no meaning between phases. If true, the lifecycle processing for the current phase must not take place.

    private boolean skipPhase;
    // -------------------------------------------------------------- Properties
    // -------------------------------------------------------------- Properties
    public String getFamily() {
        return ();
    }


    

The render kit identifier of the javax.faces.render.RenderKit associated wth this view.

    private String renderKitId = null;


    

Return the render kit identifier of the javax.faces.render.RenderKit associated with this view. Unless explicitly set, as in javax.faces.application.ViewHandler.createView(javax.faces.context.FacesContext,java.lang.String), the returned value will be null.

    public String getRenderKitId() {
        String result;
        if (null != ) {
            result = this.;
        } else {
            ValueExpression vb = getValueExpression("renderKitId");
            FacesContext context = getFacesContext();
            if (vb != null) {
                try {
                    result = (Stringvb.getValue(context.getELContext());
                }
                catch (ELException e) {
                    // PENDING(edburns): log this
                    result = null;
                }
            } else {
                result = null;
            }
        }
        return result;
    }


    

Set the render kit identifier of the javax.faces.render.RenderKit associated with this view. This method may be called at any time between the end of Apply Request Values phase of the request processing lifecycle (i.e. when events are being broadcast) and the beginning of the Render Response phase.

Parameters:
renderKitId The new javax.faces.render.RenderKit identifier, or null to disassociate this view with any specific javax.faces.render.RenderKit instance
    public void setRenderKitId(String renderKitId) {
        this. = renderKitId;
    }


    

The view identifier of this view.

    private String viewId = null;


    

Return the view identifier for this view.

    public String getViewId() {
        return (this.);
    }


    

Set the view identifier for this view.

Parameters:
viewId The new view identifier
    public void setViewId(String viewId) {
        this. = viewId;
    }
    // ------------------------------------------------ Event Management Methods
    private MethodExpression beforePhase = null;
    private MethodExpression afterPhase = null;

    

Returns:
the javax.el.MethodExpression that will be invoked before this view is rendered.
        return ;
    }

    

Allow an arbitrary method to be called for the "beforePhase" event as the UIViewRoot runs through its lifecycle. This method will be called for all phases except javax.faces.event.PhaseId.RESTORE_VIEW. Unlike a true javax.faces.event.PhaseListener, this approach doesn't allow for only receiving javax.faces.event.PhaseEvents for a given phase.

The method must conform to the signature of javax.faces.event.PhaseListener.beforePhase(javax.faces.event.PhaseEvent).

Parameters:
newBeforePhase the javax.el.MethodExpression that will be invoked before this view is rendered.
    public void setBeforePhaseListener(MethodExpression newBeforePhase) {
         = newBeforePhase;
    }

    

Returns:
the javax.el.MethodExpression that will be invoked after this view is rendered.
        return ;
    }

    

Allow an arbitrary method to be called for the "afterPhase" event as the UIViewRoot runs through its lifecycle. This method will be called for all phases except javax.faces.event.PhaseId.RESTORE_VIEW. Unlike a true javax.faces.event.PhaseListener, this approach doesn't allow for only receiving javax.faces.event.PhaseEvents for a given phase.

The method must conform to the signature of javax.faces.event.PhaseListener.afterPhase(javax.faces.event.PhaseEvent).

Parameters:
newAfterPhase the javax.el.MethodExpression that will be invoked after this view is rendered.
    public void setAfterPhaseListener(MethodExpression newAfterPhase) {
         = newAfterPhase;
    }
    private List<PhaseListenerphaseListeners = null;
    public void removePhaseListener(PhaseListener toRemove) {
        if (null != ) {
            .remove(toRemove);
        }
    }
    public void addPhaseListener(PhaseListener newPhaseListener) {
        if (null == ) {
            //noinspection CollectionWithoutInitialCapacity
             = new ArrayList<PhaseListener>();
        }
        .add(newPhaseListener);
    }

    

An array of Lists of events that have been queued for later broadcast, with one List for each lifecycle phase. The list indices match the ordinals of the PhaseId instances. This instance is lazily instantiated. This list is NOT part of the state that is saved and restored for this component.

    private List<List<FacesEvent>> events = null;


    

Override the default UIComponentBase.queueEvent(javax.faces.event.FacesEvent) behavior to accumulate the queued events for later broadcasting.

Parameters:
event javax.faces.event.FacesEvent to be queued
Throws:
java.lang.IllegalStateException if this component is not a descendant of a UIViewRoot
java.lang.NullPointerException if event is null
    public void queueEvent(FacesEvent event) {
        if (event == null) {
            throw new NullPointerException();
        }
        int i;
        int len = ..size();
        // We are a UIViewRoot, so no need to check for the ISE
        if ( == null) {
            List<List<FacesEvent>> events = new ArrayList<List<FacesEvent>>(len);
            for (i = 0; i < leni++) {
                events.add(new ArrayList<FacesEvent>(5));
            }
            this. = events;
        }
        .get(event.getPhaseId().getOrdinal()).add(event);
    }


    

Broadcast any events that have been queued.

Parameters:
context javax.faces.context.FacesContext for the current request
phaseId javax.faces.event.PhaseId of the current phase
    private void broadcastEvents(FacesContext contextPhaseId phaseId) {
        if (null == ) {
            // no events have been queued
            return;
        }
        boolean hasMoreAnyPhaseEvents;
        boolean hasMoreCurrentPhaseEvents;
        List<FacesEventeventsForPhaseId =
             .get(..getOrdinal());
        // keep iterating till we have no more events to broadcast.
        // This is necessary for events that cause other events to be
        // queued.  PENDING(edburns): here's where we'd put in a check
        // to prevent infinite event queueing.
        do {
            // broadcast the ANY_PHASE events first
            if (null != eventsForPhaseId) {
                // We cannot use an Iterator because we will get
                // ConcurrentModificationException errors, so fake it
                while (!eventsForPhaseId.isEmpty()) {
                    FacesEvent event =
                          eventsForPhaseId.get(0);
                    UIComponent source = event.getComponent();
                    try {
                        source.broadcast(event);
                    } catch (AbortProcessingException e) {
                        if (.isLoggable(.)) {
                            UIComponent component = event.getComponent();
                            String id = "";
                            if (component != null) {
                                id = component.getId();
                                if (id == null) {
                                    id = component.getClientId(context);
                                }
                            }
                            .log(.,
                                       "error.component.abortprocessing_thrown",
                                       new Object[]{event.getClass().getName(),
                                                    phaseId.toString(),
                                                    id});
                            .log(.e.toString(), e);
                        }
                    }
                    eventsForPhaseId.remove(0); // Stay at current position
                }
            }
            // then broadcast the events for this phase.
            if (null != (eventsForPhaseId = .get(phaseId.getOrdinal()))) {
                // We cannot use an Iterator because we will get
                // ConcurrentModificationException errors, so fake it
                while (!eventsForPhaseId.isEmpty()) {
                    FacesEvent event = eventsForPhaseId.get(0);
                    UIComponent source = event.getComponent();
                    try {
                        source.broadcast(event);
                    } catch (AbortProcessingException e) {
                        ; // A "return" here would abort remaining events too
                    }
                    eventsForPhaseId.remove(0); // Stay at current position
                }
            }
            // true if we have any more ANY_PHASE events
            hasMoreAnyPhaseEvents =
                  (null != (eventsForPhaseId =
                        .get(..getOrdinal()))) &&
                        !eventsForPhaseId.isEmpty();
            // true if we have any more events for the argument phaseId
            hasMoreCurrentPhaseEvents =
                  (null != .get(phaseId.getOrdinal())) &&
                  !.get(phaseId.getOrdinal()).isEmpty();
        } while (hasMoreAnyPhaseEvents || hasMoreCurrentPhaseEvents);
    }
    // ------------------------------------------------ Lifecycle Phase Handlers


    

Override the default UIComponentBase.processDecodes(javax.faces.context.FacesContext) behavior to broadcast any queued events after the default processing has been completed and to clear out any events for later phases if the event processing for this phase caused javax.faces.context.FacesContext.renderResponse() or javax.faces.context.FacesContext.responseComplete() to be called.

Parameters:
context javax.faces.context.FacesContext for the request we are processing
Throws:
java.lang.NullPointerException if context is null
    public void processDecodes(FacesContext context) {
         = false;
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.true);
        }
        if (!) {
            super.processDecodes(context);
            broadcastEvents(context.);
        }
        // clear out the events if we're skipping to render-response
        // or if there is a response complete signal.
        if (context.getRenderResponse() || context.getResponseComplete()) {
            if ( != null) {
                for (List<FacesEventeventList : ) {
                    if (eventList != null) {
                        eventList.clear();
                    }
                }
                 = null;
            }
        }
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.false);
        }
    }

    

Override the default UIComponentBase.encodeBegin(javax.faces.context.FacesContext) behavior. If getBeforePhaseListener() returns non-null, invoke it, passing a javax.faces.event.PhaseEvent for the javax.faces.event.PhaseId.RENDER_RESPONSE phase. If the internal list populated by calls to addPhaseListener(javax.faces.event.PhaseListener) is non-empty, any listeners in that list must have their javax.faces.event.PhaseListener.beforePhase(javax.faces.event.PhaseEvent) method called, passing the PhaseEvent. Any errors that occur during invocation of any of the the beforePhase listeners must be logged and swallowed. After listeners are invoked call superclass processing.

    public void encodeBegin(FacesContext contextthrows IOException {
         = false;
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.true);
        }
        if (!) {
            super.encodeBegin(context);
        }
    }

    

Override the default UIComponentBase.encodeEnd(javax.faces.context.FacesContext) behavior. If getAfterPhaseListener() returns non-null, invoke it, passing a javax.faces.event.PhaseEvent for the javax.faces.event.PhaseId.RENDER_RESPONSE phase. Any errors that occur during invocation of the afterPhase listener must be logged and swallowed.

    public void encodeEnd(FacesContext contextthrows IOException {
        super.encodeEnd(context);
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.false);
        }
    }

    

Utility method that notifies phaseListeners for the given phaseId. Assumes that either or both the MethodExpression or phaseListeners data structure are non-null.

Parameters:
context the context for this request
phaseId the javax.faces.event.PhaseId of the current phase
isBefore, if true, notify beforePhase listeners. Notify afterPhase listeners otherwise.
    private void notifyPhaseListeners(FacesContext context,
                                      PhaseId phaseId,
                                      boolean isBefore) {
        PhaseEvent event = createPhaseEvent(contextphaseId);
        boolean hasPhaseMethodExpression =
              (isBefore && (null != )) ||
              (!isBefore && (null != ));
        MethodExpression expression = isBefore ?  : ;
        if (hasPhaseMethodExpression) {
            try {
                expression.invoke(context.getELContext(), new Object[]{event});
                 = context.getResponseComplete() ||
                            context.getRenderResponse();
            }
            catch (Exception e) {
                // PENDING(edburns): log this
            }
        }
        if (null != ) {
            Iterator<PhaseListeneriter = .iterator();
            PhaseListener curListener;
            while (iter.hasNext()) {
                curListener = iter.next();
                if (phaseId == curListener.getPhaseId() ||
                    . == curListener.getPhaseId()) {
                    try {
                        if (isBefore) {
                            curListener.beforePhase(event);
                        } else {
                            curListener.afterPhase(event);
                        }
                         = context.getResponseComplete() ||
                                    context.getRenderResponse();
                    }
                    catch (Exception e) {
                        // PENDING(edburns): log this
                    }
                }
            }
        }
    }
    private static PhaseEvent createPhaseEvent(FacesContext context,
                                               PhaseId phaseId)
    throws FacesException {
        if ( == null) {
            LifecycleFactory lifecycleFactory = (LifecycleFactory)
                  FactoryFinder.getFactory(.);
            String lifecycleId =
                  context.getExternalContext()
                        .getInitParameter(.);
            if (lifecycleId == null) {
                lifecycleId = .;
            }
             = lifecycleFactory.getLifecycle(lifecycleId);
        }
        return (new PhaseEvent(contextphaseId));
    }


    

Override the default UIComponentBase.processValidators(javax.faces.context.FacesContext) behavior to broadcast any queued events after the default processing has been completed and to clear out any events for later phases if the event processing for this phase caused javax.faces.context.FacesContext.renderResponse() or javax.faces.context.FacesContext.responseComplete() to be called.

Parameters:
context javax.faces.context.FacesContext for the request we are processing
Throws:
java.lang.NullPointerException if context is null
    public void processValidators(FacesContext context) {
         = false;
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.true);
        }
        if (!) {
            super.processValidators(context);
            broadcastEvents(context.);
        }
        // clear out the events if we're skipping to render-response
        // or if there is a response complete signal.
        if (context.getRenderResponse() || context.getResponseComplete()) {
            if ( != null) {
                for (List<FacesEventeventList : ) {
                    if (eventList != null) {
                        eventList.clear();
                    }
                }
                 = null;
            }
        }
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.false);
        }
    }


    

Override the default UIComponentBase behavior to broadcast any queued events after the default processing has been completed and to clear out any events for later phases if the event processing for this phase caused javax.faces.context.FacesContext.renderResponse() or javax.faces.context.FacesContext.responseComplete() to be called.

Parameters:
context javax.faces.context.FacesContext for the request we are processing
Throws:
java.lang.NullPointerException if context is null
    public void processUpdates(FacesContext context) {
         = false;
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.true);
        }
        if (!) {
            super.processUpdates(context);
            broadcastEvents(context.);
        }
        // clear out the events if we're skipping to render-response
        // or if there is a response complete signal.
        if (context.getRenderResponse() || context.getResponseComplete()) {
            if ( != null) {
                for (List<FacesEventeventList : ) {
                    if (eventList != null) {
                        eventList.clear();
                    }
                }
                 = null;
            }
        }
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.false);
        }
    }


    

Broadcast any events that have been queued for the Invoke Application phase of the request processing lifecycle and to clear out any events for later phases if the event processing for this phase caused javax.faces.context.FacesContext.renderResponse() or javax.faces.context.FacesContext.responseComplete() to be called.

Parameters:
context javax.faces.context.FacesContext for the request we are processing
Throws:
java.lang.NullPointerException if context is null
    public void processApplication(FacesContext context) {
         = false;
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.true);
        }
        if (!) {
            // NOTE - no tree walk is performed; this is a UIViewRoot-only operation
            broadcastEvents(context.);
        }
        // clear out the events if we're skipping to render-response
        // or if there is a response complete signal.
        if (context.getRenderResponse() || context.getResponseComplete()) {
            if ( != null) {
                for (List<FacesEventeventList : ) {
                    if (eventList != null) {
                        eventList.clear();
                    }
                }
                 = null;
            }
        }
        // avoid creating the PhaseEvent if possible by doing redundant
        // null checks.
        if (null !=  || null != ) {
            notifyPhaseListeners(context.false);
        }
    }

    

Generate an identifier for a component. The identifier will be prefixed with UNIQUE_ID_PREFIX, and will be unique within this UIViewRoot.

    public String createUniqueId() {
        return  + ++;
    }
    /*
    * <p>The locale for this view.</p>
    */
    private Locale locale = null;

    

Return the Locale to be used in localizing the response being created for this view.

Algorithm:

If we have a locale ivar, return it. If we have a value expression for "locale", get its value. If the value is null, return the result of calling javax.faces.application.ViewHandler.calculateLocale(javax.faces.context.FacesContext). If the value is an instance of java.util.Locale return it. If the value is a String, convert it to a java.util.Locale and return it. If there is no value expression for "locale", return the result of calling javax.faces.application.ViewHandler.calculateLocale(javax.faces.context.FacesContext).

Returns:
The current Locale obtained by executing the above algorithm.
    public Locale getLocale() {
        Locale result = null;
        if (null != ) {
            result = this.;
        } else {
            ValueExpression vb = getValueExpression("locale");
            FacesContext context = getFacesContext();
            if (vb != null) {
                Object resultLocale = null;
                try {
                    resultLocale = vb.getValue(context.getELContext());
                }
                catch (ELException e) {
                    // PENDING(edburns): log this
                }
                if (null == resultLocale) {
                    result =
                          context.getApplication().getViewHandler()
                                .calculateLocale(context);
                } else if (resultLocale instanceof Locale) {
                    result = (LocaleresultLocale;
                } else if (resultLocale instanceof String) {
                    result = getLocaleFromString((StringresultLocale);
                }
            } else {
                result =
                      context.getApplication().getViewHandler()
                            .calculateLocale(context);
            }
        }
        return result;
    }


    
Returns the locale represented by the expression.

Parameters:
localeExpr a String in the format specified by JSTL Specification as follows: "A String value is interpreted as the printable representation of a locale, which must contain a two-letter (lower-case) language code (as defined by ISO-639), and may contain a two-letter (upper-case) country code (as defined by ISO-3166). Language and country codes must be separated by hyphen (???-???) or underscore (???_???)."
Returns:
Locale instance cosntructed from the expression.
    private static Locale getLocaleFromString(String localeExpr) {
        Locale result = Locale.getDefault();
        if (localeExpr.indexOf('_') == -1 || localeExpr.indexOf('-') == -1) {
            // expression has just language code in it. make sure the 
            // expression contains exactly 2 characters.
            if (localeExpr.length() == 2) {
                result = new Locale(localeExpr"");
            }
        } else {
            // expression has country code in it. make sure the expression 
            // contains exactly 5 characters.
            if (localeExpr.length() == 5) {
                // get the language and country to construct the locale.
                String language = localeExpr.substring(0, 1);
                String country = localeExpr.substring(3, 4);
                result = new Locale(languagecountry);
            }
        }
        return result;
    }

    

Set the Locale to be used in localizing the response being created for this view.

Parameters:
locale The new localization Locale
    public void setLocale(Locale locale) {
        this. = locale;
        // Make sure to appraise the EL of this switch in Locale.
        FacesContext.getCurrentInstance().getELContext().setLocale(locale);
    }
    // ----------------------------------------------------- StateHolder Methods
    private Object[] values;
    public Object saveState(FacesContext context) {
        if ( == null) {
             = new Object[8];
        }
        [0] = super.saveState(context);
        [1] = ;
        [2] = ;
        [3] = ;
        [4] = ;
        [5] = saveAttachedState(context);
        [6] = saveAttachedState(context);
        [7] = saveAttachedState(context);
        return ();
    }
    public void restoreState(FacesContext contextObject state) {
         = (Object[]) state;
        super.restoreState(context, values[0]);
         = (String[1];
         = (String[2];
         = (Locale[3];
         = ((Integer[4]).intValue();
         =
              (MethodExpressionrestoreAttachedState(context[5]);
         =
              (MethodExpressionrestoreAttachedState(context[6]);
         = TypedCollections.dynamicallyCastList((List)
              restoreAttachedState(context[7]), PhaseListener.class);
    }
New to GrepCode? Check out our FAQ X