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