View Javadoc

1   /**
2    * This file Copyright (c) 2013-2014 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.pages.app.action;
35  
36  import info.magnolia.context.MgnlContext;
37  import info.magnolia.event.EventBus;
38  import info.magnolia.i18nsystem.SimpleTranslator;
39  import info.magnolia.jcr.util.NodeTypes;
40  import info.magnolia.objectfactory.ComponentProvider;
41  import info.magnolia.pages.app.field.TemplateSelectorFieldFactory;
42  import info.magnolia.registry.RegistrationException;
43  import info.magnolia.rendering.template.TemplateDefinition;
44  import info.magnolia.rendering.template.registry.TemplateDefinitionRegistry;
45  import info.magnolia.ui.admincentral.dialog.action.CancelDialogActionDefinition;
46  import info.magnolia.ui.api.action.AbstractAction;
47  import info.magnolia.ui.api.action.ActionExecutionException;
48  import info.magnolia.ui.api.app.SubAppContext;
49  import info.magnolia.ui.api.app.SubAppEventBus;
50  import info.magnolia.ui.api.event.ContentChangedEvent;
51  import info.magnolia.ui.dialog.DialogView;
52  import info.magnolia.ui.dialog.action.CallbackDialogActionDefinition;
53  import info.magnolia.ui.dialog.definition.ConfiguredFormDialogDefinition;
54  import info.magnolia.ui.dialog.definition.FormDialogDefinition;
55  import info.magnolia.ui.dialog.formdialog.FormDialogPresenter;
56  import info.magnolia.ui.dialog.formdialog.FormDialogPresenterFactory;
57  import info.magnolia.ui.form.EditorCallback;
58  import info.magnolia.ui.form.definition.ConfiguredFormDefinition;
59  import info.magnolia.ui.form.definition.ConfiguredTabDefinition;
60  import info.magnolia.ui.form.field.definition.SelectFieldDefinition;
61  import info.magnolia.ui.form.field.definition.SelectFieldOptionDefinition;
62  import info.magnolia.ui.vaadin.gwt.client.shared.AreaElement;
63  import info.magnolia.ui.vaadin.integration.jcr.DefaultProperty;
64  import info.magnolia.ui.vaadin.integration.jcr.JcrNewNodeAdapter;
65  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;
66  import info.magnolia.ui.vaadin.integration.jcr.ModelConstants;
67  
68  import javax.inject.Inject;
69  import javax.inject.Named;
70  import javax.jcr.Node;
71  import javax.jcr.RepositoryException;
72  import javax.jcr.Session;
73  
74  import org.apache.commons.lang3.StringUtils;
75  import org.slf4j.Logger;
76  import org.slf4j.LoggerFactory;
77  
78  /**
79   * Adds a component underneath the area passed in {@link AreaElement}.
80   * Gets a list of available components for this area and creates a select field.
81   */
82  public class CreateComponentAction extends AbstractAction<CreateComponentActionDefinition> {
83  
84      private static final Logger log = LoggerFactory.getLogger(CreateComponentAction.class);
85  
86      private AreaElement area;
87      private EventBus eventBus;
88      private TemplateDefinitionRegistry templateDefinitionRegistry;
89      private SubAppContext subAppContext;
90      private ComponentProvider componentProvider;
91      private DialogView dialogView;
92      private FormDialogPresenterFactory formDialogPresenterFactory;
93      private final SimpleTranslator i18n;
94  
95      @Inject
96      public CreateComponentAction(CreateComponentActionDefinition definition, AreaElement area, @Named(SubAppEventBus.NAME) EventBus eventBus, TemplateDefinitionRegistry templateDefinitionRegistry,
97                                   SubAppContext subAppContext, ComponentProvider componentProvider, FormDialogPresenterFactory formDialogPresenterFactory, SimpleTranslator i18n) {
98          super(definition);
99          this.area = area;
100         this.eventBus = eventBus;
101         this.templateDefinitionRegistry = templateDefinitionRegistry;
102         this.subAppContext = subAppContext;
103         this.componentProvider = componentProvider;
104         this.formDialogPresenterFactory = formDialogPresenterFactory;
105         this.i18n = i18n;
106     }
107 
108     @Override
109     public void execute() throws ActionExecutionException {
110         final FormDialogDefinition dialogDefinition = buildNewComponentDialog(area.getAvailableComponents());
111 
112         final FormDialogPresenter formDialogPresenter = componentProvider.newInstance(FormDialogPresenter.class);
113         try {
114             String workspace = area.getWorkspace();
115             String path = area.getPath();
116             Session session = MgnlContext.getJCRSession(area.getWorkspace());
117             if (path == null || !session.itemExists(path)) {
118                 path = "/";
119             }
120             session = MgnlContext.getJCRSession(workspace);
121 
122             Node areaNode = session.getNode(path);
123 
124             final JcrNodeAdapter item = new JcrNewNodeAdapter(areaNode, NodeTypes.Component.NAME);
125             DefaultProperty<String> property = new DefaultProperty<String>(String.class, "0");
126             item.addItemProperty(ModelConstants.JCR_NAME, property);
127 
128             // perform custom chaining of dialogs
129             this.dialogView = formDialogPresenter.start(item, dialogDefinition, subAppContext, new ComponentCreationCallback(item, formDialogPresenter));
130         } catch (RepositoryException e) {
131             throw new ActionExecutionException(e);
132         }
133     }
134 
135     private void openDialog(final JcrNodeAdapter item, String dialogId) {
136 
137         final FormDialogPresenter dialogPresenter = formDialogPresenterFactory.createFormDialogPresenter(dialogId);
138         dialogPresenter.start(item, dialogId, subAppContext, new EditorCallback() {
139 
140             @Override
141             public void onSuccess(String actionName) {
142                 eventBus.fireEvent(new ContentChangedEvent(item.getItemId()));
143                 dialogPresenter.closeDialog();
144             }
145 
146             @Override
147             public void onCancel() {
148                 dialogPresenter.closeDialog();
149             }
150         });
151     }
152 
153     /**
154      * Builds a new {@link info.magnolia.ui.dialog.definition.FormDialogDefinition} containing actions and {@link info.magnolia.ui.form.definition.FormDefinition}.
155      * The definition will hold a {@link info.magnolia.ui.form.field.definition.SelectFieldDefinition} with the available components as options.
156      */
157     private FormDialogDefinition buildNewComponentDialog(String availableComponents) {
158 
159         ConfiguredFormDefinition form = new ConfiguredFormDefinition();
160 
161         ConfiguredTabDefinition tab = new ConfiguredTabDefinition();
162         tab.setName("components");
163 
164         SelectFieldDefinition select = new SelectFieldDefinition();
165         select.setName("mgnl:template");
166 
167         tab.addField(select);
168 
169         form.addTab(tab);
170 
171         String[] tokens = availableComponents.split(",");
172 
173         for (String token : tokens) {
174             try {
175                 TemplateDefinition templateDefinition = templateDefinitionRegistry.getTemplateDefinition(token);
176 
177                 SelectFieldOptionDefinition option = new SelectFieldOptionDefinition();
178                 option.setValue(templateDefinition.getId());
179                 option.setLabel(TemplateSelectorFieldFactory.getI18nTitle(templateDefinition));
180                 select.addOption(option);
181 
182             } catch (RegistrationException e) {
183                 log.error("Exception caught: {}", e.getMessage(), e);
184             }
185         }
186 
187         ConfiguredFormDialogDefinition dialog = new ConfiguredFormDialogDefinition();
188         dialog.setId("pages:newComponent");
189         dialog.setForm(form);
190 
191         CallbackDialogActionDefinition callbackAction = new CallbackDialogActionDefinition();
192         callbackAction.setName("commit");
193         dialog.getActions().put(callbackAction.getName(), callbackAction);
194 
195         CancelDialogActionDefinition cancelAction = new CancelDialogActionDefinition();
196         cancelAction.setName("cancel");
197         dialog.getActions().put(cancelAction.getName(), cancelAction);
198 
199         return dialog;
200     }
201 
202     private class ComponentCreationCallback implements EditorCallback {
203 
204         private final JcrNodeAdapter item;
205         private final FormDialogPresenter formDialogPresenter;
206 
207         public ComponentCreationCallback(JcrNodeAdapter item, FormDialogPresenter formDialogPresenter) {
208             this.item = item;
209             this.formDialogPresenter = formDialogPresenter;
210         }
211 
212         @Override
213         public void onSuccess(String actionName) {
214             String templateId = String.valueOf(item.getItemProperty(NodeTypes.Renderable.TEMPLATE).getValue());
215             try {
216                 TemplateDefinition templateDef = templateDefinitionRegistry.getTemplateDefinition(templateId);
217                 String dialogId = templateDef.getDialog();
218 
219                 if (StringUtils.isNotEmpty(dialogId)) {
220                     openDialog(item, dialogId);
221                 } else {
222                     // if there is no dialog defined for the component, persist the node as is and reload.
223                     try {
224                         final Node node = item.applyChanges();
225                         node.getSession().save();
226 
227                     } catch (RepositoryException e) {
228                         log.error("Exception caught: {}", e.getMessage(), e);
229                     }
230 
231                     eventBus.fireEvent(new ContentChangedEvent(item.getItemId()));
232                 }
233             } catch (RegistrationException e) {
234                 log.error("Exception caught: {}", e.getMessage(), e);
235             } finally {
236                 dialogView.close();
237             }
238         }
239 
240         @Override
241         public void onCancel() {
242             formDialogPresenter.closeDialog();
243         }
244     }
245 }