KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > gui > dialog > DialogControlImpl


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.gui.dialog;
14
15 import info.magnolia.cms.core.Content;
16 import info.magnolia.cms.core.ItemType;
17 import info.magnolia.cms.core.NodeData;
18 import info.magnolia.cms.i18n.Messages;
19 import info.magnolia.cms.i18n.MessagesUtil;
20 import info.magnolia.cms.i18n.TemplateMessagesUtil;
21 import info.magnolia.cms.util.AlertUtil;
22 import info.magnolia.cms.util.ContentUtil;
23 import info.magnolia.cms.util.RequestFormUtil;
24
25 import java.io.IOException JavaDoc;
26 import java.io.Writer JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.jcr.PathNotFoundException;
35 import javax.jcr.RepositoryException;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletResponse JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import org.apache.commons.lang.BooleanUtils;
41 import org.apache.commons.lang.StringUtils;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45
46 /**
47  * @author Vinzenz Wyser
48  * @version 2.0
49  */

50 public abstract class DialogControlImpl implements DialogControl {
51
52     private static final String JavaDoc I18N_BASENAME_PROPERTY = "i18nBasename";
53
54     public static final String JavaDoc SESSION_ATTRIBUTENAME_DIALOGOBJECT = "mgnlSessionAttribute"; //$NON-NLS-1$
55

56     public static final String JavaDoc SESSION_ATTRIBUTENAME_DIALOGOBJECT_REMOVE = "mgnlSessionAttributeRemove"; //$NON-NLS-1$
57

58     /**
59      * Logger.
60      */

61     private static Logger log = LoggerFactory.getLogger(DialogControlImpl.class);
62
63     /**
64      * Current request.
65      */

66     private HttpServletRequest JavaDoc request;
67
68     /**
69      * Current response.
70      */

71     private HttpServletResponse JavaDoc response;
72
73     /**
74      * content data.
75      */

76     private Content websiteNode;
77
78     /**
79      * config data.
80      */

81     private Map JavaDoc config = new Hashtable JavaDoc();
82
83     /**
84      * Sub controls.
85      */

86     private List JavaDoc subs = new ArrayList JavaDoc();
87
88     /**
89      * options (radio, checkbox...).
90      */

91     private List JavaDoc options = new ArrayList JavaDoc();
92
93     /**
94      * The id is used to make the controls unic. Used by the javascripts. This is not a configurable value. See method
95      * set and getName().
96      */

97     private String JavaDoc id = "mgnlControl"; //$NON-NLS-1$
98

99     protected String JavaDoc value;
100
101     /**
102      * multiple values, e.g. checkbox.
103      */

104     private List JavaDoc values;
105
106     private DialogControlImpl parent;
107
108     private DialogControlImpl topParent;
109
110     /**
111      * Used if this control has its own message bundle defined or if this is the dialog object itself. Use getMessages
112      * method to get the object for a control.
113      */

114     private Messages messages;
115
116     /**
117      */

118     public void init(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Content websiteNode, Content configNode)
119         throws RepositoryException {
120
121         if (log.isDebugEnabled()) {
122             log.debug("Init " + getClass().getName()); //$NON-NLS-1$
123
}
124
125         this.websiteNode = websiteNode;
126         this.request = request;
127         this.response = response;
128
129         this.initializeConfig(configNode);
130     }
131
132     /**
133      * @see info.magnolia.cms.gui.dialog.DialogControl#drawHtml(Writer)
134      */

135     public void drawHtml(Writer JavaDoc out) throws IOException JavaDoc {
136         this.drawHtmlPreSubs(out);
137         this.drawSubs(out);
138         this.drawHtmlPostSubs(out);
139     }
140
141     public void addSub(Object JavaDoc o) {
142         this.getSubs().add(o);
143     }
144
145     public void setConfig(String JavaDoc key, String JavaDoc value) {
146         if (value != null) {
147             this.config.put(key, value);
148         }
149     }
150
151     public void setConfig(String JavaDoc key, boolean value) {
152         this.config.put(key, BooleanUtils.toBooleanObject(value).toString());
153     }
154
155     public void setConfig(String JavaDoc key, int value) {
156         this.config.put(key, Integer.toString(value));
157     }
158
159     public String JavaDoc getConfigValue(String JavaDoc key, String JavaDoc nullValue) {
160         if (this.config.containsKey(key)) {
161             return (String JavaDoc) this.config.get(key);
162         }
163
164         return nullValue;
165     }
166
167     public String JavaDoc getConfigValue(String JavaDoc key) {
168         return this.getConfigValue(key, StringUtils.EMPTY);
169     }
170
171     public void setValue(String JavaDoc s) {
172         this.value = s;
173     }
174
175     public String JavaDoc getValue() {
176         if (this.value == null) {
177             if (this.getWebsiteNode() != null) {
178                 this.value = readValue();
179                 if(this instanceof UUIDDialogControl){
180                     String JavaDoc repository = ((UUIDDialogControl)this).getRepository();
181                     this.value = ContentUtil.uuid2path(repository, this.value);
182                 }
183             }
184             RequestFormUtil params = new RequestFormUtil(request);
185             if (params.getParameter(this.getName()) != null) {
186                 this.value = params.getParameter(this.getName());
187             }
188
189             if (this.value == null && StringUtils.isNotEmpty(getConfigValue("defaultValue"))) {
190                 return this.getMessage(this.getConfigValue("defaultValue"));
191             }
192
193             if (this.value == null) {
194                 this.value = StringUtils.EMPTY;
195             }
196         }
197         return this.value;
198     }
199
200     protected String JavaDoc readValue() {
201         return this.getWebsiteNode().getNodeData(this.getName()).getString();
202     }
203
204     public void setSaveInfo(boolean b) {
205         this.setConfig("saveInfo", b); //$NON-NLS-1$
206
}
207
208     /**
209      * Set the name of this control. This is not the same value as the id setted by the parent. In common this value is
210      * setted in the dialog configuration.
211      * @param the name
212      */

213     public void setName(String JavaDoc s) {
214         this.setConfig("name", s); //$NON-NLS-1$
215
}
216
217     /**
218      * Return the configured name of this control (not the id).
219      * @return the name
220      */

221     public String JavaDoc getName() {
222         return this.getConfigValue("name"); //$NON-NLS-1$
223
}
224
225     public void addOption(Object JavaDoc o) {
226         this.getOptions().add(o);
227     }
228
229     public Content getWebsiteNode() {
230         return this.websiteNode;
231     }
232
233     public void setLabel(String JavaDoc s) {
234         this.config.put("label", s); //$NON-NLS-1$
235
}
236
237     public void setDescription(String JavaDoc s) {
238         this.config.put("description", s); //$NON-NLS-1$
239
}
240
241     public void removeSessionAttribute() {
242         String JavaDoc name = this.getConfigValue(SESSION_ATTRIBUTENAME_DIALOGOBJECT);
243         HttpServletRequest JavaDoc request = this.getRequest();
244         if (request == null) {
245             request = this.getTopParent().getRequest();
246         }
247         try {
248             HttpSession JavaDoc httpsession = request.getSession(false);
249             if (httpsession != null) {
250                 httpsession.removeAttribute(name);
251             }
252         }
253         catch (Exception JavaDoc e) {
254             if (log.isDebugEnabled()) {
255                 log.debug("removeSessionAttribute() for " + name + " failed because this.request is null"); //$NON-NLS-1$ //$NON-NLS-2$
256
}
257         }
258     }
259
260     public HttpServletRequest JavaDoc getRequest() {
261         return this.request;
262     }
263
264     public void setOptions(List JavaDoc options) {
265         this.options = options;
266     }
267
268     protected void drawHtmlPreSubs(Writer JavaDoc out) throws IOException JavaDoc {
269         // do nothing
270
}
271
272     protected void drawSubs(Writer JavaDoc out) throws IOException JavaDoc {
273         Iterator JavaDoc it = this.getSubs().iterator();
274         int i = 0;
275         while (it.hasNext()) {
276             // use underscore (not divis)! could be used as js variable names
277
String JavaDoc dsId = this.getId() + "_" + i; //$NON-NLS-1$
278

279             DialogControlImpl ds = (DialogControlImpl) it.next();
280             ds.setId(dsId);
281             ds.setParent(this);
282             if (this.getParent() == null) {
283                 this.setTopParent(this);
284             }
285             ds.setTopParent(this.getTopParent());
286             ds.drawHtml(out);
287             i++;
288         }
289     }
290
291     protected void drawHtmlPostSubs(Writer JavaDoc out) throws IOException JavaDoc {
292         // do nothing
293
}
294
295     public DialogControlImpl getParent() {
296         return this.parent;
297     }
298
299     protected void setTopParent(DialogControlImpl top) {
300         this.topParent = top;
301     }
302
303     public DialogControlImpl getTopParent() {
304         return this.topParent;
305     }
306
307     public List JavaDoc getSubs() {
308         return this.subs;
309     }
310
311     /**
312      * Find a control by its name
313      * @param name the name of the control to find
314      * @return the found control or null
315      */

316     public DialogControlImpl getSub(String JavaDoc name) {
317         DialogControlImpl found;
318         for (Iterator JavaDoc iter = subs.iterator(); iter.hasNext();) {
319             Object JavaDoc control = iter.next();
320
321             // could be an implementation of DialogControl only
322
if (control instanceof DialogControlImpl) {
323                 if (StringUtils.equals(((DialogControlImpl) control).getName(), name)) {
324                     return (DialogControlImpl) control;
325                 }
326                 found = ((DialogControlImpl) control).getSub(name);
327                 if (found != null) {
328                     return found;
329                 }
330             }
331         }
332         return null;
333     }
334
335     protected HttpServletResponse JavaDoc getResponse() {
336         return this.response;
337     }
338
339     /**
340      * @deprecated websitenode should only be set in init(), this is a workaround used in DialogDate
341      */

342     protected void clearWebsiteNode() {
343         this.websiteNode = null;
344     }
345
346     public String JavaDoc getId() {
347         return this.id;
348     }
349
350     public String JavaDoc getLabel() {
351         return this.getConfigValue("label", StringUtils.EMPTY); //$NON-NLS-1$
352
}
353
354     public String JavaDoc getDescription() {
355         return this.getConfigValue("description", StringUtils.EMPTY); //$NON-NLS-1$
356
}
357
358     public List JavaDoc getOptions() {
359         return this.options;
360     }
361
362     public List JavaDoc getValues() {
363         if (this.values == null) {
364             this.values = readValues();
365             
366             if(this instanceof UUIDDialogControl){
367                 String JavaDoc repository = ((UUIDDialogControl)this).getRepository();
368                 List JavaDoc pathes = new ArrayList JavaDoc();
369                 for (Iterator JavaDoc iter = this.values.iterator(); iter.hasNext();) {
370                     String JavaDoc uuid = (String JavaDoc) iter.next();
371                     String JavaDoc path = ContentUtil.uuid2path(repository, uuid);
372                     pathes.add(path);
373                 }
374                 this.values = pathes;
375             }
376
377             if (request != null) {
378                 RequestFormUtil params = new RequestFormUtil(request);
379                 String JavaDoc[] values = params.getParameterValues(this.getName());
380                 if (values != null && values.length > 0) {
381                     this.values.clear();
382                     for (int i = 0; i < values.length; i++) {
383                         String JavaDoc value = values[i];
384                         this.values.add(value);
385                     }
386                 }
387             }
388         }
389
390         return this.values;
391     }
392
393     protected List JavaDoc readValues() {
394         List JavaDoc values = new ArrayList JavaDoc();
395         if (this.getWebsiteNode() != null) {
396             try {
397                 Iterator JavaDoc it = this.getWebsiteNode().getContent(this.getName()).getNodeDataCollection().iterator();
398                 while (it.hasNext()) {
399                     NodeData data = (NodeData) it.next();
400                     values.add(data.getString());
401                 }
402             }
403             catch (PathNotFoundException e) {
404                 // not yet existing: OK
405
}
406             catch (RepositoryException re) {
407                 log.error("can't set values", re);
408             }
409         }
410         return values;
411     }
412
413     /**
414      * This method sets a control into the session
415      */

416     public void setSessionAttribute() {
417         String JavaDoc name = SESSION_ATTRIBUTENAME_DIALOGOBJECT + "_" + this.getName() + "_" + new Date JavaDoc().getTime(); //$NON-NLS-1$ //$NON-NLS-2$
418
this.setConfig(SESSION_ATTRIBUTENAME_DIALOGOBJECT, name);
419         HttpServletRequest JavaDoc request = this.getRequest();
420         if (request == null) {
421             request = this.getTopParent().getRequest();
422         }
423         try {
424
425             // @todo IMPORTANT remove use of http session
426
HttpSession JavaDoc httpsession = request.getSession(true);
427             httpsession.setAttribute(name, this);
428         }
429         catch (Exception JavaDoc e) {
430             log.error("setSessionAttribute() for " + name + " failed because this.request is null"); //$NON-NLS-1$ //$NON-NLS-2$
431
}
432     }
433
434     private void setId(String JavaDoc id) {
435         this.id = id;
436     }
437
438     private void initializeConfig(Content configNodeParent) throws RepositoryException {
439         // create config and subs out of dialog structure
440
Map JavaDoc config = new Hashtable JavaDoc();
441
442         if (configNodeParent == null) {
443             // can happen only if Dialog is instantiated directly
444
return;
445         }
446
447         // get properties -> to this.config
448
Iterator JavaDoc itProps = configNodeParent.getNodeDataCollection().iterator();
449         while (itProps.hasNext()) {
450             NodeData data = (NodeData) itProps.next();
451             String JavaDoc name = data.getName();
452             String JavaDoc value = data.getString();
453             config.put(name, value);
454         }
455
456         // name is usually mandatory, use node name if a name property is not set
457
if (!config.containsKey("name")) {
458             config.put("name", configNodeParent.getName());
459         }
460
461         this.config = config;
462
463         Iterator JavaDoc it = configNodeParent.getChildren(ItemType.CONTENTNODE).iterator();
464         while (it.hasNext()) {
465             Content configNode = (Content) it.next();
466             String JavaDoc controlType = configNode.getNodeData("controlType").getString(); //$NON-NLS-1$
467

468             if (StringUtils.isEmpty(controlType)) {
469                 String JavaDoc name = configNode.getName();
470                 if (!name.startsWith("options")) { //$NON-NLS-1$
471
log.warn("Missing control type for configNode " + name); //$NON-NLS-1$
472
}
473                 return;
474             }
475
476             if (log.isDebugEnabled()) {
477                 log.debug("Loading control \"" + controlType + "\" for " + configNode.getHandle()); //$NON-NLS-1$ //$NON-NLS-2$
478
}
479             DialogControl dialogControl = DialogFactory
480                 .loadDialog(request, response, this.getWebsiteNode(), configNode);
481             this.addSub(dialogControl);
482         }
483     }
484
485     private void setParent(DialogControlImpl parent) {
486         this.parent = parent;
487     }
488
489     /**
490      * Get the AbstractMessagesImpl object for this dialog/control. It checks first if there was a bundle defined
491      * <code>i18nBasename</code>, then it tries to find the parent with the first definition.
492      * @return
493      */

494     protected Messages getMessages() {
495         if (messages == null) {
496             // if this is the root
497
if (this.getParent() == null) {
498                 messages = TemplateMessagesUtil.getMessages();
499             }
500             else {
501                 // try to get it from the control nearest to the root
502
messages = this.getParent().getMessages();
503             }
504             // if this control defines a bundle (basename in the terms of jstl)
505
String JavaDoc basename = this.getConfigValue(I18N_BASENAME_PROPERTY);
506             if (StringUtils.isNotEmpty(basename)) {
507                 // extend the chain with this bundle
508
messages = MessagesUtil.chain(basename, messages);
509             }
510         }
511         return messages;
512     }
513
514     /**
515      * Get the message.
516      * @param key key
517      * @return message
518      */

519     public String JavaDoc getMessage(String JavaDoc key) {
520         return this.getMessages().getWithDefault(key, key);
521     }
522
523     /**
524      * Get the message with replacement strings. Use the {nr} syntax
525      * @param key key
526      * @param args replacement strings
527      * @return message
528      */

529     public String JavaDoc getMessage(String JavaDoc key, Object JavaDoc[] args) {
530         return this.getMessages().getWithDefault(key, args, key);
531     }
532
533     /**
534      * If the validation fails the code will set a message in the context using the AlertUtil.
535      * @return true if valid
536      */

537     public boolean validate() {
538         if (this.isRequired()) {
539             if (StringUtils.isEmpty(this.getValue()) && this.getValues().size() == 0) {
540                 String JavaDoc name = this.getMessage(this.getLabel());
541                 AlertUtil.setMessage(this.getMessage("dialogs.validation.required", new Object JavaDoc[]{name}));
542                 return false;
543             }
544         }
545         for (Iterator JavaDoc iter = this.getSubs().iterator(); iter.hasNext();) {
546             DialogControl sub = (DialogControl) iter.next();
547             if (sub instanceof DialogControlImpl) {
548                 if (!((DialogControlImpl) sub).validate()) {
549                     return false;
550                 }
551             }
552
553         }
554         return true;
555     }
556
557     /**
558      * True if a value is required. Set it in the configuration
559      * @return
560      */

561     public boolean isRequired() {
562         if (BooleanUtils.toBoolean(this.getConfigValue("required"))) {
563             return true;
564         }
565         return false;
566     }
567
568     public void setRequired(boolean required) {
569         this.setConfig("required", BooleanUtils.toStringTrueFalse(required));
570     }
571
572 }
573
Popular Tags