View Javadoc
1   /*
2    * Copyright (C) 2003-2008 eXo Platform SAS.
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Affero General Public License
6    * as published by the Free Software Foundation; either version 3
7    * of the License, or (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program; if not, see<http://www.gnu.org/licenses/>.
16   */
17  package org.exoplatform.ecm.webui.form;
18  
19  import java.io.InputStream;
20  import java.io.Writer;
21  import java.text.DateFormat;
22  import java.text.SimpleDateFormat;
23  import java.util.ArrayList;
24  import java.util.Arrays;
25  import java.util.Calendar;
26  import java.util.GregorianCalendar;
27  import java.util.HashMap;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.MissingResourceException;
33  import java.util.ResourceBundle;
34  import java.util.Set;
35  
36  import javax.jcr.ItemNotFoundException;
37  import javax.jcr.Node;
38  import javax.jcr.NodeIterator;
39  import javax.jcr.PathNotFoundException;
40  import javax.jcr.PropertyType;
41  import javax.jcr.RepositoryException;
42  import javax.jcr.Session;
43  import javax.jcr.Value;
44  import javax.jcr.ValueFormatException;
45  import javax.jcr.lock.LockException;
46  
47  import org.apache.commons.lang.StringUtils;
48  import org.exoplatform.commons.utils.IOUtil;
49  import org.exoplatform.download.DownloadService;
50  import org.exoplatform.download.InputStreamDownloadResource;
51  import org.exoplatform.ecm.resolver.JCRResourceResolver;
52  import org.exoplatform.ecm.webui.core.fckconfig.FCKConfigService;
53  import org.exoplatform.ecm.webui.core.fckconfig.FCKEditorContext;
54  import org.exoplatform.ecm.webui.form.field.UIFormActionField;
55  import org.exoplatform.ecm.webui.form.field.UIFormCalendarField;
56  import org.exoplatform.ecm.webui.form.field.UIFormCheckBoxField;
57  import org.exoplatform.ecm.webui.form.field.UIFormHiddenField;
58  import org.exoplatform.ecm.webui.form.field.UIFormRadioBoxField;
59  import org.exoplatform.ecm.webui.form.field.UIFormRichtextField;
60  import org.exoplatform.ecm.webui.form.field.UIFormSelectBoxField;
61  import org.exoplatform.ecm.webui.form.field.UIFormTextAreaField;
62  import org.exoplatform.ecm.webui.form.field.UIFormTextField;
63  import org.exoplatform.ecm.webui.form.field.UIFormUploadField;
64  import org.exoplatform.ecm.webui.form.field.UIFormWYSIWYGField;
65  import org.exoplatform.ecm.webui.form.field.UIMixinField;
66  import org.exoplatform.ecm.webui.form.validator.UploadFileMimeTypesValidator;
67  import org.exoplatform.ecm.webui.utils.DialogFormUtil;
68  import org.exoplatform.ecm.webui.utils.JCRExceptionManager;
69  import org.exoplatform.ecm.utils.lock.LockUtil;
70  import org.exoplatform.ecm.webui.utils.Utils;
71  import org.exoplatform.portal.webui.util.Util;
72  import org.exoplatform.services.cms.BasePath;
73  import org.exoplatform.services.cms.JcrInputProperty;
74  import org.exoplatform.services.cms.impl.DMSConfiguration;
75  import org.exoplatform.services.cms.scripts.CmsScript;
76  import org.exoplatform.services.cms.scripts.ScriptService;
77  import org.exoplatform.services.cms.templates.TemplateService;
78  import org.exoplatform.services.jcr.RepositoryService;
79  import org.exoplatform.services.jcr.core.ManageableRepository;
80  import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator;
81  import org.exoplatform.services.jcr.util.Text;
82  import org.exoplatform.services.log.ExoLogger;
83  import org.exoplatform.services.log.Log;
84  import org.exoplatform.services.wcm.core.NodetypeConstant;
85  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
86  import org.exoplatform.webui.form.UIFormRichtextInput;
87  import org.exoplatform.web.application.ApplicationMessage;
88  import org.exoplatform.web.application.RequestContext;
89  import org.exoplatform.webui.application.WebuiRequestContext;
90  import org.exoplatform.webui.config.annotation.ComponentConfig;
91  import org.exoplatform.webui.config.annotation.ComponentConfigs;
92  import org.exoplatform.webui.config.annotation.EventConfig;
93  import org.exoplatform.webui.core.UIApplication;
94  import org.exoplatform.webui.core.UIComponent;
95  import org.exoplatform.webui.core.model.SelectItemOption;
96  import org.exoplatform.webui.event.Event;
97  import org.exoplatform.webui.event.Event.Phase;
98  import org.exoplatform.webui.event.EventListener;
99  import org.exoplatform.webui.form.UIForm;
100 import org.exoplatform.webui.form.UIFormDateTimeInput;
101 import org.exoplatform.webui.form.UIFormInput;
102 import org.exoplatform.webui.form.UIFormInputBase;
103 import org.exoplatform.webui.form.UIFormMultiValueInputSet;
104 import org.exoplatform.webui.form.UIFormRadioBoxInput;
105 import org.exoplatform.webui.form.UIFormSelectBox;
106 import org.exoplatform.webui.form.UIFormStringInput;
107 import org.exoplatform.webui.form.UIFormTextAreaInput;
108 import org.exoplatform.webui.form.input.UICheckBoxInput;
109 import org.exoplatform.webui.form.input.UIUploadInput;
110 import org.exoplatform.webui.form.wysiwyg.FCKEditorConfig;
111 import org.exoplatform.webui.form.wysiwyg.UIFormWYSIWYGInput;
112 
113 /**
114  * Created by The eXo Platform SAS
115  * @author : Hoa.Pham
116  *          hoa.pham@exoplatform.com
117  * Jun 23, 2008
118  */
119 
120 @ComponentConfigs( {
121   @ComponentConfig(type = UIFormMultiValueInputSet.class, id = "WYSIWYGRichTextMultipleInputset",
122                    events = {
123     @EventConfig(listeners = UIDialogForm.AddActionListener.class, phase = Phase.DECODE),
124     @EventConfig(listeners = UIFormMultiValueInputSet.RemoveActionListener.class, phase = Phase.DECODE) }) })
125 @SuppressWarnings("unused")
126 public class UIDialogForm extends UIForm {
127 
128   /**
129    * Logger.
130    */
131   private static final Log LOG  = ExoLogger.getLogger(UIDialogForm.class.getName());
132 
133   private final String REPOSITORY = "repository";
134   protected final static String CANCEL_ACTION = "Cancel";
135   protected final static String SAVE_ACTION = "Save";
136   protected static final String SAVE_AND_CLOSE = "SaveAndClose";
137   protected static final  String[]  ACTIONS = { SAVE_ACTION, CANCEL_ACTION };
138   private static final String WYSIWYG_MULTI_ID = "WYSIWYGRichTextMultipleInputset";
139 
140   protected Map<String, Map<String,String>> componentSelectors = new HashMap<String, Map<String,String>>();
141   protected Map<String, String> fieldNames = new HashMap<String, String>();
142   protected Map<String, String> propertiesName = new HashMap<String, String>();
143   protected Map<String, String[]> uiMultiValueParam = new HashMap<String, String[]>();
144   protected String contentType;
145   protected boolean isAddNew = true;
146   protected boolean isRemovePreference;
147   protected boolean isRemoveActionField;
148   protected boolean isShowingComponent;
149   protected boolean isUpdateSelect;
150   protected Map<String, JcrInputProperty> properties = new HashMap<String, JcrInputProperty>();
151   protected Map<String, String> options = new HashMap<String, String>();
152   protected String repositoryName;
153   protected JCRResourceResolver resourceResolver;
154   private String childPath;
155   private boolean isNotEditNode;
156   private boolean dataRemoved_ = false;;
157 
158   private boolean isNTFile;
159   private boolean isOnchange;
160   private boolean isResetForm;
161   private boolean isResetMultiField;
162   protected String nodePath;
163   protected String i18nNodePath = null;
164   private List<String> postScriptInterceptor = new ArrayList<String>();
165   private List<String> prevScriptInterceptor = new ArrayList<String>();
166 
167   private List<String> listTaxonomy = new ArrayList<String>();
168   private List<String> removedNodes = new ArrayList<String>();
169   private String storedPath;
170 
171   protected String workspaceName;
172   protected boolean isReference;
173   protected boolean isShowActionsOnTop_ = false;
174   private List<String> removedBinary ;
175   /** Selected Tab id */
176   private String selectedTab;
177 
178   private String SEPARATOR_VALUE = "::";
179 
180   public UIDialogForm() {
181     removedBinary = new ArrayList<String>();
182   }
183 
184   public boolean isEditing() { return !isAddNew;}
185   public boolean isAddNew() { return isAddNew;}
186   public void addNew(boolean b) { this.isAddNew = b; }
187 
188   private boolean isKeepinglock = false;
189 
190   public void setSelectedTab(String selectedTab) {
191     this.selectedTab = selectedTab;
192   }
193 
194   public String getSelectedTab() {
195     return selectedTab;
196   }
197   public boolean isKeepinglock() {
198     return isKeepinglock;
199   }
200 
201   public void setIsKeepinglock(boolean isKeepinglock) {
202     this.isKeepinglock = isKeepinglock;
203   }
204 
205   public boolean isShowActionsOnTop() { return isShowActionsOnTop_; }
206 
207   public void setShowActionsOnTop(boolean isShowActionsOnTop) {
208     this.isShowActionsOnTop_ = isShowActionsOnTop;
209   }
210 
211   public void releaseLock() throws Exception {
212     if (isKeepinglock()) {
213       Node currentNode = getNode();
214       if ((currentNode!=null) && currentNode.isLocked()) {
215         try {
216           if(currentNode.holdsLock()) {
217             String lockToken = LockUtil.getLockTokenOfUser(currentNode);
218             if(lockToken != null) {
219               currentNode.getSession().addLockToken(LockUtil.getLockToken(currentNode));
220             }
221             currentNode.unlock();
222             currentNode.removeMixin(Utils.MIX_LOCKABLE);
223             currentNode.save();
224             //remove lock from Cache
225             LockUtil.removeLock(currentNode);
226           }
227         } catch(LockException le) {
228           if (LOG.isErrorEnabled()) {
229             LOG.error("Fails when unlock node that is editing", le);
230           }
231         }
232       }
233     }
234     setIsKeepinglock(false);
235   }
236 
237   public List<String> getListTaxonomy() {
238     return listTaxonomy;
239   }
240 
241   public void setListTaxonomy(List<String> listTaxonomy) {
242     this.listTaxonomy = listTaxonomy;
243   }
244 
245   public void setStoredLocation(String workspace, String storedPath) {
246     try {
247     this.repositoryName = getApplicationComponent(RepositoryService.class).getCurrentRepository()
248                                                                           .getConfiguration()
249                                                                           .getName();
250     } catch (RepositoryException ex) {
251       this.repositoryName = null;
252     }
253     setWorkspace(workspace);
254     setStoredPath(storedPath);
255   }
256 
257   protected String getCategoryLabel(String resource) {
258     String[] taxonomyPathSplit = resource.split("/");
259     StringBuilder buildlabel;
260     StringBuilder buildPathlabel = new StringBuilder();
261     for (int i = 0; i < taxonomyPathSplit.length; i++) {
262       buildlabel = new StringBuilder("eXoTaxonomies");
263       for (int j = 0; j <= i; j++) {
264         buildlabel.append(".").append(taxonomyPathSplit[j]);
265       }
266       try {
267         buildPathlabel.append(Utils.getResourceBundle(buildlabel.append(".label").toString())).append("/");
268       } catch (MissingResourceException me) {
269         buildPathlabel.append(taxonomyPathSplit[i]).append("/");
270       }
271     }
272     return buildPathlabel.substring(0, buildPathlabel.length() - 1);
273   }
274 
275   public void seti18nNodePath(String nodePath) { i18nNodePath = nodePath; }
276 
277   public String geti18nNodePath() { return i18nNodePath; }
278 
279   @SuppressWarnings("unchecked")
280   public void addActionField(String name,String label,String[] arguments) throws Exception {
281     UIFormActionField formActionField = new UIFormActionField(name,label,arguments);
282     if(formActionField.useSelector()) {
283       componentSelectors.put(name, formActionField.getSelectorInfo());
284     }
285     String jcrPath = formActionField.getJcrPath();
286     JcrInputProperty inputProperty = new JcrInputProperty();
287     inputProperty.setJcrPath(jcrPath);
288     inputProperty.setChangeInJcrPathParam(formActionField.getChangeInJcrPathParam());
289     setInputProperty(name, inputProperty);
290     Node node = getNode();
291     UIComponent uiInput;
292     boolean isFirstTimeRender = false;
293     if(formActionField.isMultiValues()) {
294       uiInput = findComponentById(name);
295       if (uiInput == null) {
296         isFirstTimeRender = true;
297         uiInput = addMultiValuesInput(UIFormStringInput.class,name,label);
298         String defaultValue = formActionField.getDefaultValue();
299         if (defaultValue != null) {
300           if (UIFormMultiValueInputSet.class.isInstance(uiInput)) {
301             String[] arrDefaultValues = defaultValue.split(",");
302             List<String> lstValues = new ArrayList<String>();
303             for (String itemDefaultValues : arrDefaultValues) {
304               if (!lstValues.contains(itemDefaultValues.trim())) lstValues.add(itemDefaultValues.trim());
305             }
306             ((UIFormMultiValueInputSet) uiInput).setValue(lstValues);
307           }
308         }
309       }
310       ((UIFormMultiValueInputSet)uiInput).setEditable(formActionField.isEditable());
311       if (node == null) {
312         renderField(name);
313         return;
314       }
315     } else {
316       uiInput = findComponentById(name);
317       if(uiInput == null) {
318         isFirstTimeRender = true;
319         uiInput = formActionField.createUIFormInput();
320         addUIFormInput((UIFormInput<?>)uiInput);
321       }
322       ((UIFormStringInput)uiInput).setReadOnly(!formActionField.isEditable());
323     }
324     String propertyName = getPropertyName(jcrPath);
325     propertiesName.put(name, propertyName);
326     fieldNames.put(propertyName, name);
327 
328     if (node != null && !isShowingComponent && !isRemovePreference && !isRemoveActionField) {
329       if (jcrPath.equals("/node")
330           && (!formActionField.isEditable() || formActionField.isEditableIfNull())) {
331         ((UIFormStringInput) uiInput).setDisabled(true);
332       }
333     }
334 
335     if (node != null && !isShowingComponent && !isRemovePreference && !isRemoveActionField
336         && isFirstTimeRender) {
337       if(jcrPath.equals("/node") && (!formActionField.isEditable() || formActionField.isEditableIfNull())) {
338         ((UIFormStringInput)uiInput).setValue(node.getName());
339       } else if(node.hasProperty(propertyName) && !isUpdateSelect) {
340         String relPath = "";
341         String itemRelPath = "";
342         if (node.getProperty(propertyName).getDefinition().isMultiple()) {
343           StringBuffer buffer = new StringBuffer();
344           Value[] values = node.getProperty(propertyName).getValues();
345           if (UIFormStringInput.class.isInstance(uiInput)) {
346             for (Value value : values) {
347               buffer.append(value).append(",");
348             }
349             if (buffer.toString().endsWith(","))
350               buffer.deleteCharAt(buffer.length() - 1);
351             ((UIFormStringInput) uiInput).setValue(buffer.toString());
352           }
353           if (UIFormMultiValueInputSet.class.isInstance(uiInput)) {
354             List<String> lstValues = new ArrayList<String>();
355             for (Value value : values) {
356               lstValues.add(value.getString());
357             }
358             ((UIFormMultiValueInputSet) uiInput).setValue(lstValues);
359           }
360         } else {
361           String value = node.getProperty(propertyName).getValue().getString();
362           if (node.getProperty(propertyName).getDefinition().getRequiredType() == PropertyType.REFERENCE)
363             value = getNodePathByUUID(value);
364           ((UIFormStringInput) uiInput).setValue(value);
365         }
366       }
367     }
368     Node childNode = getChildNode();
369     if(isNotEditNode && !isShowingComponent && !isRemovePreference && !isRemoveActionField) {
370       if(childNode != null) {
371         ((UIFormInput<String>)uiInput).setValue(propertyName);
372       } else if(childNode == null && jcrPath.equals("/node") && node != null) {
373         ((UIFormInput<String>)uiInput).setValue(node.getName());
374       } else {
375         ((UIFormInput<?>)uiInput).setValue(null);
376       }
377     }
378     renderField(name);
379   }
380   public void addActionField(String name, String[] arguments) throws Exception {
381     addActionField(name,null,arguments);
382   }
383 
384   public void addCalendarField(String name, String label, String[] arguments) throws Exception {
385     UIFormCalendarField calendarField = new UIFormCalendarField(name,label,arguments);
386     String jcrPath = calendarField.getJcrPath();
387     JcrInputProperty inputProperty = new JcrInputProperty();
388     inputProperty.setJcrPath(jcrPath);
389     inputProperty.setChangeInJcrPathParam(calendarField.getChangeInJcrPathParam());
390     setInputProperty(name, inputProperty);
391     if(calendarField.isMultiValues()) {
392       renderMultiValuesInput(UIFormDateTimeInput.class,name,label);
393       return;
394     }
395     boolean isFirstTimeRender = false;
396     UIFormDateTimeInput uiDateTime = findComponentById(name);
397     if (uiDateTime == null) {
398       isFirstTimeRender = true;
399       uiDateTime = calendarField.createUIFormInput();
400       if (calendarField.validateType != null) {
401         DialogFormUtil.addValidators(uiDateTime, calendarField.validateType);
402       }
403       if (isAddNew && uiDateTime.getCalendar() == null) {
404         uiDateTime.setCalendar(new GregorianCalendar());
405       }
406     }
407     uiDateTime.setDisplayTime(calendarField.isDisplayTime());
408     String propertyName = getPropertyName(jcrPath);
409     propertiesName.put(name, propertyName);
410     fieldNames.put(propertyName, name);
411     Node  node = getNode();
412     uiDateTime.setCalendar(uiDateTime.getCalendar());
413     if(node != null && node.hasProperty(propertyName) && !isShowingComponent && !isRemovePreference) {
414       if (isFirstTimeRender)
415         uiDateTime.setCalendar(node.getProperty(propertyName).getDate());
416     }
417     Node childNode = getChildNode();
418     if(isNotEditNode && !isShowingComponent && !isRemovePreference) {
419       if(childNode != null) {
420         if(childNode.hasProperty(propertyName)) {
421           if(childNode.getProperty(propertyName).getDefinition().isMultiple()) {
422             Value[] values = childNode.getProperty(propertyName).getValues();
423             for(Value value : values) {
424               if (uiDateTime.getDefaultValue() == null) {
425                 uiDateTime.setCalendar(value.getDate());
426                 uiDateTime.setDefaultValue(uiDateTime.getValue());
427               }
428             }
429           } else {
430             uiDateTime.setCalendar(childNode.getProperty(propertyName).getValue().getDate());
431           }
432         }
433       } else if(childNode == null && jcrPath.equals("/node") && node != null) {
434         uiDateTime.setCalendar(node.getProperty(propertyName).getDate());
435       } else {
436         uiDateTime.setCalendar(new GregorianCalendar());
437       }
438     }else{
439       if((node != null) && node.hasNode("jcr:content") && (childNode == null)) {
440         Node jcrContentNode = node.getNode("jcr:content");
441         if(jcrContentNode.hasProperty(propertyName)) {
442           if(jcrContentNode.getProperty(propertyName).getDefinition().isMultiple()) {
443             Value[] values = jcrContentNode.getProperty(propertyName).getValues();
444             for(Value value : values) {
445               if (uiDateTime.getDefaultValue() == null) {
446                 uiDateTime.setCalendar(value.getDate());
447                 uiDateTime.setDefaultValue(uiDateTime.getValue());
448               }
449             }
450           }else{
451             uiDateTime.setCalendar(jcrContentNode.getProperty(propertyName).getValue().getDate());
452           }
453         }
454       }
455     }
456     if (findComponentById(name) == null) addUIFormInput(uiDateTime);
457     if(calendarField.isVisible()) renderField(name);
458   }
459 
460   public void addCalendarField(String name, String[] arguments) throws Exception {
461     addCalendarField(name,null,arguments);
462   }
463 
464   public void addHiddenField(String name, String[] arguments) throws Exception {
465     UIFormHiddenField formHiddenField = new UIFormHiddenField(name,null,arguments);
466     String jcrPath = formHiddenField.getJcrPath();
467     JcrInputProperty inputProperty = formHiddenField.createJcrInputProperty();
468     inputProperty.setJcrPath(jcrPath);
469     inputProperty.setChangeInJcrPathParam(formHiddenField.getChangeInJcrPathParam());
470     inputProperty.setValue(formHiddenField.getDefaultValue());
471     if(formHiddenField.getMixinTypes() != null) inputProperty.setMixintype(formHiddenField.getMixinTypes());
472     if(formHiddenField.getNodeType() != null ) inputProperty.setNodetype(formHiddenField.getNodeType());
473     setInputProperty(name, inputProperty);
474   }
475 
476   public void addInterceptor(String scriptPath, String type) {
477     if(scriptPath.length() > 0 && type.length() > 0){
478       if(type.equals("prev") && !prevScriptInterceptor.contains(scriptPath)){
479         prevScriptInterceptor.add(scriptPath);
480       } else if(type.equals("post") && !postScriptInterceptor.contains(scriptPath)){
481         postScriptInterceptor.add(scriptPath);
482       }
483     }
484   }
485 
486   public void addMixinField(String name,String label,String[] arguments) throws Exception {
487     UIMixinField mixinField = new UIMixinField(name,label,arguments);
488     String jcrPath = mixinField.getJcrPath();
489     String nodetype = mixinField.getNodeType();
490     String mixintype = mixinField.getMixinTypes();
491     JcrInputProperty inputProperty = new JcrInputProperty();
492     inputProperty.setJcrPath(jcrPath);
493     inputProperty.setChangeInJcrPathParam(mixinField.getChangeInJcrPathParam());
494     if (nodetype != null || mixintype != null) {
495       inputProperty.setType(JcrInputProperty.NODE);
496       if(nodetype != null) inputProperty.setNodetype(nodetype);
497       if(mixintype != null) inputProperty.setMixintype(mixintype);
498     }
499     setInputProperty(name, inputProperty);
500     Node node = getNode();
501     if(node != null && mixinField.isVisibleIfNotNull()) {
502       UIFormStringInput uiMixin = findComponentById(name);
503       if(uiMixin == null) {
504         uiMixin = mixinField.createUIFormInput();
505         uiMixin.setValue(node.getName());
506         addUIFormInput(uiMixin);
507       } else
508         uiMixin.setValue(node.getName());
509       uiMixin.setReadOnly(true);
510       renderField(name);
511     }
512   }
513 
514   public void addMixinField(String name, String[] arguments) throws Exception {
515     addMixinField(name,null,arguments);
516   }
517 
518   public void addCheckBoxField(String name, String lable, String[] arguments) throws Exception{
519     UIFormCheckBoxField formCheckBoxField =  new UIFormCheckBoxField(name, lable, arguments);
520     String jcrPath = formCheckBoxField.getJcrPath();
521     String defaultValue = formCheckBoxField.getDefaultValue();
522     if (defaultValue == null) defaultValue = "false";
523     JcrInputProperty inputProperty = new JcrInputProperty();
524     inputProperty.setJcrPath(jcrPath);
525     inputProperty.setChangeInJcrPathParam(formCheckBoxField.getChangeInJcrPathParam());
526     setInputProperty(name, inputProperty);
527     String propertyName = getPropertyName(jcrPath);
528     propertiesName.put(name, propertyName);
529     fieldNames.put(propertyName, name);
530     Node node = getNode();
531     Node childNode = getChildNode();
532     UICheckBoxInput uiCheckBoxInput = findComponentById(name);
533     boolean isFirstTimeRender = false;
534     if(uiCheckBoxInput == null || isResetForm ){
535       isFirstTimeRender = true;
536         uiCheckBoxInput = new UICheckBoxInput(name, name, null);
537         if (defaultValue != null) {
538           uiCheckBoxInput.setValue(Boolean.parseBoolean(defaultValue));
539           uiCheckBoxInput.setChecked(Boolean.parseBoolean(defaultValue));
540         }
541     }
542 
543     if (node != null && node.hasProperty(propertyName) && isFirstTimeRender) {
544       uiCheckBoxInput.setValue(Boolean.parseBoolean(node.getProperty(propertyName).getValue().toString()));
545       uiCheckBoxInput.setChecked(node.getProperty(propertyName).getValue().getBoolean());
546     }else if( childNode != null && childNode.hasProperty(propertyName) && isFirstTimeRender){
547       uiCheckBoxInput.setValue(Boolean.parseBoolean(childNode.getProperty(propertyName).getValue().toString()));
548       uiCheckBoxInput.setChecked(childNode.getProperty(propertyName).getValue().getBoolean());
549     }
550 
551     if (formCheckBoxField.validateType != null) {
552       DialogFormUtil.addValidators(uiCheckBoxInput, formCheckBoxField.validateType);
553     }
554 
555     if(formCheckBoxField.isOnchange()){
556       uiCheckBoxInput.setOnChange("Onchange");
557       uiCheckBoxInput.setValue(uiCheckBoxInput.getValue());
558     }
559     removeChildById(name);
560     addUIFormInput(uiCheckBoxInput);
561     renderField(name);
562   }
563 
564   public void addCheckBoxField(String name, String[] arguments) throws Exception{
565     addCheckBoxField(name, null, arguments);
566   }
567 
568   public void addRadioBoxField(String name, String label, String[] arguments) throws Exception{
569     UIFormRadioBoxField formRadioBoxField = new UIFormRadioBoxField(name, label, arguments);
570     String jcrPath = formRadioBoxField.getJcrPath();
571     String options = formRadioBoxField.getOptions();
572     String defaultValue = formRadioBoxField.getDefaultValue();
573     List<SelectItemOption<String>> optionsList = new ArrayList<SelectItemOption<String>>();
574     UIFormRadioBoxInput uiRadioBox = findComponentById(name);
575     boolean isFirstTimeRender = false;
576     if(uiRadioBox == null){
577       isFirstTimeRender = true;
578       uiRadioBox = new UIFormRadioBoxInput(name, defaultValue, null);
579       if(options != null && options.length() > 0){
580         String[] array = options.split(";");
581         for(int i = 0; i < array.length; i++) {
582           String[] arrayChild = array[i].trim().split(",");
583           for(int j=0; j<arrayChild.length; j++) {
584             optionsList.add(new SelectItemOption<String>(arrayChild[j], arrayChild[j]));
585           }
586         }
587         uiRadioBox.setOptions(optionsList);
588       } else {
589         uiRadioBox.setOptions(optionsList);
590       }
591       if(defaultValue != null) uiRadioBox.setDefaultValue(defaultValue);
592     }
593     addUIFormInput(uiRadioBox);
594     String propertyName = getPropertyName(jcrPath);
595     propertiesName.put(name, propertyName);
596     fieldNames.put(propertyName, name);
597     JcrInputProperty inputProperty = new JcrInputProperty();
598     inputProperty.setJcrPath(jcrPath);
599     inputProperty.setChangeInJcrPathParam(formRadioBoxField.getChangeInJcrPathParam());
600     setInputProperty(name, inputProperty);
601     Node node = getNode();
602     Node childNode = getChildNode();
603     if(childNode != null) {
604       if(childNode.hasProperty(propertyName) && isFirstTimeRender) {
605         uiRadioBox.setValue(childNode.getProperty(propertyName).getValue().getString());
606       }
607     } else {
608       if(node != null && node.hasProperty(propertyName) && isFirstTimeRender) {
609         uiRadioBox.setValue(node.getProperty(propertyName).getString());
610       }
611     }
612     if(isNotEditNode) {
613       Node child = getChildNode();
614       if(child != null && child.hasProperty(propertyName) && isFirstTimeRender) {
615         uiRadioBox.setValue(DialogFormUtil.getPropertyValueAsString(child,propertyName));
616       }
617     }
618     renderField(name);
619   }
620 
621   public void addRadioBoxField(String name, String[] arguments) throws Exception{
622     addRadioBoxField(name, null, arguments);
623   }
624 
625   public void addSelectBoxField(String name, String label, String[] arguments) throws Exception {
626     UIFormSelectBoxField formSelectBoxField = new UIFormSelectBoxField(name,label,arguments);
627     String jcrPath = formSelectBoxField.getJcrPath();
628     String editable = formSelectBoxField.getEditable();
629     String onchange = formSelectBoxField.getOnchange();
630     String defaultValue = formSelectBoxField.getDefaultValue();
631     String options = formSelectBoxField.getOptions();
632     String script = formSelectBoxField.getGroovyScript();
633     if (editable == null) formSelectBoxField.setEditable("true");
634     List<SelectItemOption<String>> optionsList = new ArrayList<SelectItemOption<String>>();
635     UIFormSelectBox uiSelectBox = findComponentById(name);
636     boolean isFirstTimeRender = false;
637     if (uiSelectBox == null || isResetForm) {
638       isFirstTimeRender = true;
639       uiSelectBox = new UIFormSelectBox(name, name, null);
640       if (script != null) {
641         try {
642           String[] scriptParams = formSelectBoxField.getScriptParams();
643           executeScript(script, uiSelectBox, scriptParams, true);
644         } catch (Exception e) {
645           if (LOG.isErrorEnabled()) {
646             LOG.error("An unexpected error occurs", e);
647           }
648           uiSelectBox.setOptions(optionsList);
649         }
650       } else if (options != null && options.length() >0) {
651         String[] array = options.split(",");
652         RequestContext context = RequestContext.getCurrentInstance();
653         ResourceBundle res = context.getApplicationResourceBundle();
654         String optionLabel;
655         for(int i = 0; i < array.length; i++) {
656           List<String> listValue = new ArrayList<String>();
657           String[] arrayChild = array[i].trim().split(SEPARATOR_VALUE);
658           for (int j = 0; j < arrayChild.length; j++) {
659             if (!arrayChild[j].trim().equals("")) {
660               listValue.add(arrayChild[j].trim());
661             }
662           }
663           try {
664             String tagName = listValue.get(0).replaceAll(" ", "-");
665             optionLabel = res.getString(tagName);
666           } catch (MissingResourceException e) {
667             optionLabel = listValue.get(0);
668           }
669           if (listValue.size() > 1) {
670             optionsList.add(new SelectItemOption<String>(optionLabel, listValue.get(1)));
671           } else {
672             optionsList.add(new SelectItemOption<String>(optionLabel, listValue.get(0)));
673           }
674         }
675         uiSelectBox.setOptions(optionsList);
676       } else {
677         uiSelectBox.setOptions(optionsList);
678       }
679       if(defaultValue != null) uiSelectBox.setValue(defaultValue);
680     }
681 
682     propertiesName.put(name, getPropertyName(jcrPath));
683     fieldNames.put(getPropertyName(jcrPath), name);
684     if (formSelectBoxField.validateType != null) {
685       DialogFormUtil.addValidators(uiSelectBox, formSelectBoxField.validateType);
686     }
687     String[] arrNodes = jcrPath.split("/");
688     Node childNode = null;
689     Node node = getNode();
690     String propertyName = getPropertyName(jcrPath);
691     if(node != null && arrNodes.length == 4) childNode = node.getNode(arrNodes[2]);
692     if (formSelectBoxField.isMultiValues()) {
693       if (formSelectBoxField.getSize() != null
694           && StringUtils.isAlphanumeric(formSelectBoxField.getSize())) {
695         uiSelectBox.setSize(Integer.parseInt(formSelectBoxField.getSize()));
696       }
697       uiSelectBox.setMultiple(true);
698       StringBuffer buffer = new StringBuffer();
699       if((childNode != null) && isFirstTimeRender && childNode.hasProperty(propertyName)) {
700         List<String> valueList = new ArrayList<String>();
701         Value[] values = childNode.getProperty(propertyName).getValues();
702         for(Value value : values) {
703           buffer.append(value.getString()).append(",");
704         }
705         uiSelectBox.setSelectedValues(StringUtils.split(buffer.toString(), ","));
706       } else {
707         if(node != null && isFirstTimeRender && node.hasProperty(propertyName)) {
708           List<String> valueList = new ArrayList<String>();
709           if (node.getProperty(propertyName).getDefinition().isMultiple()
710               && (!"true".equals(onchange) || !isOnchange)) {
711             Value[] values = node.getProperty(propertyName).getValues();
712             for(Value value : values) {
713               buffer.append(value.getString()).append(",");
714             }
715           } else if("true".equals(onchange) && isOnchange) {
716             if (uiSelectBox.isMultiple()) {
717               String[] values = uiSelectBox.getSelectedValues();
718               for (String value : values) {
719                 buffer.append(value).append(",");
720               }
721             } else {
722               String values = uiSelectBox.getValue();
723               buffer.append(values).append(",");
724             }
725           } else {
726             Value[] values = node.getProperty(propertyName).getValues();
727             for(Value value : values) {
728               buffer.append(value.getString()).append(",");
729             }
730           }
731           uiSelectBox.setSelectedValues(StringUtils.split(buffer.toString(), ","));
732         }
733       }
734     } else {
735       if ((childNode != null) && isFirstTimeRender && childNode.hasProperty(propertyName)) {
736         uiSelectBox.setValue(childNode.getProperty(propertyName).getValue().getString());
737       } else {
738         if (node != null && node.hasProperty(propertyName)) {
739           if (node.getProperty(propertyName).getDefinition().isMultiple()) {
740             if (findComponentById(name) == null)
741               uiSelectBox.setValue(node.getProperty(propertyName).getValues().toString());
742           } else if (formSelectBoxField.isOnchange() && isOnchange) {
743             uiSelectBox.setValue(uiSelectBox.getValue());
744           } else {
745             if (findComponentById(name) == null)
746               uiSelectBox.setValue(node.getProperty(propertyName).getValue().getString());
747           }
748         }
749       }
750     }
751     uiSelectBox.setReadOnly(!formSelectBoxField.isEditable());
752 //    addUIFormInput(uiSelectBox);
753     if(isNotEditNode) {
754       Node child = getChildNode();
755       if(child != null && child.hasProperty(propertyName)) {
756         if(child.getProperty(propertyName).getDefinition().isMultiple()) {
757           Value[] values = child.getProperty(propertyName).getValues();
758           List<String> listValues = new ArrayList<String>();
759           for(Value value : values) {
760             listValues.add(value.getString());
761           }
762           uiSelectBox.setSelectedValues(listValues.toArray(new String[listValues.size()]));
763         } else {
764           uiSelectBox.setValue(DialogFormUtil.getPropertyValueAsString(child,propertyName));
765         }
766       }
767     }
768     if(formSelectBoxField.isOnchange()) uiSelectBox.setOnChange("Onchange");
769     if (findComponentById(name) == null) addUIFormInput(uiSelectBox);
770 
771     StringBuilder newValues = new StringBuilder();
772     int count = 0;
773     for (String v : ((UIFormSelectBox)findComponentById(name)).getSelectedValues()) {
774       if (count++ > 0) newValues.append(",");
775       newValues.append(v);
776     }
777     String newValue = newValues.toString();
778     JcrInputProperty inputProperty = properties.get(name);
779     if (inputProperty== null) {
780       inputProperty = new JcrInputProperty();
781       inputProperty.setJcrPath(jcrPath);
782       inputProperty.setChangeInJcrPathParam(formSelectBoxField.getChangeInJcrPathParam());
783       setInputProperty(name, inputProperty);
784     } else {
785       if (inputProperty.getValue() != null) {
786       String oldValue = inputProperty.getValue().toString();
787       if ((oldValue != null) && (!oldValue.equals(newValue))) {
788         Iterator<String> componentSelector = componentSelectors.keySet().iterator();
789         Map<String, String> obj = null;
790         while (componentSelector.hasNext()) {
791           String componentName = componentSelector.next();
792           obj = (Map<String, String>) componentSelectors.get(componentName);
793           Set<String> set = obj.keySet();
794           for (String key : set) {
795             if (name.equals(obj.get(key))) {
796               UIComponent uiInput = findComponentById(componentName);
797               ((UIFormStringInput) uiInput).reset();
798             }
799           }
800         }
801       }
802       }
803     }
804     inputProperty.setValue(newValue);
805     if (isUpdateSelect && newValue != null) {
806       String[] values1 = newValue.split(",");
807       uiSelectBox.setSelectedValues(values1);
808     }
809     renderField(name);
810   }
811 
812   public void addSelectBoxField(String name, String[] arguments) throws Exception {
813     addSelectBoxField(name,null,arguments);
814   }
815 
816   public void addTextAreaField(String name, String label, String[] arguments) throws Exception {
817     UIFormTextAreaField formTextAreaField = new UIFormTextAreaField(name,label,arguments);
818     if(formTextAreaField.useSelector()) {
819       componentSelectors.put(name, formTextAreaField.getSelectorInfo());
820     }
821     String jcrPath = formTextAreaField.getJcrPath();
822     JcrInputProperty inputProperty = new JcrInputProperty();
823     inputProperty.setJcrPath(jcrPath);
824     inputProperty.setChangeInJcrPathParam(formTextAreaField.getChangeInJcrPathParam());
825     setInputProperty(name, inputProperty);
826     String option = formTextAreaField.getOptions();
827     setInputOption(name, option);
828     String propertyName = getPropertyName(jcrPath);
829     propertiesName.put(name, propertyName);
830     fieldNames.put(propertyName, name);
831     Node node = getNode();
832     Node childNode = getChildNode();
833     boolean isFirstTimeRender = false;
834     if(formTextAreaField.isMultiValues()) {
835       UIFormMultiValueInputSet uiMulti;
836       if(node == null && childNode == null) {
837         uiMulti = findComponentById(name);
838         if(uiMulti == null) {
839           isFirstTimeRender = true;
840           uiMulti = createUIComponent(UIFormMultiValueInputSet.class, null, null);
841           uiMulti.setId(name);
842           uiMulti.setName(name);
843           uiMulti.setType(UIFormTextAreaInput.class);
844           uiMulti.setEditable(formTextAreaField.isEditable());
845           if (formTextAreaField.validateType != null) {
846             String validateType = formTextAreaField.validateType;
847             String[] validatorList = null;
848             if (validateType.indexOf(',') > -1) validatorList = validateType.split(",");
849             else validatorList = new String[] {validateType};
850             for (String validator : validatorList) {
851               Object[] params;
852               String s_param=null;
853               int p_begin, p_end;
854               p_begin = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_BEGIN);
855               p_end   = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_END);
856               if (p_begin>=0 && p_end > p_begin) {
857                 s_param = validator.substring(p_begin, p_end);
858                 params = s_param.split(DialogFormUtil.VALIDATOR_PARAM_SEPERATOR);
859                 uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim()), params) ;
860               }else {
861                 uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim())) ;
862               }
863             }
864           }
865           List<String> valueList = new ArrayList<String>();
866           List<UIComponent> listChildren = uiMulti.getChildren();
867           if (listChildren.size() == 0) {
868             valueList.add(formTextAreaField.getDefaultValue());
869           } else {
870             for (UIComponent component : listChildren) {
871               UIFormTextAreaInput uiTextAreaInput = (UIFormTextAreaInput)component;
872               if(uiTextAreaInput.getValue() != null) {
873                 valueList.add(uiTextAreaInput.getValue().trim());
874               } else{
875                 valueList.add(formTextAreaField.getDefaultValue());
876               }
877             }
878           }
879           uiMulti.setValue(valueList);
880           addUIFormInput(uiMulti);
881         }
882       } else {
883         uiMulti = createUIComponent(UIFormMultiValueInputSet.class, null, null);
884         isFirstTimeRender = true;
885         uiMulti.setId(name);
886         uiMulti.setName(name);
887         uiMulti.setType(UIFormTextAreaInput.class);
888         uiMulti.setEditable(formTextAreaField.isEditable());
889         if (formTextAreaField.validateType != null) {
890           String validateType = formTextAreaField.validateType;
891           String[] validatorList = null;
892           if (validateType.indexOf(',') > -1)
893             validatorList = validateType.split(",");
894           else
895             validatorList = new String[] { validateType };
896           for (String validator : validatorList) {
897             Object[] params;
898             String s_param = null;
899             int p_begin, p_end;
900             p_begin = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_BEGIN);
901             p_end = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_END);
902             if (p_begin >= 0 && p_end > p_begin) {
903               s_param = validator.substring(p_begin, p_end);
904               params = s_param.split(DialogFormUtil.VALIDATOR_PARAM_SEPERATOR);
905               uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim()), params);
906             } else {
907               uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim()));
908             }
909           }
910         }
911         addUIFormInput(uiMulti);
912       }
913       List<String> valueList = new ArrayList<String>();
914       boolean valueListIsSet = false;
915       if((node != null) && node.hasNode("jcr:content") && (childNode == null)) {
916         Node jcrContentNode = node.getNode("jcr:content");
917         if(jcrContentNode.hasProperty(propertyName)) {
918           Value[] values = jcrContentNode.getProperty(propertyName).getValues();
919           for(Value value : values) {
920             valueList.add(value.getString());
921           }
922           uiMulti.setEditable(formTextAreaField.isEditable());
923           uiMulti.setValue(valueList);
924           valueListIsSet = true;
925         }
926       } else {
927         if(childNode != null) {
928           if(childNode.hasProperty(propertyName)) {
929             Value[] values = childNode.getProperty(propertyName).getValues();
930             for(Value value : values) {
931               valueList.add(value.getString());
932             }
933             uiMulti.setEditable(formTextAreaField.isEditable());
934             uiMulti.setValue(valueList);
935             valueListIsSet = true;
936           }
937         }
938       }
939       if (!valueListIsSet && node != null && !isShowingComponent && !isRemovePreference
940           && isFirstTimeRender) {
941         String propertyPath = jcrPath.substring("/node/".length());
942         if (node.hasProperty(propertyPath)) {
943           Value[] values = node.getProperty(propertyPath).getValues();
944           // if the node type is mix:referenceable, its values will contain the UUIDs of the reference nodes
945           // we need to get the paths of the reference nodes instead of its UUIDs to display onto screen
946           if (node.getProperty(propertyPath).getType() == PropertyType.REFERENCE) {
947             for (Value vl : values) {
948               if (vl != null) {
949                 String strUUID = vl.getString();
950                 try {
951                   String strReferenceableNodePath = node.getSession().getNodeByUUID(strUUID).getPath();
952 
953                   //if the referenceable node is not ROOT, remove the "/" character at head
954                   if (strReferenceableNodePath.length() > 1){
955                     strReferenceableNodePath = strReferenceableNodePath.substring(1);
956                   }
957 
958                   valueList.add(strReferenceableNodePath);
959                 } catch (ItemNotFoundException infEx) {
960                   valueList.add(formTextAreaField.getDefaultValue());
961                 } catch (RepositoryException repoEx) {
962                   valueList.add(formTextAreaField.getDefaultValue());
963                 }
964               }
965             }
966           } else {
967             for (Value vl : values) {
968               if (vl != null) {
969                 valueList.add(vl.getString());
970               }
971             }
972           }
973         }
974         uiMulti.setValue(valueList);
975       }
976       if(isResetMultiField) {
977         uiMulti.setValue(new ArrayList<Value>());
978       }
979       uiMulti.setEditable(formTextAreaField.isEditable());
980       renderField(name);
981       return;
982     }
983     UIFormTextAreaInput uiTextArea = findComponentById(name);
984     if(uiTextArea == null) {
985       isFirstTimeRender = true;
986       uiTextArea = formTextAreaField.createUIFormInput();
987       if(formTextAreaField.getRowSize() != null){
988         uiTextArea.setRows(Integer.parseInt(formTextAreaField.getRowSize()));
989       } else {
990         uiTextArea.setRows(UIFormTextAreaField.DEFAULT_ROW);
991       }
992       if(formTextAreaField.getColSize() != null){
993         uiTextArea.setColumns(Integer.parseInt(formTextAreaField.getColSize()));
994       } else {
995         uiTextArea.setColumns(UIFormTextAreaField.DEFAULT_COL);
996       }
997       addUIFormInput(uiTextArea);
998     }
999     if (node != null && !isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1000       StringBuffer value = new StringBuffer();
1001       if (node.hasProperty(propertyName)) {
1002         value.append(node.getProperty(propertyName).getValue().getString());
1003         uiTextArea.setValue(value.toString());
1004       } else if (node.isNodeType("nt:file")) {
1005         Node jcrContentNode = node.getNode("jcr:content");
1006         if (jcrContentNode.hasProperty(propertyName)) {
1007           if (jcrContentNode.getProperty(propertyName).getDefinition().isMultiple()) {
1008             Value[] values = jcrContentNode.getProperty(propertyName).getValues();
1009             for (Value v : values) {
1010               value.append(v.getString());
1011             }
1012             uiTextArea.setValue(value.toString());
1013           } else {
1014             uiTextArea.setValue(jcrContentNode.getProperty(propertyName).getValue().getString());
1015           }
1016         }
1017       }
1018     }
1019     if (isNotEditNode && !isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1020       if (node != null && node.hasNode("jcr:content") && childNode != null) {
1021         Node jcrContentNode = node.getNode("jcr:content");
1022         uiTextArea.setValue(jcrContentNode.getProperty("jcr:data").getValue().getString());
1023       } else {
1024         if (childNode != null) {
1025           uiTextArea.setValue(propertyName);
1026         } else if (childNode == null && jcrPath.equals("/node") && node != null) {
1027           uiTextArea.setValue(node.getName());
1028         } else {
1029           uiTextArea.setValue(null);
1030         }
1031       }
1032     }
1033     //set default value for textarea if no value was set by above code
1034     if (uiTextArea.getValue() == null) {
1035       if (formTextAreaField.getDefaultValue() != null)
1036         uiTextArea.setValue(formTextAreaField.getDefaultValue());
1037       else
1038         uiTextArea.setValue("");
1039     }
1040     uiTextArea.setReadOnly(!formTextAreaField.isEditable());
1041     renderField(name);
1042   }
1043   public void addTextAreaField(String name, String[] arguments) throws Exception {
1044     addTextAreaField(name,null,arguments);
1045   }
1046 
1047   public String getPathTaxonomy() throws Exception {
1048     NodeHierarchyCreator nodeHierarchyCreator = getApplicationComponent(NodeHierarchyCreator.class);
1049     DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class);
1050     String workspace = dmsConfiguration.getConfig().getSystemWorkspace();
1051     String userName = Util.getPortalRequestContext().getRemoteUser();
1052     Session session;
1053     if (userName != null)
1054       session = WCMCoreUtils.getUserSessionProvider().getSession(workspace, getRepository());
1055     else
1056       session = WCMCoreUtils.createAnonimProvider().getSession(workspace, getRepository());
1057     return ((Node)session.getItem(nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH))).getPath();
1058   }
1059 
1060   @SuppressWarnings("unchecked")
1061   public void addTextField(String name, String label, String[] arguments) throws Exception {
1062     UIFormTextField formTextField = new UIFormTextField(name,label,arguments);
1063     String jcrPath = formTextField.getJcrPath();
1064     String mixintype = formTextField.getMixinTypes();
1065     String nodetype = formTextField.getNodeType();
1066     JcrInputProperty inputProperty = new JcrInputProperty();
1067     inputProperty.setJcrPath(jcrPath);
1068     inputProperty.setChangeInJcrPathParam(formTextField.getChangeInJcrPathParam());
1069     setInputProperty(name, inputProperty);
1070     String option = formTextField.getOptions();
1071     setInputOption(name, option);
1072     String propertyName = getPropertyName(jcrPath);
1073     if(mixintype != null) inputProperty.setMixintype(mixintype);
1074     if(jcrPath.equals("/node") && nodetype != null ) inputProperty.setNodetype(nodetype);
1075     properties.put(name, inputProperty);
1076     propertiesName.put(name, propertyName);
1077     fieldNames.put(propertyName, name);
1078     Node node = getNode();
1079     Node childNode = getChildNode();
1080     if(!isReference) {
1081       if(formTextField.isReference()) isReference = true;
1082       else isReference = false;
1083     }
1084     boolean isFirstTimeRender = false;
1085     if(formTextField.isMultiValues()) {
1086       UIFormMultiValueInputSet uiMulti;
1087       if(node == null &&childNode == null) {
1088         uiMulti = findComponentById(name);
1089         if(uiMulti == null) {
1090           isFirstTimeRender = true;
1091           uiMulti = createUIComponent(UIFormMultiValueInputSet.class, null, null);
1092           uiMulti.setId(name);
1093           uiMulti.setName(name);
1094           uiMulti.setType(UIFormStringInput.class);
1095           uiMulti.setEditable(formTextField.isEditable());
1096           if (formTextField.validateType != null) {
1097             String validateType = formTextField.validateType;
1098             String[] validatorList = null;
1099             if (validateType.indexOf(',') > -1) validatorList = validateType.split(",");
1100             else validatorList = new String[] {validateType};
1101             for (String validator : validatorList) {
1102               Object[] params;
1103               String s_param=null;
1104               int p_begin, p_end;
1105               p_begin = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_BEGIN);
1106               p_end   = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_END);
1107               if (p_begin>=0 && p_end > p_begin) {
1108                 s_param = validator.substring(p_begin, p_end);
1109                 params = s_param.split(DialogFormUtil.VALIDATOR_PARAM_SEPERATOR);
1110                 uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim()), params) ;
1111               }else {
1112                 uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim())) ;
1113               }
1114             }
1115           }
1116           List<String> valueList = new ArrayList<String>();
1117           List<UIComponent> listChildren = uiMulti.getChildren();
1118           if (listChildren.size() == 0) {
1119             valueList.add(formTextField.getDefaultValue());
1120           } else {
1121             for (UIComponent component : listChildren) {
1122               UIFormStringInput uiStringInput = (UIFormStringInput)component;
1123               if(uiStringInput.getValue() != null) {
1124                 valueList.add(uiStringInput.getValue().trim());
1125               } else{
1126                 valueList.add(formTextField.getDefaultValue());
1127               }
1128             }
1129           }
1130           uiMulti.setValue(valueList);
1131           addUIFormInput(uiMulti);
1132         }
1133       } else {
1134         uiMulti = createUIComponent(UIFormMultiValueInputSet.class, null, null);
1135         isFirstTimeRender = true;
1136         uiMulti.setId(name);
1137         uiMulti.setName(name);
1138         uiMulti.setType(UIFormStringInput.class);
1139         uiMulti.setEditable(formTextField.isEditable());
1140         if (formTextField.validateType != null) {
1141           String validateType = formTextField.validateType;
1142           String[] validatorList = null;
1143           if (validateType.indexOf(',') > -1) validatorList = validateType.split(",");
1144           else validatorList = new String[] {validateType};
1145           for (String validator : validatorList) {
1146             Object[] params;
1147             String s_param=null;
1148             int p_begin, p_end;
1149             p_begin = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_BEGIN);
1150             p_end   = validator.indexOf(DialogFormUtil.VALIDATOR_PARAM_END);
1151             if (p_begin>=0 && p_end > p_begin) {
1152               s_param = validator.substring(p_begin, p_end);
1153               params = s_param.split(DialogFormUtil.VALIDATOR_PARAM_SEPERATOR);
1154               uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim()), params) ;
1155             }else {
1156               uiMulti.addValidator(DialogFormUtil.getValidator(validator.trim())) ;
1157             }
1158           }
1159         }
1160         if (getChildById(name) == null)
1161           addUIFormInput(uiMulti);
1162       }
1163       List<String> valueList = new ArrayList<String>();
1164       boolean valueListIsSet = false;
1165       if((node != null) && node.hasNode("jcr:content") && (childNode == null)) {
1166         Node jcrContentNode = node.getNode("jcr:content");
1167         if(jcrContentNode.hasProperty(propertyName)) {
1168           Value[] values = jcrContentNode.getProperty(propertyName).getValues();
1169           for(Value value : values) {
1170             valueList.add(value.getString());
1171           }
1172           uiMulti.setEditable(formTextField.isEditable());
1173           uiMulti.setValue(valueList);
1174           valueListIsSet = true;
1175         }
1176       } else {
1177         if(childNode != null) {
1178           if(childNode.hasProperty(propertyName)) {
1179             Value[] values = childNode.getProperty(propertyName).getValues();
1180             for(Value value : values) {
1181               valueList.add(value.getString());
1182             }
1183             uiMulti.setEditable(formTextField.isEditable());
1184             uiMulti.setValue(valueList);
1185             valueListIsSet = true;
1186           }
1187         }
1188       }
1189       if (!valueListIsSet && node != null && !isShowingComponent && !isRemovePreference
1190           && isFirstTimeRender) {
1191         String propertyPath = jcrPath.substring("/node/".length());
1192         if (node.hasProperty(propertyPath)) {
1193           Value[] values = node.getProperty(propertyPath).getValues();
1194           // if the node type is mix:referenceable, its values will contain the UUIDs of the reference nodes
1195           // we need to get the paths of the reference nodes instead of its UUIDs to display onto screen
1196           if (node.getProperty(propertyPath).getType() == PropertyType.REFERENCE) {
1197             for (Value vl : values) {
1198               if (vl != null) {
1199                 String strUUID = vl.getString();
1200                 try {
1201                   String strReferenceableNodePath = node.getSession().getNodeByUUID(strUUID).getPath();
1202 
1203                   //if the referenceable node is not ROOT, remove the "/" character at head
1204                   if (strReferenceableNodePath.length() > 1){
1205                     strReferenceableNodePath = strReferenceableNodePath.substring(1);
1206                   }
1207 
1208                   valueList.add(strReferenceableNodePath);
1209                 } catch (ItemNotFoundException infEx) {
1210                   valueList.add(formTextField.getDefaultValue());
1211                 } catch (RepositoryException repoEx) {
1212                   valueList.add(formTextField.getDefaultValue());
1213                 }
1214               }
1215             }
1216           } else {
1217             for (Value vl : values) {
1218               if (vl != null) {
1219                 valueList.add(vl.getString());
1220               }
1221             }
1222           }
1223         }
1224         uiMulti.setValue(valueList);
1225       }
1226       if(isResetMultiField) {
1227         uiMulti.setValue(new ArrayList<Value>());
1228       }
1229       uiMulti.setEditable(formTextField.isEditable());
1230       renderField(name);
1231       return;
1232     }
1233     UIFormStringInput uiInput = findComponentById(name);
1234     if(uiInput == null) {
1235       isFirstTimeRender = true;
1236       uiInput = formTextField.createUIFormInput();
1237       addUIFormInput(uiInput);
1238     }
1239     uiInput.setReadOnly(!formTextField.isEditable());
1240     if(uiInput.getValue() == null) uiInput.setValue(formTextField.getDefaultValue());
1241     else uiInput.setReadOnly(false);
1242 
1243     if(node != null && !isShowingComponent && !isRemovePreference) {
1244       if(jcrPath.equals("/node") && (!formTextField.isEditable() || formTextField.isEditableIfNull())) {
1245         uiInput.setDisabled(true);
1246       }
1247     }
1248     if(node != null && !isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1249       if(jcrPath.equals("/node") && (!formTextField.isEditable() || formTextField.isEditableIfNull())) {
1250         String value = uiInput.getValue();
1251         if(i18nNodePath != null) {
1252           uiInput.setValue(i18nNodePath.substring(i18nNodePath.lastIndexOf("/") + 1));
1253         } else {
1254           String nameValue =  node.getPath().substring(node.getPath().lastIndexOf("/") + 1);
1255           uiInput.setValue(nameValue);
1256         }
1257       } else if(node.hasProperty(propertyName)) {
1258         uiInput.setValue(node.getProperty(propertyName).getValue().getString());
1259       }
1260     }
1261     if(isNotEditNode && !isShowingComponent && !isRemovePreference) {
1262       if(childNode != null && childNode.hasProperty(propertyName)) {
1263         if(childNode.hasProperty(propertyName)) {
1264           uiInput.setValue(childNode.getProperty(propertyName).getValue().getString());
1265         }
1266       } else if(childNode == null && jcrPath.equals("/node") && node != null) {
1267         uiInput.setValue(node.getName());
1268       } else if(i18nNodePath != null && jcrPath.equals("/node")) {
1269         uiInput.setValue(i18nNodePath.substring(i18nNodePath.lastIndexOf("/") + 1));
1270       } else {
1271         uiInput.setValue(formTextField.getDefaultValue());
1272       }
1273     }
1274     renderField(name);
1275   }
1276   public void addTextField(String name, String[] arguments) throws Exception {
1277     addTextField(name,null,arguments);
1278   }
1279 
1280   public void addUploadField(String name,String label,String[] arguments) throws Exception {
1281     UIFormUploadField formUploadField = new UIFormUploadField(name,label,arguments);
1282     String mimeTypes = formUploadField.getMimeTypes();
1283     String jcrPath = formUploadField.getJcrPath();
1284     JcrInputProperty inputProperty = new JcrInputProperty();
1285     inputProperty.setJcrPath(jcrPath);
1286     inputProperty.setChangeInJcrPathParam(formUploadField.getChangeInJcrPathParam());
1287     setInputProperty(name, inputProperty);
1288     String option = formUploadField.getOptions();
1289     setInputOption(name, option);
1290     setMultiPart(true);
1291     String propertyName = getPropertyName(jcrPath);
1292     properties.put(name, inputProperty);
1293     propertiesName.put(name, propertyName);
1294     fieldNames.put(propertyName, name);
1295     Node node = getNode();
1296     if(formUploadField.isMultiValues()) {
1297       UIFormMultiValueInputSet multiValueField = getChildById(name);
1298       if (multiValueField == null) {
1299         String propertyPath = jcrPath.substring("/node/".length());
1300         if (node != null && node.hasNode(propertyPath)) {
1301           multiValueField = createUIComponent(UIFormUploadMultiValueInputSet.class, null, null);
1302           multiValueField.setId(name);
1303           multiValueField.setName(name);
1304           multiValueField.setType(UIFormUploadInputNoUploadButton.class);
1305           addUIFormInput(multiValueField);
1306           NodeIterator nodeIter = node.getNode(propertyPath).getNodes();
1307           int count = 0;
1308           while (nodeIter.hasNext()) {
1309             Node childNode = nodeIter.nextNode();
1310             if (!childNode.isNodeType(NodetypeConstant.NT_FILE)) continue;
1311             UIFormInputBase<?> uiInput = multiValueField.createUIFormInput(count++);
1312             ((UIFormUploadInputNoUploadButton)uiInput).setFileName(childNode.getName());
1313             Value value = childNode.getNode(NodetypeConstant.JCR_CONTENT).getProperty(NodetypeConstant.JCR_DATA).getValue();
1314             ((UIFormUploadInputNoUploadButton)uiInput).setByteValue(
1315                                                                     IOUtil.getStreamContentAsBytes(value.getStream()));
1316           }
1317           if(label != null) multiValueField.setLabel(label);
1318           multiValueField.setType(UIFormUploadInputNoRemoveButton.class);
1319           renderField(name);
1320           return;
1321         }
1322         multiValueField = renderMultiValuesInput(UIFormUploadInputNoRemoveButton.class,name,label);
1323         if (mimeTypes != null) {
1324           multiValueField.addValidator(UploadFileMimeTypesValidator.class, mimeTypes);
1325         }
1326         return;
1327       }
1328     } else {
1329       UIUploadInput uiInputUpload = findComponentById(name);
1330       if(uiInputUpload == null) {
1331         uiInputUpload = formUploadField.createUIFormInput();
1332         if (mimeTypes != null) {
1333             uiInputUpload.addValidator(UploadFileMimeTypesValidator.class, mimeTypes);
1334         }
1335         addUIFormInput(uiInputUpload);
1336       }
1337     }
1338     renderField(name);
1339   }
1340 
1341   public void addUploadField(String name, String[] arguments) throws Exception {
1342     addUploadField(name,null,arguments);
1343   }
1344 
1345   public void addWYSIWYGField(String name, String label, String[] arguments) throws Exception {
1346     UIFormWYSIWYGField formWYSIWYGField = new UIFormWYSIWYGField(name,label,arguments);
1347     String jcrPath = formWYSIWYGField.getJcrPath();
1348     JcrInputProperty inputProperty = new JcrInputProperty();
1349     inputProperty.setJcrPath(jcrPath);
1350     inputProperty.setChangeInJcrPathParam(formWYSIWYGField.getChangeInJcrPathParam());
1351     setInputProperty(name, inputProperty);
1352     String option = formWYSIWYGField.getOptions();
1353     setInputOption(name, option);
1354     String propertyName = getPropertyName(jcrPath);
1355     propertiesName.put(name, propertyName);
1356     fieldNames.put(propertyName, name);
1357 
1358     List<UIFormInputBase<String>> wysiwygList = getUIFormInputList(name, formWYSIWYGField, false);
1359     if(formWYSIWYGField.isMultiValues()) {
1360       UIFormMultiValueInputSet uiMulti = findComponentById(name);
1361       if (uiMulti == null) {
1362         uiMulti = createUIComponent(UIFormMultiValueInputSet.class, WYSIWYG_MULTI_ID, null);
1363 
1364         this.uiMultiValueParam.put(name, arguments);
1365         uiMulti.setId(name);
1366         uiMulti.setName(name);
1367         uiMulti.setType(UIFormWYSIWYGInput.class);
1368         for (int i = 0; i < wysiwygList.size(); i++) {
1369           uiMulti.addChild(wysiwygList.get(i));
1370           wysiwygList.get(i).setId(name + i);
1371           wysiwygList.get(i).setName(name + i);
1372         }
1373         addUIFormInput(uiMulti);
1374         if(label != null) uiMulti.setLabel(label);
1375       }
1376     } else {
1377       if (wysiwygList.size() > 0)
1378         addUIFormInput(wysiwygList.get(0));
1379     }
1380     renderField(name);
1381   }
1382 
1383   @SuppressWarnings("unchecked")
1384   private List<UIFormInputBase<String>> getUIFormInputList(String name,
1385                                                            DialogFormField formField,
1386                                                            boolean isCreateNew) throws Exception {
1387     String jcrPath = formField.getJcrPath();
1388     String propertyName = getPropertyName(jcrPath);
1389     List<UIFormInputBase<String>> ret = new ArrayList<UIFormInputBase<String>>();
1390 
1391     UIFormInputBase<String> formInput = formField.isMultiValues() ? null : (UIFormInputBase<String>)findComponentById(name);
1392 
1393     boolean isFirstTimeRender = false;
1394     if(formInput == null) {
1395       isFirstTimeRender = true;
1396       formInput = formField.createUIFormInput();
1397     }
1398     /**
1399      * Broadcast some info about current node by FCKEditorConfig Object
1400      * FCKConfigService used to allow add custom config for fckeditor from service
1401      * */
1402     FCKEditorConfig config = new FCKEditorConfig();
1403     FCKEditorContext editorContext = new FCKEditorContext();
1404     if(repositoryName != null) {
1405       config.put("repositoryName",repositoryName);
1406       editorContext.setRepository(repositoryName);
1407     }
1408     if(workspaceName != null) {
1409       config.put("workspaceName",workspaceName);
1410       editorContext.setWorkspace(workspaceName);
1411     }
1412     if(nodePath != null) {
1413       config.put("jcrPath",nodePath);
1414       editorContext.setCurrentNodePath(nodePath);
1415     }else {
1416       config.put("jcrPath",storedPath);
1417       editorContext.setCurrentNodePath(storedPath);
1418     }
1419     FCKConfigService fckConfigService = getApplicationComponent(FCKConfigService.class);
1420     editorContext.setPortalName(Util.getUIPortal().getName());
1421     editorContext.setSkinName(Util.getUIPortalApplication().getSkin());
1422     fckConfigService.processFCKEditorConfig(config,editorContext);
1423     if (formInput instanceof UIFormWYSIWYGInput)
1424       ((UIFormWYSIWYGInput)formInput).setFCKConfig(config);
1425     if(formInput.getValue() == null) formInput.setValue(formField.getDefaultValue());
1426     Node node = getNode();
1427 
1428     if (isCreateNew) {
1429       ret.add(formInput);
1430       return ret;
1431     }
1432     if (!formField.isMultiValues() && isFirstTimeRender) {
1433       if(!isShowingComponent && !isRemovePreference) {
1434         if(node != null && (node.isNodeType("nt:file") || isNTFile) && formField.isFillJcrDataFile()) {
1435           Node jcrContentNode = node.getNode("jcr:content");
1436           formInput.setValue(jcrContentNode.getProperty("jcr:data").getValue().getString());
1437         } else {
1438           if(node != null && node.hasProperty(propertyName)) {
1439             formInput.setValue(node.getProperty(propertyName).getValue().getString());
1440           }
1441         }
1442       }
1443       if(isNotEditNode && !isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1444         Node childNode = getChildNode();
1445         if(node != null && node.hasNode("jcr:content") && childNode != null && formField.isFillJcrDataFile()) {
1446           Node jcrContentNode = node.getNode("jcr:content");
1447           formInput.setValue(jcrContentNode.getProperty("jcr:data").getValue().getString());
1448         } else {
1449           if(childNode != null) {
1450             formInput.setValue(propertyName);
1451           } else if(childNode == null && jcrPath.equals("/node") && node != null) {
1452             formInput.setValue(node.getName());
1453           } else {
1454             formInput.setValue(null);
1455           }
1456         }
1457       }
1458       ret.add(formInput);
1459       return ret;
1460     }
1461     Value[] values = null;
1462 
1463     if(!isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1464       if(node != null && node.hasProperty(propertyName)) {
1465         values = node.getProperty(propertyName).getValues();
1466       }
1467     }
1468     if(isNotEditNode && !isShowingComponent && !isRemovePreference && isFirstTimeRender) {
1469       Node childNode = getChildNode();
1470       if(childNode != null) {
1471         values = new Value[] {node.getSession().getValueFactory().createValue(propertyName)};
1472       } else if(childNode == null && jcrPath.equals("/node") && node != null) {
1473         values = new Value[] {node.getSession().getValueFactory().createValue(node.getName())};
1474       } else {
1475         values = new Value[] {node.getSession().getValueFactory().createValue("")};
1476       }
1477     }
1478     if (values != null && isFirstTimeRender) {
1479       for (Value v : values) {
1480         UIFormInputBase<String> uiFormInput = formField.createUIFormInput();
1481         if (uiFormInput instanceof UIFormWYSIWYGInput)
1482           ((UIFormWYSIWYGInput)uiFormInput).setFCKConfig((FCKEditorConfig)config.clone());
1483         if(v == null || v.getString() == null)
1484           uiFormInput.setValue(formField.getDefaultValue());
1485         else uiFormInput.setValue(v.getString());
1486         ret.add(uiFormInput);
1487       }
1488     } else {
1489       ret.add(formInput);
1490     }
1491     return ret;
1492   }
1493 
1494   public void addWYSIWYGField(String name, String[] arguments) throws Exception {
1495     addWYSIWYGField(name,null,arguments);
1496   }
1497 
1498   public void addRichtextField(String name, String label, String[] arguments) throws Exception {
1499     UIFormRichtextField richtextField = new UIFormRichtextField(name,label,arguments);
1500     String jcrPath = richtextField.getJcrPath();
1501     JcrInputProperty inputProperty = new JcrInputProperty();
1502     inputProperty.setJcrPath(jcrPath);
1503     inputProperty.setChangeInJcrPathParam(richtextField.getChangeInJcrPathParam());
1504     setInputProperty(name, inputProperty);
1505     String option = richtextField.getOptions();
1506     setInputOption(name, option);
1507     String propertyName = getPropertyName(jcrPath);
1508     propertiesName.put(name, propertyName);
1509     fieldNames.put(propertyName, name);
1510 
1511     List<UIFormInputBase<String>> richtextList = getUIFormInputList(name, richtextField, false);
1512     if(richtextField.isMultiValues()) {
1513       UIFormMultiValueInputSet uiMulti = findComponentById(name);
1514       if (uiMulti == null) {
1515         uiMulti = createUIComponent(UIFormMultiValueInputSet.class, WYSIWYG_MULTI_ID, null);
1516 
1517         this.uiMultiValueParam.put(name, arguments);
1518         uiMulti.setId(name);
1519         uiMulti.setName(name);
1520         uiMulti.setType(UIFormRichtextInput.class);
1521         for (int i = 0; i < richtextList.size(); i++) {
1522           uiMulti.addChild(richtextList.get(i));
1523           richtextList.get(i).setId(name + i);
1524           richtextList.get(i).setName(name + i);
1525         }
1526         addUIFormInput(uiMulti);
1527         if(label != null) uiMulti.setLabel(label);
1528       }
1529     } else {
1530       if (getChildById(name) == null && richtextList.size() > 0)
1531         addUIFormInput(richtextList.get(0));
1532     }
1533     renderField(name);
1534   }
1535 
1536   public void addRichtextField(String name, String[] arguments) throws Exception {
1537     addRichtextField(name,null,arguments);
1538   }
1539 
1540   public Node getChildNode() throws Exception {
1541     if(childPath == null) return null;
1542     return (Node) getSession().getItem(childPath);
1543   }
1544 
1545   public String getContentType() { return contentType; };
1546 
1547   public Map<String, JcrInputProperty> getInputProperties() { return properties; }
1548 
1549   public Map<String, String> getInputOptions() { return options; }
1550 
1551   public JcrInputProperty getInputProperty(String name) { return properties.get(name); }
1552   public String getInputOption(String name) { return options.get(name); }
1553   public JCRResourceResolver getJCRResourceResolver() { return resourceResolver; }
1554 
1555   public Node getNode() {
1556     if(nodePath == null) return null;
1557     try {
1558       return (Node) getSession().getItem(nodePath);
1559     } catch (Exception e) {
1560       return null;
1561     }
1562   }
1563 
1564   public String getPropertyName(String jcrPath) {
1565     return jcrPath.substring(jcrPath.lastIndexOf("/") + 1);
1566   }
1567 
1568   public String getSelectBoxFieldValue(String name) {
1569     UIFormSelectBox uiSelectBox = findComponentById(name);
1570     if (uiSelectBox != null) return uiSelectBox.getValue();
1571     return null;
1572   }
1573 
1574   public List<String> getSelectedBoxFieldValue(String name) {
1575     UIFormSelectBox uiSelectBox = findComponentById(name);
1576     if (uiSelectBox != null) return Arrays.asList(uiSelectBox.getSelectedValues());
1577     return null;
1578   }
1579 
1580   public Session getSession() throws Exception {
1581     return WCMCoreUtils.getUserSessionProvider().getSession(workspaceName, getRepository());
1582   }
1583 
1584   public String getTemplate() {
1585     TemplateService templateService = getApplicationComponent(TemplateService.class);
1586     String userName = Util.getPortalRequestContext().getRemoteUser();
1587     try {
1588       return templateService.getTemplatePathByUser(true, contentType, userName);
1589     } catch (Exception e) {
1590       UIApplication uiApp = getAncestorOfType(UIApplication.class);
1591       Object[] arg = { contentType };
1592       uiApp.addMessage(new ApplicationMessage("UIDialogForm.msg.not-support-contenttype", arg, ApplicationMessage.ERROR));
1593       return null;
1594     }
1595   }
1596 
1597   public boolean isResetForm() { return isResetForm; }
1598 
1599   public void onchange(Event<?> event) throws Exception {
1600   }
1601 
1602   @Override
1603   public void processAction(WebuiRequestContext context) throws Exception {
1604     String action = context.getRequestParameter(UIForm.ACTION);
1605     boolean clearInterceptor = false;
1606     if (SAVE_ACTION.equalsIgnoreCase(action) || SAVE_AND_CLOSE.equalsIgnoreCase(action)) {
1607       try {
1608         if (executePreSaveEventInterceptor()) {
1609           super.processAction(context);
1610           String nodePath_ = (String) context.getAttribute("nodePath");
1611           if (nodePath_ != null) {
1612             executePostSaveEventInterceptor(nodePath_);
1613             clearInterceptor = true;
1614           }
1615         } else {
1616           context.setProcessRender(true);
1617           super.processAction(context);
1618         }
1619       } finally {
1620         if (clearInterceptor) {
1621           prevScriptInterceptor.clear();
1622           postScriptInterceptor.clear();
1623         }
1624       }
1625     } else {
1626       super.processAction(context);
1627     }
1628   }
1629 
1630   public void removeComponent(String name) {
1631     if (!properties.isEmpty() && properties.containsKey(name)) {
1632       properties.remove(name);
1633       String jcrPath = propertiesName.get(name);
1634       propertiesName.remove(name);
1635       fieldNames.remove(jcrPath);
1636       removeChildById(name);
1637     }
1638   }
1639 
1640   private String getResourceBundle(WebuiRequestContext context, String key) {
1641     try {
1642       ResourceBundle rs = context.getApplicationResourceBundle();
1643       return rs.getString(key);
1644     } catch(MissingResourceException e) {
1645       if (LOG.isWarnEnabled()) {
1646         LOG.warn("Missing resource " + key);
1647       }
1648       key = key.contains(".") ? key.substring(key.lastIndexOf(".") + 1) : key;
1649       return key;
1650     }
1651   }
1652 
1653   public void renderField(String name) throws Exception {
1654     UIComponent uiInput = findComponentById(name);
1655     WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
1656     Writer w = context.getWriter();
1657     if(componentSelectors.get(name) != null && name.equals(componentSelectors.get(name).get("returnField"))) {
1658       uiInput.processRender(context);
1659     } else {
1660       uiInput.processRender(context);
1661     }
1662     if(componentSelectors.get(name) != null) {
1663       Map<String,String> fieldPropertiesMap = componentSelectors.get(name);
1664       String fieldName = fieldPropertiesMap.get("returnField");
1665       String iconClass = "uiIconPlus";
1666       if(fieldPropertiesMap.get("selectorIcon") != null) {
1667         iconClass = fieldPropertiesMap.get("selectorIcon");
1668       }
1669       ResourceBundle rs = context.getApplicationResourceBundle();
1670       String showComponent = getResourceBundle(context, getId().concat(".title.ShowComponent"));
1671       String removeReference = getResourceBundle(context, getId().concat(".title.removeReference"));
1672       if (name.equals(fieldName)) {
1673         w.write("<a rel=\"tooltip\" data-placement=\"bottom\" class=\"actionIcon\" title=\"" + showComponent + "\""
1674             + "onclick=\"javascript:eXo.webui.UIForm.submitEvent('" + "" + getId()
1675             + "','ShowComponent','&objectId=" + fieldName + "' )\"><i"
1676             + " class='"
1677             + iconClass + " uiIconLightGray'></i></a>");
1678         /* No need Remove action if uiInput is UIFormMultiValueInputSet */
1679         if (!UIFormMultiValueInputSet.class.isInstance(uiInput))
1680           w.write("<a rel=\"tooltip\" data-placement=\"bottom\" class=\"actionIcon\" title=\""
1681               + removeReference
1682               + "\""
1683               + "onclick=\"javascript:eXo.webui.UIForm.submitEvent('"
1684               + ""
1685               + getId()
1686               + "','RemoveReference','&objectId="
1687               + fieldName
1688               + "' )\"><i"
1689               +" class='uiIconTrash uiIconLightGray'></i>"
1690               + "</a>");
1691       }
1692     }
1693   }
1694 
1695   public String getImage(Node node, String nodeTypeName) throws Exception {
1696     DownloadService dservice = getApplicationComponent(DownloadService.class);
1697     Node imageNode = node.getNode(nodeTypeName);
1698     InputStream input = imageNode.getProperty(Utils.JCR_DATA).getStream();
1699     InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image");
1700     dresource.setDownloadName(node.getName());
1701     return dservice.getDownloadLink(dservice.addDownloadResource(dresource));
1702   }
1703 
1704   public String getImage(InputStream input, String nodeName) throws Exception {
1705     DownloadService dservice = getApplicationComponent(DownloadService.class);
1706     InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image");
1707     dresource.setDownloadName(nodeName);
1708     return dservice.getDownloadLink(dservice.addDownloadResource(dresource));
1709   }
1710   @Deprecated
1711   /**
1712    * Deprecated method, should used removeData(String path) next time
1713    */
1714   public boolean dataRemoved() { return dataRemoved_; }
1715   @Deprecated
1716   public void setDataRemoved(boolean dataRemoved) { dataRemoved_ = dataRemoved; }
1717 
1718   /**
1719    * Mark a uploaded field as removed.
1720    *
1721    * @param       path: of property content binarydata for uploading
1722    */
1723   public void removeData(String path) {
1724     if (!removedBinary.contains(path)) {
1725       removedBinary.add(path);
1726     }
1727   }
1728   /**
1729    * Checking the binary field is removed or not
1730    *
1731    * @param       path: of property content binarydata for uploading
1732    * @return    : True if the uploaded field is removed from UI
1733    */
1734   public boolean isDataRemoved(String path) {
1735     return removedBinary.contains(path);
1736   }
1737   public void clearDataRemovedList() {
1738     removedBinary.clear();
1739   }
1740   public void resetProperties() { properties.clear(); }
1741 
1742   public void resetInterceptors(){
1743     this.prevScriptInterceptor.clear();
1744     this.postScriptInterceptor.clear();
1745   }
1746 
1747   public void setChildPath(String childPath) { this.childPath = childPath; }
1748 
1749   public void setContentType(String type) { this.contentType = type; }
1750 
1751   public void setInputProperty(String name, JcrInputProperty value) { properties.put(name, value); }
1752 
1753   public void setInputOption(String name, String value) { options.put(name, value); }
1754 
1755   public void setIsNotEditNode(boolean isNotEditNode) { this.isNotEditNode = isNotEditNode; }
1756 
1757   public void setIsNTFile(boolean isNTFile) { this.isNTFile = isNTFile; }
1758 
1759   public void setIsOnchange(boolean isOnchange) { this.isOnchange = isOnchange; }
1760 
1761   public void setIsResetForm(boolean isResetForm) { this.isResetForm = isResetForm; }
1762 
1763   public void setIsResetMultiField(boolean isResetMultiField) {
1764     this.isResetMultiField = isResetMultiField;
1765   }
1766 
1767   public void setIsUpdateSelect(boolean isUpdateSelect) { this.isUpdateSelect = isUpdateSelect; }
1768 
1769   public void setJCRResourceResolver(JCRResourceResolver resourceResolver) {
1770     this.resourceResolver = resourceResolver;
1771   }
1772 
1773   public void setNodePath(String nodePath) { this.nodePath = nodePath; }
1774 
1775   public String getNodePath() { return nodePath; }
1776 
1777   public void setRepositoryName(String repositoryName){ this.repositoryName = repositoryName; }
1778 
1779   public void setStoredPath(String storedPath) { this.storedPath = storedPath; }
1780 
1781   public String getStoredPath() { return storedPath; }
1782 
1783   public void setWorkspace(String workspace) { this.workspaceName = workspace; }
1784 
1785   public String getLastModifiedDate() throws Exception {
1786     return getLastModifiedDate(getNode());
1787   }
1788 
1789   public String getLastModifiedDate(Node node) {
1790     String d = StringUtils.EMPTY;
1791       try {
1792         if (node.hasProperty("exo:dateModified")) {
1793           Locale locale = Util.getPortalRequestContext().getLocale();
1794           DateFormat dateFormater = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale);
1795           Calendar calendar = node.getProperty("exo:dateModified").getValue().getDate();
1796           d = dateFormater.format(calendar.getTime());
1797         }
1798       } catch (ValueFormatException e) { d = StringUtils.EMPTY;
1799       } catch (IllegalStateException e) { d = StringUtils.EMPTY;
1800       } catch (PathNotFoundException e) { d = StringUtils.EMPTY;
1801       } catch (RepositoryException e) { d = StringUtils.EMPTY;
1802       }
1803     return d;
1804   }
1805 
1806   protected List<String> getRemovedNodes() { return removedNodes; }
1807 
1808   public void addRemovedNode(String path) { removedNodes.add(path); }
1809 
1810   public void clearRemovedNode() { removedNodes = new ArrayList<String>(); }
1811 
1812   private void executePostSaveEventInterceptor(String nodePath_) throws Exception {
1813     if (postScriptInterceptor.size() > 0) {
1814       String path = nodePath_ + "&workspaceName=" + this.workspaceName + "&repository="
1815           + this.repositoryName;
1816         for (String interceptor : postScriptInterceptor) {
1817           this.executeScript(interceptor, path, null, true);
1818         }
1819     }
1820   }
1821 
1822   private boolean executePreSaveEventInterceptor() throws Exception {
1823     if (!prevScriptInterceptor.isEmpty()) {
1824       Map<String, JcrInputProperty> maps = DialogFormUtil.prepareMap(this.getChildren(),
1825           getInputProperties(), getInputOptions());
1826       for (String interceptor : prevScriptInterceptor) {
1827         if(!executeScript(interceptor, maps, null, false)){
1828           return false;
1829         }
1830       }
1831     }
1832     return true;
1833   }
1834 
1835   private boolean executeScript(String script, Object o, String[] params, boolean printException)
1836       throws Exception {
1837     ScriptService scriptService = getApplicationComponent(ScriptService.class);
1838     try {
1839       CmsScript dialogScript = scriptService.getScript(script);
1840       if (params != null) {
1841         dialogScript.setParams(params);
1842       }
1843       dialogScript.execute(o);
1844       return true;
1845     } catch (Exception e) {
1846       if(printException){
1847         if (LOG.isWarnEnabled()) {
1848           LOG.warn("An unexpected error occurs", e);
1849         }
1850       } else {
1851         UIApplication uiApp = getAncestorOfType(UIApplication.class);
1852         if (e instanceof DialogFormException) {
1853           for (ApplicationMessage message : ((DialogFormException) e).getMessages()) {
1854             uiApp.addMessage(message);
1855           }
1856         } else {
1857           JCRExceptionManager.process(uiApp, e);
1858         }
1859       }
1860     }
1861     return false;
1862   }
1863 
1864   private String getNodePathByUUID(String uuid) throws Exception{
1865     String[] workspaces = getRepository().getWorkspaceNames();
1866     Node node = null;
1867     for(String ws : workspaces) {
1868       try{
1869         node = WCMCoreUtils.getSystemSessionProvider().getSession(ws, getRepository()).getNodeByUUID(uuid);
1870         return ws + ":" + node.getPath();
1871       } catch(ItemNotFoundException e) {
1872         continue;
1873       }
1874     }
1875     if (LOG.isErrorEnabled()) {
1876       LOG.error("No node with uuid ='" + uuid + "' can be found");
1877     }
1878     return null;
1879   }
1880 
1881   private ManageableRepository getRepository() throws Exception{
1882     RepositoryService repositoryService  = getApplicationComponent(RepositoryService.class);
1883     return repositoryService.getCurrentRepository();
1884   }
1885 
1886   private UIFormMultiValueInputSet renderMultiValuesInput(Class<? extends UIFormInputBase<?>> type, String name,String label) throws Exception{
1887     UIFormMultiValueInputSet ret = addMultiValuesInput(type, name, label);
1888     renderField(name);
1889     return ret;
1890   }
1891 
1892   private UIFormMultiValueInputSet addMultiValuesInput(Class<? extends UIFormInputBase<?>> type, String name,String label) throws Exception{
1893     UIFormMultiValueInputSet uiMulti = null;
1894     if (UIUploadInput.class.isAssignableFrom(type)) {
1895       uiMulti = createUIComponent(UIFormUploadMultiValueInputSet.class, null, null);
1896     }
1897     else {
1898       uiMulti = createUIComponent(UIFormMultiValueInputSet.class, null, null);
1899     }
1900     uiMulti.setId(name);
1901     uiMulti.setName(name);
1902     uiMulti.setType(type);
1903     addUIFormInput(uiMulti);
1904     if(label != null) uiMulti.setLabel(label);
1905     return uiMulti;
1906   }
1907 
1908   static  public class OnchangeActionListener extends EventListener<UIDialogForm> {
1909     public void execute(Event<UIDialogForm> event) throws Exception {
1910       event.getSource().isOnchange = true;
1911       event.getSource().onchange(event);
1912     }
1913   }
1914 
1915   public boolean isOnchange() {
1916     return isOnchange;
1917   }
1918 
1919   public void processRenderAction() throws Exception {
1920     WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
1921     Writer writer = context.getWriter();
1922     writer.append("<div class=\"uiAction uiActionBorder\">");
1923     String[] listAction = getActions();
1924     ResourceBundle res = context.getApplicationResourceBundle();
1925     String actionLabel;
1926     String link;
1927     for (String action : listAction) {
1928       try {
1929         actionLabel = res.getString(getName() + ".action." + action);
1930       } catch (MissingResourceException e) {
1931         actionLabel = action;
1932       }
1933       link = event(action);
1934       writer.append("<button type=\"button\" class=\"btn\" onclick =\"")
1935             .append(link)
1936             .append("\">")
1937             .append(actionLabel)
1938             .append("</button>");
1939     }
1940     writer.append("</div>");
1941   }
1942 
1943   public Node getNodeByType(String nodeType) throws Exception {
1944     if (this.getNode() == null) return null;
1945     NodeIterator nodeIter = this.getNode().getNodes();
1946     while (nodeIter.hasNext()) {
1947       Node node = nodeIter.nextNode();
1948       if (node.isNodeType(nodeType))
1949         return node;
1950     }
1951     return null;
1952   }
1953 
1954   static public class AddActionListener extends EventListener<UIFormMultiValueInputSet> {
1955     public void execute(Event<UIFormMultiValueInputSet> event) throws Exception {
1956       UIFormMultiValueInputSet uiSet = event.getSource();
1957       String id = event.getRequestContext().getRequestParameter(OBJECTID);
1958       if (uiSet.getId().equals(id)) {
1959         // get max id
1960         List<UIComponent> children = uiSet.getChildren();
1961         if (children.size() > 0) {
1962           UIFormInputBase<?> uiInput = (UIFormInputBase<?>) children.get(children.size() - 1);
1963           String index = uiInput.getId();
1964           int maxIndex = Integer.parseInt(index.replaceAll(id, ""));
1965 
1966           UIDialogForm uiDialogForm = uiSet.getAncestorOfType(UIDialogForm.class);
1967           String[] arguments = uiDialogForm.uiMultiValueParam.get(uiSet.getName());
1968           UIFormInputBase<?> newUIInput = null;
1969           if (uiInput instanceof UIFormWYSIWYGInput) {
1970             newUIInput = uiDialogForm.getUIFormInputList(uiSet.getName(),
1971                                                          new UIFormWYSIWYGField(uiSet.getName(),
1972                                                                                 null,
1973                                                                                 arguments),
1974                                                          true).get(0);
1975           } else {
1976             newUIInput = uiDialogForm.getUIFormInputList(uiSet.getName(),
1977                                                          new UIFormRichtextField(uiSet.getName(),
1978                                                                                  null,
1979                                                                                  arguments),
1980                                                          true).get(0);
1981           }
1982 
1983           uiSet.addChild(newUIInput);
1984           newUIInput.setId(uiSet.getName() + (maxIndex + 1));
1985           newUIInput.setName(uiSet.getName() + (maxIndex + 1));
1986         }
1987       }
1988     }
1989   }
1990 
1991 }