View Javadoc
1   /*
2    * Copyright (C) 2003-2007 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.component.admin.views;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import javax.jcr.AccessDeniedException;
23  import javax.jcr.Node;
24  import javax.jcr.RepositoryException;
25  import javax.jcr.version.VersionHistory;
26  
27  import org.exoplatform.ecm.jcr.model.VersionNode;
28  import org.exoplatform.ecm.resolver.JCRResourceResolver;
29  import org.exoplatform.ecm.webui.form.validator.ECMNameValidator;
30  import org.exoplatform.ecm.webui.utils.Utils;
31  import org.exoplatform.groovyscript.text.TemplateService;
32  import org.exoplatform.services.cms.BasePath;
33  import org.exoplatform.services.cms.views.ManageViewService;
34  import org.exoplatform.services.jcr.RepositoryService;
35  import org.exoplatform.services.jcr.ext.common.SessionProvider;
36  import org.exoplatform.services.wcm.core.NodeLocation;
37  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
38  import org.exoplatform.web.application.ApplicationMessage;
39  import org.exoplatform.webui.config.annotation.ComponentConfig;
40  import org.exoplatform.webui.config.annotation.EventConfig;
41  import org.exoplatform.webui.core.UIApplication;
42  import org.exoplatform.webui.core.UIPopupWindow;
43  import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
44  import org.exoplatform.webui.core.model.SelectItemOption;
45  import org.exoplatform.webui.event.Event;
46  import org.exoplatform.webui.event.Event.Phase;
47  import org.exoplatform.webui.event.EventListener;
48  import org.exoplatform.webui.form.UIForm;
49  import org.exoplatform.webui.form.UIFormSelectBox;
50  import org.exoplatform.webui.form.UIFormStringInput;
51  import org.exoplatform.webui.form.UIFormTextAreaInput;
52  import org.exoplatform.webui.form.input.UICheckBoxInput;
53  import org.exoplatform.webui.form.validator.MandatoryValidator;
54  
55  /**
56   * Created by The eXo Platform SARL Author : Tran The Trong trongtt@gmail.com
57   * July 3, 2006 10:07:15 AM
58   */
59  @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = {
60    @EventConfig(listeners = UITemplateForm.SaveActionListener.class),
61    @EventConfig(phase = Phase.DECODE, listeners = UITemplateForm.CancelActionListener.class),
62    @EventConfig(phase = Phase.DECODE, listeners = UITemplateForm.ResetActionListener.class),
63    @EventConfig(phase = Phase.DECODE, listeners = UITemplateForm.ChangeActionListener.class),
64    @EventConfig(phase = Phase.DECODE, listeners = UITemplateForm.RestoreActionListener.class) })
65  public class UITemplateForm extends UIForm {
66  
67    final static private String FIELD_VERSION       = "version";
68  
69    final static private String FIELD_CONTENT       = "content";
70  
71    final static private String FIELD_NAME          = "name";
72  
73    final static private String FIELD_HOMETEMPLATE  = "homeTemplate";
74  
75    final static private String FIELD_ENABLEVERSION = "enableVersion"; 
76  
77  
78    private NodeLocation      template_           = null;
79  
80    private List<String>        listVersion         = new ArrayList<String>();
81  
82    private String               baseVersionName_;
83  
84    private VersionNode         selectedVersion_;
85  
86    public boolean              isAddNew_           = false;
87  
88    private String              templatePath_;
89  
90    private VersionNode         rootVersionNode;
91  
92    private org.exoplatform.services.cms.templates.TemplateService     templateService;
93  
94    public UITemplateForm() throws Exception {
95      templateService = WCMCoreUtils.getService(org.exoplatform.services.cms.templates.TemplateService.class);
96      List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>();
97      UIFormSelectBox versions = new UIFormSelectBox(FIELD_VERSION, FIELD_VERSION, options);
98      versions.setOnChange("Change");
99      versions.setRendered(false);
100     addUIFormInput(versions);
101     addUIFormInput(new UIFormTextAreaInput(FIELD_CONTENT, FIELD_CONTENT, null)
102     .addValidator(MandatoryValidator.class));
103     addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null).addValidator(
104                                                                                     MandatoryValidator.class).addValidator(ECMNameValidator.class));
105     List<SelectItemOption<String>> typeList = new ArrayList<SelectItemOption<String>>();
106     addUIFormInput(new UIFormSelectBox(FIELD_HOMETEMPLATE, FIELD_HOMETEMPLATE, typeList));
107     UICheckBoxInput enableVersion = new UICheckBoxInput(FIELD_ENABLEVERSION,
108                                                         FIELD_ENABLEVERSION, null);
109     enableVersion.setRendered(false);
110     addUIFormInput(enableVersion);
111   }
112 
113   public String getRepository() {
114     try {
115       return getApplicationComponent(RepositoryService.class).getCurrentRepository()
116           .getConfiguration()
117           .getName();
118     } catch (RepositoryException e) {
119       return null;
120     }
121   }
122 
123   public void updateOptionList() throws Exception {
124     getUIFormSelectBox(FIELD_HOMETEMPLATE).setOptions(getOptionList());
125   }
126 
127   public List<SelectItemOption<String>> getOptionList() throws Exception {
128     List<SelectItemOption<String>> typeList = new ArrayList<SelectItemOption<String>>();
129     SessionProvider provider = WCMCoreUtils.getSystemSessionProvider();
130     if (getId().equalsIgnoreCase("ecmTempForm")) {
131       Node ecmTemplateHome = getApplicationComponent(ManageViewService.class).getTemplateHome(
132                                                                                               BasePath.ECM_EXPLORER_TEMPLATES, provider);
133       if (ecmTemplateHome != null) {
134         typeList.add(new SelectItemOption<String>(ecmTemplateHome.getName(), ecmTemplateHome
135             .getPath()));
136       }
137     } 
138     return typeList;
139   }
140 
141   public boolean canEnableVersionning(Node node) throws Exception {
142     return node.canAddMixin(Utils.MIX_VERSIONABLE);
143   }
144 
145   private boolean isVersioned(Node node) throws RepositoryException {
146     return node.isNodeType(Utils.MIX_VERSIONABLE);
147   }
148 
149   private VersionNode getRootVersion(Node node) throws Exception {
150     VersionHistory vH = node.getVersionHistory();
151     return (vH != null) ? new VersionNode(vH.getRootVersion(), node.getSession()) : null;
152   }
153 
154   private List<String> getNodeVersions(List<VersionNode> children) throws Exception {
155     List<VersionNode> child = new ArrayList<VersionNode>();
156     for (VersionNode vNode : children) {
157       listVersion.add(vNode.getName());
158       child = vNode.getChildren();
159       if (!child.isEmpty())
160         getNodeVersions(child);
161     }
162     return listVersion;
163   }
164 
165   private List<SelectItemOption<String>> getVersionValues(Node node) throws Exception {
166     List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>();
167     List<VersionNode> children = getRootVersion(node).getChildren();
168     listVersion.clear();
169     List<String> versionList = getNodeVersions(children);
170     for (int i = 0; i < versionList.size(); i++) {
171       for (int j = i + 1; j < versionList.size(); j++) {
172         if (Integer.parseInt(versionList.get(j)) < Integer.parseInt(versionList.get(i))) {
173           String temp = versionList.get(i);
174           versionList.set(i, versionList.get(j));
175           versionList.set(j, temp);
176         }
177       }
178       options.add(new SelectItemOption<String>(versionList.get(i), versionList.get(i)));
179     }
180     return options;
181   }
182 
183   public void refresh() throws Exception {
184     UIFormSelectBox versionField = getUIFormSelectBox(FIELD_VERSION);
185     if (isAddNew_) {
186       versionField.setRendered(false);
187       getUIFormTextAreaInput(FIELD_CONTENT).setValue(null);
188       getUIStringInput(FIELD_NAME).setDisabled(false).setValue(null);
189       getUIFormSelectBox(FIELD_HOMETEMPLATE).setValue(null);
190       getUIFormSelectBox(FIELD_HOMETEMPLATE).setDisabled(false);
191       getUICheckBoxInput(FIELD_ENABLEVERSION).setRendered(false);
192       template_ = null;
193       selectedVersion_ = null;
194       baseVersionName_ = null;
195       return;
196     }
197     update(template_.getPath(), null);
198   }
199 
200   public void update(String templatePath, VersionNode selectedVersion) throws Exception {
201     if (templatePath != null) {
202       templatePath_ = templatePath;
203       Node templateNode = getApplicationComponent(ManageViewService.class).
204           getTemplate(templatePath, WCMCoreUtils.getSystemSessionProvider());
205       template_ = NodeLocation.getNodeLocationByNode(templateNode);
206       getUIStringInput(FIELD_NAME).setValue(templateNode.getName());
207       getUIStringInput(FIELD_NAME).setDisabled(true);
208       String value = templatePath.substring(0, templatePath.lastIndexOf("/"));
209       getUIFormSelectBox(FIELD_HOMETEMPLATE).setValue(value);
210       getUIFormSelectBox(FIELD_HOMETEMPLATE).setDisabled(false);
211       getUICheckBoxInput(FIELD_ENABLEVERSION).setRendered(true);
212       if (isVersioned(templateNode)) {
213         rootVersionNode = getRootVersion(templateNode);
214         baseVersionName_ = templateNode.getBaseVersion().getName();
215         List<SelectItemOption<String>> options = getVersionValues(templateNode);
216         getUIFormSelectBox(FIELD_VERSION).setOptions(options).setRendered(true);
217         getUIFormSelectBox(FIELD_VERSION).setValue(baseVersionName_);
218         getUICheckBoxInput(FIELD_ENABLEVERSION).setChecked(true).setDisabled(true);
219         if (options.size() > 1)
220           setActions(new String[] { "Save", "Reset", "Restore", "Cancel" });
221         else
222           setActions(new String[] { "Save", "Reset", "Cancel" });
223       } else if (canEnableVersionning(templateNode)) {
224         getUIFormSelectBox(FIELD_VERSION).setRendered(false);
225         getUICheckBoxInput(FIELD_ENABLEVERSION).setChecked(false).setDisabled(false);
226       }
227     }
228     if (selectedVersion != null) {
229       NodeLocation.getNodeByLocation(template_).restore(selectedVersion.getName(), false);
230       selectedVersion_ = selectedVersion;
231       Object[] args = { getUIStringInput(FIELD_VERSION).getValue() };
232       UIApplication app = getAncestorOfType(UIApplication.class);
233       app.addMessage(new ApplicationMessage("UITemplateForm.msg.version-restored", args));
234     }
235     String content = templateService.getTemplate(NodeLocation.getNodeByLocation(template_));
236     getUIFormTextAreaInput(FIELD_CONTENT).setValue(content);
237   }
238 
239   static public class SaveActionListener extends EventListener<UITemplateForm> {
240     public void execute(Event<UITemplateForm> event) throws Exception {
241       UITemplateForm uiForm = event.getSource();
242       String templateName = uiForm.getUIStringInput(FIELD_NAME).getValue().trim();
243       String content = uiForm.getUIFormTextAreaInput(FIELD_CONTENT).getValue();
244       String homeTemplate = uiForm.getUIFormSelectBox(FIELD_HOMETEMPLATE).getValue();
245       ManageViewService manageViewService = uiForm.getApplicationComponent(ManageViewService.class);
246       UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class);
247       if (homeTemplate == null) {
248         String tempPath = uiForm.template_.getPath();
249         homeTemplate = tempPath.substring(0, tempPath.lastIndexOf("/"));
250       }
251       boolean isEnableVersioning = uiForm.getUICheckBoxInput(FIELD_ENABLEVERSION).isChecked();
252       String path = null;
253       if (uiForm.getId().equalsIgnoreCase(UIECMTemplateList.ST_ecmTempForm)) {
254         List<Node> ecmTemps = manageViewService.getAllTemplates(BasePath.ECM_EXPLORER_TEMPLATES,
255                                                                 WCMCoreUtils.getSystemSessionProvider());
256         for (Node temp : ecmTemps) {
257           if (temp.getName().equals(templateName) && uiForm.isAddNew_) {
258             Object[] args = { templateName };
259             uiApp.addMessage(new ApplicationMessage("UITemplateForm.msg.template-name-exist", args,
260                                                     ApplicationMessage.WARNING));
261 
262             return;
263           }
264         }
265       }
266       if (uiForm.isAddNew_) {
267         try {
268           if (uiForm.templatePath_ != null) {
269             String oldHomeTemplate = uiForm.templatePath_.substring(0, uiForm.templatePath_.lastIndexOf("/"));
270             if (!oldHomeTemplate.equals(homeTemplate)) {
271               Node oldNode = manageViewService.getTemplate(uiForm.templatePath_, WCMCoreUtils.getSystemSessionProvider());
272               oldNode.remove();
273               manageViewService.getTemplate(oldHomeTemplate, WCMCoreUtils.getSystemSessionProvider()).save();
274             }
275           }
276 
277           path = manageViewService.addTemplate(templateName,
278                                                content,
279                                                homeTemplate,
280                                                WCMCoreUtils.getSystemSessionProvider());
281           uiForm.template_ = NodeLocation.getNodeLocationByNode(manageViewService.getTemplate(path, 
282                                                                                               WCMCoreUtils.getSystemSessionProvider()));
283         } catch (AccessDeniedException ex) {
284           uiApp.addMessage(new ApplicationMessage("UITemplateForm.msg.add-permission-denied",
285                                                   null,
286                                                   ApplicationMessage.WARNING));
287 
288           return;
289         }
290       } else {
291         try {
292           Node templateNode = NodeLocation.getNodeByLocation(uiForm.template_);
293           if (isEnableVersioning) {
294             if (!templateNode.isNodeType(Utils.MIX_VERSIONABLE)) {
295               templateNode.addMixin(Utils.MIX_VERSIONABLE);
296               templateNode.save();
297             } else {
298               templateNode.checkout();
299             }
300           }
301           path = manageViewService.updateTemplate(templateName,
302                                                   content,
303                                                   homeTemplate,
304                                                   WCMCoreUtils.getSystemSessionProvider());
305           templateNode.save();
306           if (isEnableVersioning) {
307             templateNode.checkin();
308           }
309         } catch (AccessDeniedException ex) {
310           Object[] args = { "UIViewFormTabPane.label.option." + templateName };
311           uiApp.addMessage(new ApplicationMessage("UITemplateForm.msg.edit-permission-denied",
312                                                   args,
313                                                   ApplicationMessage.WARNING));
314 
315           return;
316         }
317       }
318       String workspaceName = NodeLocation.getNodeByLocation(uiForm.template_).getSession().getWorkspace().getName();
319       JCRResourceResolver resourceResolver = new JCRResourceResolver(workspaceName);
320       TemplateService templateService = uiForm.getApplicationComponent(TemplateService.class);
321       if (path != null) templateService.invalidateTemplate(path, resourceResolver);
322       UITemplateContainer uiTempContainer = uiForm.getAncestorOfType(UIPopupWindow.class).getParent();
323       UIECMTemplateList uiECMTempList = uiTempContainer.getChild(UIECMTemplateList.class);
324       uiECMTempList.refresh(uiECMTempList.getUIPageIterator().getCurrentPage());
325       if (uiForm.isAddNew_) {
326         uiTempContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Add");
327       } else {
328         uiTempContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Edit");
329       }
330       event.getRequestContext().addUIComponentToUpdateByAjax(uiTempContainer);
331     }
332   }
333 
334   static public class CancelActionListener extends EventListener<UITemplateForm> {
335     public void execute(Event<UITemplateForm> event) throws Exception {
336       UITemplateForm uiForm = event.getSource();
337       uiForm.refresh();
338       UITemplateContainer uiTempContainer = uiForm.getAncestorOfType(UIPopupWindow.class).getParent();
339       if (uiForm.isAddNew_) {
340         uiTempContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Add");
341       } else {
342         uiTempContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Edit");
343       }
344       event.getRequestContext().addUIComponentToUpdateByAjax(uiTempContainer);
345     }
346   }
347 
348   static public class ResetActionListener extends EventListener<UITemplateForm> {
349     public void execute(Event<UITemplateForm> event) throws Exception {
350       UITemplateForm uiForm = event.getSource();
351       UITemplateContainer uiTempContainer = uiForm.getAncestorOfType(UIPopupWindow.class).getParent();
352       if (uiForm.selectedVersion_ != null) {
353         if (!uiForm.selectedVersion_.getName().equals(uiForm.baseVersionName_)) {
354           Node templateNode = NodeLocation.getNodeByLocation(uiForm.template_);
355           templateNode.restore(uiForm.baseVersionName_, true);
356           templateNode.checkout();
357         }
358       }
359       uiForm.refresh();
360       UIECMTemplateList uiECMTempList = uiTempContainer.getChild(UIECMTemplateList.class);
361       uiECMTempList.refresh(uiECMTempList.getUIPageIterator().getCurrentPage());
362       event.getRequestContext().addUIComponentToUpdateByAjax(uiForm);
363     }
364   }
365 
366   static public class ChangeActionListener extends EventListener<UITemplateForm> {
367     public void execute(Event<UITemplateForm> event) throws Exception {
368       UITemplateForm uiForm = event.getSource();
369       String version = uiForm.getUIFormSelectBox(FIELD_VERSION).getValue();
370       String path = NodeLocation.getNodeByLocation(uiForm.template_).getVersionHistory().getVersion(version).getPath();
371       VersionNode versionNode = uiForm.rootVersionNode.findVersionNode(path);
372       Node frozenNode = versionNode.getNode(Utils.JCR_FROZEN);
373       String content = uiForm.templateService.getTemplate(frozenNode);
374       uiForm.getUIFormTextAreaInput(FIELD_CONTENT).setValue(content);
375       event.getRequestContext().addUIComponentToUpdateByAjax(uiForm);
376     }
377   }
378 
379   static public class RestoreActionListener extends EventListener<UITemplateForm> {
380     public void execute(Event<UITemplateForm> event) throws Exception {
381       UITemplateForm uiForm = event.getSource();
382       String version = uiForm.getUIFormSelectBox(FIELD_VERSION).getValue();
383       String path = NodeLocation.getNodeByLocation(uiForm.template_).getVersionHistory().getVersion(version).getPath();
384       VersionNode selectedVesion = uiForm.rootVersionNode.findVersionNode(path);
385       if (uiForm.baseVersionName_.equals(selectedVesion.getName()))
386         return;
387       uiForm.update(null, selectedVesion);
388       UITemplateContainer uiTempContainer = uiForm.getAncestorOfType(UIPopupWindow.class).getParent();
389       UIECMTemplateList uiECMTempList = uiTempContainer.getChild(UIECMTemplateList.class);
390       uiECMTempList.refresh(uiECMTempList.getUIPageIterator().getCurrentPage());
391       UITemplateContainer uiTemplateContainer = uiForm.getAncestorOfType(UITemplateContainer.class);
392       if (uiForm.isAddNew_) {
393         uiTemplateContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Add");
394       } else {
395         uiTemplateContainer.removeChildById(UIECMTemplateList.ST_ecmTempForm + "Edit");
396       }
397       event.getRequestContext().addUIComponentToUpdateByAjax(uiTempContainer);
398     }
399   }
400 }