KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > icesoft > faces > component > panelpositioned > PanelPositionedRenderer


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
34 package com.icesoft.faces.component.panelpositioned;
35
36 import com.icesoft.faces.component.panelseries.UISeries;
37 import com.icesoft.faces.context.DOMContext;
38 import com.icesoft.faces.context.effects.EffectsArguments;
39 import com.icesoft.faces.context.effects.JavascriptContext;
40 import com.icesoft.faces.renderkit.dom_html_basic.DomBasicRenderer;
41 import com.icesoft.faces.renderkit.dom_html_basic.HTML;
42 import com.icesoft.faces.utils.DnDCache;
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45 import org.w3c.dom.Element JavaDoc;
46 import org.w3c.dom.Node JavaDoc;
47
48 import javax.faces.component.NamingContainer;
49 import javax.faces.component.UIComponent;
50 import javax.faces.component.UIViewRoot;
51 import javax.faces.context.FacesContext;
52 import java.beans.Beans JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.util.ArrayList JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.List JavaDoc;
57 import java.util.Map JavaDoc;
58 import java.util.Random JavaDoc;
59 import java.util.StringTokenizer JavaDoc;
60
61 /**
62  * Renderer for Positioned Panel
63  */

64 public class PanelPositionedRenderer extends DomBasicRenderer {
65
66     private static Log log = LogFactory.getLog(PanelPositionedRenderer.class);
67
68     private static final String JavaDoc INPUT_ID = "colOrder";
69
70
71     public boolean getRendersChildren() {
72         return true;
73     }
74
75     public void encodeBegin(FacesContext facesContext, UIComponent uiComponent)
76             throws IOException JavaDoc {
77
78         try {
79             DOMContext domContext =
80                     DOMContext.attachDOMContext(facesContext, uiComponent);
81             if (!domContext.isInitialized()) {
82                 Element JavaDoc root = domContext.createRootElement(HTML.DIV_ELEM);
83                 domContext.setRootNode(root);
84                 setRootElementId(facesContext, root, uiComponent);
85
86
87                 String JavaDoc style = ((PanelPositioned) uiComponent).getStyle();
88                 String JavaDoc styleClass =
89                         ((PanelPositioned) uiComponent).getStyleClass();
90                 if(style != null && style.length() > 0)
91                     root.setAttribute(HTML.STYLE_ATTR, style);
92                 else
93                     root.removeAttribute(HTML.STYLE_ATTR);
94                 if (styleClass != null && styleClass.length() > 0)
95                     root.setAttribute(HTML.CLASS_ATTR, styleClass);
96                 else
97                     root.removeAttribute(HTML.CLASS_ATTR);
98                 Element JavaDoc orderField = domContext.createElement(HTML.INPUT_ELEM);
99                 String JavaDoc orderFieldId =
100                         getHiddenFieldName(facesContext, uiComponent, INPUT_ID);
101                 orderField.setAttribute(HTML.ID_ATTR, orderFieldId);
102                 orderField.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN);
103                 orderField.setAttribute(HTML.NAME_ATTR, orderFieldId);
104                 orderField.setAttribute(HTML.VALUE_ATTR, "");
105
106                 if (isChanged(facesContext)) {
107                     // Force the re rendering of the entire component. This is due to a strange quick with positioned
108
// panel. When an element is moved in the same list then it container element moves with it
109
// When the update occurs the elements are replaced but because the containers have moved
110
// then the result looks the same. (But a refresh shows otherwise)
111
Node JavaDoc node = domContext.createTextNode(
112                             "<!-- " + (new Random JavaDoc().nextInt(1000)) + "-->");
113                     root.appendChild(node);
114                 }
115                 root.appendChild(orderField);
116
117             }
118
119             Element JavaDoc root = (Element JavaDoc) domContext.getRootNode();
120             if (!Beans.isDesignTime()) {
121                 DOMContext.removeChildrenByTagName(root, HTML.DIV_ELEM);
122             }
123             domContext.streamWrite(facesContext, uiComponent);
124         } catch (Exception JavaDoc e) {
125             log.error("Encode Begin", e);
126         }
127     }
128
129     public void encodeEnd(FacesContext facesContext, UIComponent uiComponent)
130             throws IOException JavaDoc {
131         validateParameters(facesContext, uiComponent, null);
132         DOMContext domContext =
133                 DOMContext.getDOMContext(facesContext, uiComponent);
134         String JavaDoc id = uiComponent.getClientId(facesContext);
135         PanelPositioned panelPositioned = (PanelPositioned) uiComponent;
136         String JavaDoc orderFieldId =
137                 getHiddenFieldName(facesContext, uiComponent, INPUT_ID);
138         EffectsArguments ea = new EffectsArguments();
139         ea.add("tag", "div");
140         String JavaDoc o = panelPositioned.getConstraint();
141         if (o == null) {
142             ea.add("constraint", false);
143         } else {
144             ea.add("constraint", panelPositioned.getConstraint());
145         }
146         ea.add("dropOnEmpty", true);
147         ea.add("containment", false);
148         o = panelPositioned.getHandle();
149         if (o != null) {
150             ea.add("handle", o);
151         }
152         o = panelPositioned.getHoverclass();
153         if (o != null) {
154             ea.add("hoverclass", o);
155         }
156         o = panelPositioned.getOverlap();
157         if (o != null) {
158             ea.add("overlap", o);
159         }
160
161
162         String JavaDoc updateCode =
163                 "function(){var o = Sortable.options('" + id + "');" +
164                 "var s = o.serializeValue;" +
165                 "f = $('" + orderFieldId + "');" +
166                 "f.value = s;" +
167                 "}";
168         ea.addFunction("onUpdate", updateCode);
169
170         String JavaDoc call = "Sortable.create('" + id + "'" + ea.toString();
171
172
173         JavascriptContext.addJavascriptCall(facesContext, call);
174         DOMContext.getDOMContext(facesContext, uiComponent).stepOver();
175         domContext.streamWrite(facesContext, uiComponent);
176
177     }
178
179
180     public void encodeChildren(FacesContext facesContext,
181                                UIComponent uiComponent)
182             throws IOException JavaDoc {
183         try {
184             validateParameters(facesContext, uiComponent, null);
185             DOMContext domContext =
186                     DOMContext.attachDOMContext(facesContext, uiComponent);
187
188             Element JavaDoc root = (Element JavaDoc) domContext.getRootNode();
189             UISeries series = (UISeries) uiComponent;
190             List JavaDoc seriesList = (List JavaDoc) series.getValue();
191             if (seriesList != null) {
192                 if (log.isTraceEnabled()) {
193                     for (int i = 0; i < seriesList.size(); i++) {
194                         log.trace("Encode index[" + i + "] value [" +
195                                   seriesList.get(i) + "]");
196                     }
197                 }
198                 Iterator JavaDoc cells = seriesList.iterator();
199                 int index = 0;
200                 PanelPositionedModel ppm = PanelPositionedModel
201                         .resetInstance(facesContext, uiComponent);
202                 while (cells.hasNext()) {
203                     series.setRowIndex(index);
204                     Object JavaDoc cell = cells.next();
205
206
207                     Iterator JavaDoc childs;
208                     childs = uiComponent.getChildren().iterator();
209                     while (childs.hasNext()) {
210                         UIComponent nextChild = (UIComponent) childs.next();
211                         if (nextChild.isRendered()) {
212                             domContext.setCursorParent(root);
213                             domContext.streamWrite(facesContext, uiComponent,
214                                                    root,
215                                                    root);
216                             encodeParentAndChildren(facesContext, nextChild);
217                             String JavaDoc childId =
218                                     nextChild.getClientId(facesContext);
219
220                             ppm.setIndex(childId, index);
221                             DnDCache.getInstance(facesContext, false)
222                                     .putPositionPanelValue(childId, seriesList,
223                                                            index);
224                         }
225                     }
226                     index++;
227                 }
228                 series.setRowIndex(-1);
229             }
230             // set the cursor here since nothing happens in encodeEnd
231
domContext.setCursorParent(root);
232         } catch (Exception JavaDoc e) {
233             log.error("Encode Children", e);
234         }
235     }
236
237     public void decode(FacesContext context, UIComponent component) {
238
239         try {
240             super.decode(context, component);
241
242             if (component instanceof PanelPositioned) {
243                 Map JavaDoc requestParameters =
244                         context.getExternalContext().getRequestParameterMap();
245                 PanelPositioned uiSeries = (PanelPositioned) component;
246                 PanelPositionedModel sortOrder =
247                         PanelPositionedModel.getInstance(context, component);
248
249                 String JavaDoc baseName =
250                         getHiddenFieldName(context, component, INPUT_ID);
251                 Iterator JavaDoc names = requestParameters.keySet().iterator();
252                 names = requestParameters.keySet().iterator();
253
254                 while (names.hasNext()) {
255                     String JavaDoc name = (String JavaDoc) names.next();
256                     int lastIndex = -1;
257                     if (name.equals(baseName)) {
258                         String JavaDoc value = (String JavaDoc) requestParameters.get(name);
259
260                         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(value, ";");
261                         Object JavaDoc o = uiSeries.getValue();
262                         List JavaDoc newList = new ArrayList JavaDoc();
263                         List JavaDoc oldList = null;
264
265                         if (o instanceof List JavaDoc) {
266                             oldList = (List JavaDoc) o;
267                         } else {
268                             throw new RuntimeException JavaDoc(
269                                     "PanelPositioned must have a java.util.List instance set as " +
270                                     "its value");
271                         }
272                         if (st.hasMoreTokens()) { // Don't do a thing if its blank
273
st.nextToken();//Last Token
274
String JavaDoc last = st.nextToken(); //Last ID dragged
275

276                             lastIndex = sortOrder.getIndex(last);
277
278                             String JavaDoc s = st.nextToken(); // Third token is always the keyword 'changed' used to indicate this filed has changed. (Even if its blank now)
279

280
281                             int currentIndex = 0;
282
283                             while (st.hasMoreTokens()) {
284                                 String JavaDoc id = st.nextToken();
285                                
286                                 int index = sortOrder.getIndex(id);
287
288                                 if (index != -1) {
289                                     Object JavaDoc obj = oldList.get(index);
290                                     if (log.isTraceEnabled()) {
291                                         log.trace("Moving ID[" + id +
292                                                   "] Value [" + obj.toString() +
293                                                   "] from index [" +
294                                                   index + "] to [" +
295                                                   currentIndex + "]");
296                                     }
297                                     newList.add(obj);
298
299                                 } else {
300                                     // Value is not from this list, check the cache
301
PanelPositionedValue ppv =
302                                             DnDCache.getInstance(context, false)
303                                                     .getPositionedPanelValue(
304                                                             id);
305                                     if (ppv != null) {
306                                         List JavaDoc source = ppv.getSourceList();
307                                         Object JavaDoc sourceValue =
308                                                 source.get(ppv.getValueIndex());
309                                         if (log.isTraceEnabled()) {
310                                             log.trace("Added value [" +
311                                                       sourceValue + "]");
312                                         }
313                                         newList.add(sourceValue);
314
315                                     } else {
316                                         throw new RuntimeException JavaDoc(
317                                                 "Unable to find Value for ID[" +
318                                                 id + "]");
319                                     }
320
321
322                                 }
323                                 currentIndex++;
324                             }
325                             int[] eventInfo = getEventInfo(oldList, newList);
326                             int event_type = eventInfo[0];
327                             int newIndex = eventInfo[1];
328                             int oldIndex = eventInfo[2];
329                             if(event_type == PanelPositionedEvent.TYPE_MOVE){
330
331                                 if(lastIndex != oldIndex){
332                                     int a = newIndex;
333                                     newIndex = oldIndex;
334                                     oldIndex = a;
335
336                                 }
337                             }
338                           
339                           
340
341
342                             if (log.isTraceEnabled()) {
343                                 for (int i = 0; i < newList.size(); i++) {
344
345                                     log.trace("New Index [" + i + "] Value [" +
346                                             newList.get(i) + "]");
347
348                                 }
349                             }
350                             setChanged(context);
351
352
353                             if (uiSeries.getListener() != null) {
354                                 uiSeries.queueEvent(new PanelPositionedEvent(
355                                         component, uiSeries.getListener(),
356                                         event_type, newIndex, oldIndex, oldList, newList));
357                             }
358
359                         }
360
361                     }
362                 }
363             }
364         } catch (Exception JavaDoc e) {
365             log.error("Decode Error Positioned Panel ", e);
366         }
367     }
368
369     private void setChanged(FacesContext context) {
370         context.getExternalContext().getRequestMap()
371                 .put(PanelPositionedRenderer.class.getName(), Boolean.TRUE);
372     }
373
374     private boolean isChanged(FacesContext context) {
375         Boolean JavaDoc b = (Boolean JavaDoc) context.getExternalContext().getRequestMap()
376                 .get(PanelPositionedRenderer.class.getName());
377         if (b != null && b.booleanValue()) {
378             return true;
379         }
380         return false;
381     }
382
383
384     private String JavaDoc getHiddenFieldName
385             (FacesContext
386                     facesContext, UIComponent
387                     uiComponent, String JavaDoc
388                     name) {
389         UIComponent form = findForm(uiComponent);
390         if(form == null){
391             throw new NullPointerException JavaDoc("PanelPositioned must be contained withing an <ice:form>");
392         }
393         String JavaDoc formId = form.getClientId(facesContext);
394         String JavaDoc clientId = uiComponent.getClientId(facesContext);
395         return formId
396                + NamingContainer.SEPARATOR_CHAR
397                + UIViewRoot.UNIQUE_ID_PREFIX
398                + clientId
399                + name;
400     }
401
402     private int[] getEventInfo(List JavaDoc l1, List JavaDoc l2){
403         int type;
404         int newIndex = -1;
405         int oldIndex = -1;
406         if(l1.size() > l2.size()){
407             type = PanelPositionedEvent.TYPE_REMOVE;
408         }else if(l1.size() < l2.size()){
409             type = PanelPositionedEvent.TYPE_ADD;
410             List JavaDoc l = l1;
411             l1 = l2;
412             l2 = l;
413         }else{
414             type = PanelPositionedEvent.TYPE_MOVE;
415             for(int i = 0; i < l1.size(); i++){
416                 if(l1.get(i) != l2.get(i)){
417                     if(newIndex == -1)newIndex = i;
418                     else oldIndex = i;
419                 }
420             }
421         }
422         if(type != PanelPositionedEvent.TYPE_MOVE){
423             for(int i = 0; i < l1.size(); i++){
424                 // Find the odd one
425
if(!l2.contains(l1.get(i))){
426                     newIndex = i;
427                 }
428             }
429         }
430         return new int[]{type, newIndex, oldIndex};
431     }
432
433
434 }
435
Popular Tags