View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.lifecycle;
20  
21  import java.io.IOException;
22  import java.util.List;
23  import java.util.logging.Level;
24  import java.util.logging.Logger;
25  
26  import javax.faces.FacesException;
27  import javax.faces.application.Application;
28  import javax.faces.application.FacesMessage;
29  import javax.faces.application.ProjectStage;
30  import javax.faces.application.ViewHandler;
31  import javax.faces.component.UIViewRoot;
32  import javax.faces.context.FacesContext;
33  import javax.faces.event.PhaseId;
34  import javax.faces.event.PreRenderViewEvent;
35  import javax.faces.view.ViewDeclarationLanguage;
36  
37  import org.apache.myfaces.shared.config.MyfacesConfig;
38  
39  /**
40   * Implements the render response phase (JSF Spec 2.2.6)
41   * 
42   * @author Nikolay Petrov (latest modification by $Author$)
43   * @version $Revision$ $Date$
44   */
45  class RenderResponseExecutor extends PhaseExecutor
46  {
47      
48      private static final Logger log = Logger.getLogger(RenderResponseExecutor.class.getName());
49      private MyfacesConfig _myfacesConfig;
50      
51      public boolean execute(FacesContext facesContext)
52      {
53          Application application = facesContext.getApplication();
54          ViewHandler viewHandler = application.getViewHandler();
55          UIViewRoot root;
56          UIViewRoot previousRoot;
57          String viewId;
58          String newViewId;
59          boolean isNotSameRoot;
60          int loops = 0;
61          int maxLoops = 15;
62          
63          if (facesContext.getViewRoot() == null)
64          {
65              throw new ViewNotFoundException("A view is required to execute "+facesContext.getCurrentPhaseId());
66          }
67  
68          forceSessionCreation(facesContext);
69  
70          try
71          {
72              // do-while, because the view might change in PreRenderViewEvent-listeners
73              do
74              {
75                  root = facesContext.getViewRoot();
76                  previousRoot = root;
77                  viewId = root.getViewId();
78                  
79                  ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(
80                          facesContext, viewId);
81                  if (vdl != null)
82                  {
83                      vdl.buildView(facesContext, root);
84                  }
85                  
86                  // publish a PreRenderViewEvent: note that the event listeners
87                  // of this event can change the view, so we have to perform the algorithm 
88                  // until the viewId does not change when publishing this event.
89                  application.publishEvent(facesContext, PreRenderViewEvent.class, root);
90                  
91                  // was the response marked as complete by an event listener?
92                  if (facesContext.getResponseComplete())
93                  {
94                      return false;
95                  }
96  
97                  root = facesContext.getViewRoot();
98                  
99                  newViewId = root.getViewId();
100                 
101                 isNotSameRoot = !( (newViewId == null ? newViewId == viewId : newViewId.equals(viewId) ) && 
102                         previousRoot.equals(root) ); 
103                 
104                 loops++;
105             }
106             while ((newViewId == null && viewId != null) 
107                     || (newViewId != null && (!newViewId.equals(viewId) || isNotSameRoot ) ) && loops < maxLoops);
108             
109             if (loops == maxLoops)
110             {
111                 // PreRenderView reach maxLoops - probably a infinitive recursion:
112                 boolean production = facesContext.isProjectStage(ProjectStage.Production);
113                 Level level = production ? Level.FINE : Level.WARNING;
114                 if (log.isLoggable(level))
115                 {
116                     log.log(level, "Cicle over buildView-PreRenderViewEvent on RENDER_RESPONSE phase "
117                                    + "reaches maximal limit, please check listeners for infinite recursion.");
118                 }
119             }
120 
121             viewHandler.renderView(facesContext, root);
122             
123             // log all unhandled FacesMessages, don't swallow them
124             // perf: org.apache.myfaces.context.servlet.FacesContextImpl.getMessageList() creates
125             // new Collections.unmodifiableList with every invocation->  call it only once
126             // and messageList is RandomAccess -> use index based loop
127             List<FacesMessage> messageList = facesContext.getMessageList();
128             if (!messageList.isEmpty())
129             {
130                 StringBuilder builder = new StringBuilder();
131                 boolean shouldLog = false;
132                 for (int i = 0, size = messageList.size(); i < size; i++)
133                 {
134                     FacesMessage message = messageList.get(i);
135                     if (!message.isRendered())
136                     {
137                         builder.append("\n- ");
138                         builder.append(message.getDetail());
139                         
140                         shouldLog = true;
141                     }
142                 }
143                 if (shouldLog)
144                 {
145                     log.log(Level.WARNING, "There are some unhandled FacesMessages, " +
146                             "this means not every FacesMessage had a chance to be rendered.\n" +
147                             "These unhandled FacesMessages are: " + builder.toString());
148                 }
149             }
150         }
151         catch (IOException e)
152         {
153             throw new FacesException(e.getMessage(), e);
154         }
155         return false;
156     }
157 
158     public PhaseId getPhase()
159     {
160         return PhaseId.RENDER_RESPONSE;
161     }
162 
163     /**
164      * Create a session if the ALWAYS_FORCE_SESSION_CREATION param is set to true, or if the
165      * current view is not transient and server side state saving is in use.
166      * 
167      * Note: if the current view is transient or client side state saving is in use, it is 
168      * not technically correct to create a session here, since a session should not be
169      * required for those cases and creating one will cause undesirable memory usage.  
170      * However, if we do not create a session before rendering begins and view or session
171      * scope beans are created later on, then the response might be committed before those 
172      * scopes have a chance to create a session and so the session cookie will not be set.
173      * See MYFACES-4309
174      * 
175      * @param FacesContext
176      */
177     private void forceSessionCreation(FacesContext context) 
178     {
179         if (context.getExternalContext().getSession(false) == null) 
180         {
181             if (_myfacesConfig == null) 
182             {
183                 _myfacesConfig = MyfacesConfig.getCurrentInstance(context.getExternalContext());
184             }
185             if (_myfacesConfig.isAlwaysForceSessionCreation() 
186                     || (!context.getViewRoot().isTransient() 
187                     && !context.getApplication().getStateManager().isSavingStateInClient(context))) 
188             {
189                 context.getExternalContext().getSession(true);
190             }
191         }
192     }
193 }