KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > icesoft > faces > context > BridgeFacesContext


1 /*
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * "The contents of this file are subject to the Mozilla Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
11  * License for the specific language governing rights and limitations under
12  * the License.
13  *
14  * The Original Code is ICEfaces 1.5 open source software code, released
15  * November 5, 2006. The Initial Developer of the Original Code is ICEsoft
16  * Technologies Canada, Corp. Portions created by ICEsoft are Copyright (C)
17  * 2004-2006 ICEsoft Technologies Canada, Corp. All Rights Reserved.
18  *
19  * Contributor(s): _____________________.
20  *
21  * Alternatively, the contents of this file may be used under the terms of
22  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"
23  * License), in which case the provisions of the LGPL License are
24  * applicable instead of those above. If you wish to allow use of your
25  * version of this file only under the terms of the LGPL License and not to
26  * allow others to use your version of this file under the MPL, indicate
27  * your decision by deleting the provisions above and replace them with
28  * the notice and other provisions required by the LGPL License. If you do
29  * not delete the provisions above, a recipient may use your version of
30  * this file under either the MPL or the LGPL License."
31  *
32  */

33 package com.icesoft.faces.context;
34
35 import com.icesoft.faces.application.D2DViewHandler;
36 import com.icesoft.faces.el.ELContextImpl;
37 import com.icesoft.faces.webapp.command.CommandQueue;
38 import com.icesoft.faces.webapp.http.common.Configuration;
39 import org.apache.commons.logging.Log;
40 import org.apache.commons.logging.LogFactory;
41 import org.w3c.dom.Document JavaDoc;
42 import org.w3c.dom.Element JavaDoc;
43 import org.w3c.dom.NodeList JavaDoc;
44
45 import javax.el.ELContext;
46 import javax.faces.FactoryFinder;
47 import javax.faces.application.Application;
48 import javax.faces.application.ApplicationFactory;
49 import javax.faces.application.FacesMessage;
50 import javax.faces.component.UIViewRoot;
51 import javax.faces.context.ExternalContext;
52 import javax.faces.context.FacesContext;
53 import javax.faces.context.ResponseStream;
54 import javax.faces.context.ResponseWriter;
55 import javax.faces.render.RenderKit;
56 import javax.faces.render.RenderKitFactory;
57 import java.io.IOException JavaDoc;
58 import java.util.ArrayList JavaDoc;
59 import java.util.Arrays JavaDoc;
60 import java.util.Collections JavaDoc;
61 import java.util.HashMap JavaDoc;
62 import java.util.Iterator JavaDoc;
63 import java.util.List JavaDoc;
64 import java.util.Map JavaDoc;
65 import java.util.Vector JavaDoc;
66
67 //for now extend BridgeFacesContext since there are so many 'instanceof' tests
68
public class BridgeFacesContext extends FacesContext {
69     private static final Log log = LogFactory.getLog(BridgeFacesContext.class);
70     private Application application;
71     private BridgeExternalContext externalContext;
72     private HashMap JavaDoc faceMessages = new HashMap JavaDoc();
73     private boolean renderResponse;
74     private boolean responseComplete;
75     private ResponseStream responseStream;
76     private ResponseWriter responseWriter;
77     private DOMSerializer domSerializer;
78     private UIViewRoot viewRoot;
79     private String JavaDoc iceFacesId;
80     private String JavaDoc viewNumber;
81     private CommandQueue commandQueue;
82     private Configuration configuration;
83
84     public BridgeFacesContext(BridgeExternalContext externalContext, String JavaDoc view, String JavaDoc icefacesID, CommandQueue commandQueue, Configuration configuration) {
85         setCurrentInstance(this);
86         this.externalContext = externalContext;
87         this.viewNumber = view;
88         this.iceFacesId = icefacesID;
89         this.commandQueue = commandQueue;
90         this.configuration = configuration;
91         this.application = ((ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY)).getApplication();
92         this.externalContext = externalContext;
93         this.switchToNormalMode();
94     }
95
96     public void setCurrentInstance() {
97         setCurrentInstance(this);
98     }
99
100     public Application getApplication() {
101         return application;
102     }
103
104     public void setApplication(Application application) {
105         this.application = application;
106     }
107
108     public Iterator JavaDoc getClientIdsWithMessages() {
109         return faceMessages.keySet().iterator();
110     }
111
112     public ExternalContext getExternalContext() {
113         return this.externalContext;
114     }
115
116     public void setExternalContext(ExternalContext externalContext) {
117         //do nothing
118
}
119
120     public ELContext getELContext() {
121         ELContext elContext = new ELContextImpl(application);
122         elContext.putContext(FacesContext.class, this);
123         UIViewRoot root = getViewRoot();
124         if (null != root) {
125             elContext.setLocale(root.getLocale());
126         }
127
128         return elContext;
129     }
130
131     public FacesMessage.Severity getMaximumSeverity() {
132         throw new UnsupportedOperationException JavaDoc();
133     }
134
135     /**
136      * gets all FacesMessages whether or not associatted with clientId.
137      *
138      * @return list of FacesMessages
139      */

140     public Iterator JavaDoc getMessages() {
141
142         // Jira #1358 The hashmap contains vectors of FacesMessages, not FacesMessages
143
// See following method.
144
ArrayList JavaDoc buffer = new ArrayList JavaDoc();
145         Iterator JavaDoc i = faceMessages.values().iterator();
146         while (i.hasNext()) {
147             buffer.addAll((Vector JavaDoc) i.next());
148         }
149
150         return buffer.iterator();
151     }
152
153     /**
154      * returns list of FacesMessages associated with a clientId. If client id is
155      * null, then return all FacesMessages which are not assocaited wih any
156      * clientId
157      *
158      * @param clientId
159      * @return list of FacesMessages
160      */

161     public Iterator JavaDoc getMessages(String JavaDoc clientId) {
162         try {
163             return ((Vector JavaDoc) faceMessages.get(clientId)).iterator();
164         } catch (NullPointerException JavaDoc e) {
165             if (log.isDebugEnabled()) {
166                 log.debug("Cannot find clientId " + clientId +
167                         "from facesMessages");
168             }
169             return Collections.EMPTY_LIST.iterator();
170         }
171     }
172
173     public RenderKit getRenderKit() {
174         UIViewRoot viewRoot = getViewRoot();
175         if (null == viewRoot) {
176             return (null);
177         }
178         String JavaDoc renderKitId = viewRoot.getRenderKitId();
179         if (null == renderKitId) {
180             return (null);
181         }
182
183         RenderKitFactory renderKitFactory = (RenderKitFactory)
184                 FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
185         RenderKit renderKit = renderKitFactory.getRenderKit(this, renderKitId);
186         return (renderKit);
187     }
188
189     public boolean getRenderResponse() {
190         return this.renderResponse;
191     }
192
193     public boolean getResponseComplete() {
194         return this.responseComplete;
195     }
196
197     public ResponseStream getResponseStream() {
198         return this.responseStream;
199     }
200
201     public void setResponseStream(ResponseStream responseStream) {
202         this.responseStream = responseStream;
203     }
204
205     public ResponseWriter getResponseWriter() {
206         return responseWriter;
207     }
208
209     public void setResponseWriter(ResponseWriter responseWriter) {
210         this.responseWriter = responseWriter;
211     }
212
213     public ResponseWriter createAndSetResponseWriter() throws IOException JavaDoc {
214         return responseWriter = new DOMResponseWriter(this, domSerializer, configuration);
215     }
216
217     public void switchToNormalMode() {
218         try {
219             domSerializer = new NormalModeSerializer(this, externalContext.getWriter("UTF-8"));
220         } catch (IOException JavaDoc e) {
221             throw new RuntimeException JavaDoc(e);
222         }
223     }
224
225     public void switchToPushMode() {
226         //todo: pull document in this class
227

228         // Jira #1330.
229
// Normally, just masking a null object just leads to
230
// a bunch of further null testing later. Except, at the time of writing,
231
// a) there is no (well, not much of a) later, and
232
// b) For the problem at hand, there's no easy way to create a Noop responseWriter
233
//
234
// The problem arises when Seam uses a Get request to logout. A Seam link tag
235
// is written with the actionMethod hack to get the Identity object to logout.
236
// As a result of the Get, a new ViewRoot is created, and in our code, the
237
// createAndSetResponseWriter method is not called until the renderResponse phase,
238
// but when the result of a Seam actionMethod hack is a redirect, renderResponse
239
// is not called, and the responseWriter will not have a value.
240
//
241
// Trying to create a Noop DomResponseWriter is problematic since the constructor
242
// of DRW does lots of initialization which needs something more than can
243
// be faked. Look in the initialize method in the DOMResponseWriter class
244
//
245
if (responseWriter != null) {
246             Document JavaDoc document = ((DOMResponseWriter) responseWriter).getDocument();
247             domSerializer = new PushModeSerializer(document, commandQueue);
248         }
249     }
250
251     public UIViewRoot getViewRoot() {
252         if (null == viewRoot) {
253             Map JavaDoc contextServletTable = D2DViewHandler.getContextServletTable(this);
254             if (null != contextServletTable) {
255                 viewRoot = (UIViewRoot) contextServletTable
256                         .get(DOMResponseWriter.RESPONSE_VIEWROOT);
257             }
258         }
259
260         return this.viewRoot;
261     }
262
263     public void setViewRoot(UIViewRoot viewRoot) {
264         //pointing this FacesContext to the new view
265
Map JavaDoc contextServletTable = D2DViewHandler.getContextServletTable(this);
266         if (null != contextServletTable) {
267             if (viewRoot != null) {
268                 contextServletTable
269                         .put(DOMResponseWriter.RESPONSE_VIEWROOT, viewRoot);
270             } else {
271                 contextServletTable.remove(DOMResponseWriter.RESPONSE_VIEWROOT);
272             }
273         }
274         responseWriter = null;
275         this.viewRoot = viewRoot;
276     }
277
278     public String JavaDoc getIceFacesId() {
279         return iceFacesId;
280     }
281
282     /**
283      * Return the unique identifier associated with each browser window
284      * associated with a single user.
285      */

286     public String JavaDoc getViewNumber() {
287         return viewNumber;
288     }
289
290     /**
291      * Return the id of the Element that currently has focus in the browser.
292      *
293      * @return String
294      */

295     public String JavaDoc getFocusId() {
296         Map JavaDoc map = externalContext.getRequestParameterMap();
297         return (String JavaDoc) (map.containsKey("focus") ? map.get("focus") : "");
298     }
299
300     /**
301      * Sets the id of the Element that should get focus in the browser.
302      */

303     public void setFocusId(String JavaDoc focusId) {
304         externalContext.getRequestParameterMap().put("focus", focusId);
305     }
306
307     /**
308      * add a FacesMessage to the set of message associated with the clientId, if
309      * clientId is not null.
310      *
311      * @param clientId
312      * @param message
313      */

314     public void addMessage(String JavaDoc clientId, FacesMessage message) {
315         if (message == null) {
316             throw new IllegalArgumentException JavaDoc("Message is null");
317         }
318         if (faceMessages.containsKey(clientId)) {
319             ((Vector JavaDoc) faceMessages.get(clientId)).addElement(message);
320         } else {
321             Vector JavaDoc vector = new Vector JavaDoc();
322             vector.add(message);
323             faceMessages.put(clientId, vector);
324         }
325     }
326
327     public void renderResponse() {
328         this.renderResponse = true;
329     }
330
331     public void responseComplete() {
332         this.responseComplete = true;
333     }
334
335     public void resetRenderResponse() {
336         this.renderResponse = false;
337     }
338
339     /**
340      * The release() found in FacesContextImpl is more comprehensive: since they
341      * blow away the context instance after a response, they null/false out much
342      * more than we do. We chose to keep the context instance around across
343      * requests so we need to keep some of our state intact.
344      */

345     public void release() {
346         faceMessages.clear();
347         renderResponse = false;
348         responseComplete = false;
349         setCurrentInstance(null);
350     }
351
352     public void dispose() {
353         String JavaDoc key = viewNumber + "/" + D2DViewHandler.DOM_CONTEXT_TABLE;
354         externalContext.getSessionMap().remove(key);
355     }
356
357     public void applyBrowserDOMChanges() {
358         if (responseWriter == null) return;
359         Document JavaDoc document = ((DOMResponseWriter) responseWriter).getDocument();
360         if (document == null) return;
361         Map JavaDoc parameters = externalContext.getRequestParameterValuesMap();
362
363         NodeList JavaDoc inputElements = document.getElementsByTagName("input");
364         int inputElementsLength = inputElements.getLength();
365         for (int i = 0; i < inputElementsLength; i++) {
366             Element JavaDoc inputElement = (Element JavaDoc) inputElements.item(i);
367             String JavaDoc id = inputElement.getAttribute("id");
368             if (!"".equals(id) && parameters.containsKey(id)) {
369                 String JavaDoc value = ((String JavaDoc[]) parameters.get(id))[0];
370                 inputElement.setAttribute("value", value);
371             }
372         }
373
374         NodeList JavaDoc textareaElements = document.getElementsByTagName("textarea");
375         int textareaElementsLength = textareaElements.getLength();
376         for (int i = 0; i < textareaElementsLength; i++) {
377             Element JavaDoc textareaElement = (Element JavaDoc) textareaElements.item(i);
378             String JavaDoc id = textareaElement.getAttribute("id");
379             if (!"".equals(id) && parameters.containsKey(id)) {
380                 String JavaDoc value = ((String JavaDoc[]) parameters.get(id))[0];
381                 textareaElement.getFirstChild()
382                         .setNodeValue(value);//set value on the Text node
383
}
384         }
385
386         NodeList JavaDoc selectElements = document.getElementsByTagName("select");
387         int selectElementsLength = selectElements.getLength();
388         for (int i = 0; i < selectElementsLength; i++) {
389             Element JavaDoc selectElement = (Element JavaDoc) selectElements.item(i);
390             String JavaDoc id = selectElement.getAttribute("id");
391             if (!"".equals(id) && parameters.containsKey(id)) {
392                 List JavaDoc values = Arrays.asList((String JavaDoc[]) parameters.get(id));
393
394                 NodeList JavaDoc optionElements =
395                         selectElement.getElementsByTagName("option");
396                 int optionElementsLength = optionElements.getLength();
397                 for (int j = 0; j < optionElementsLength; j++) {
398                     Element JavaDoc optionElement = (Element JavaDoc) optionElements.item(j);
399                     if (values.contains(optionElement.getAttribute("value"))) {
400                         optionElement.setAttribute("selected", "selected");
401                     } else {
402                         optionElement.removeAttribute("selected");
403                     }
404                 }
405             }
406         }
407     }
408 }
409
Popular Tags