View Javadoc
1   /**
2    * This file Copyright (c) 2013-2018 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.ui.framework.action;
35  
36  import info.magnolia.ui.api.action.AbstractAction;
37  import info.magnolia.ui.api.action.ActionDefinition;
38  import info.magnolia.ui.api.action.ActionExecutionException;
39  import info.magnolia.ui.api.context.UiContext;
40  import info.magnolia.ui.vaadin.integration.jcr.JcrItemAdapter;
41  import info.magnolia.ui.vaadin.integration.jcr.JcrItemUtil;
42  import info.magnolia.ui.vaadin.overlay.MessageStyleTypeEnum;
43  
44  import java.util.Comparator;
45  import java.util.LinkedHashMap;
46  import java.util.List;
47  import java.util.Map;
48  
49  import javax.jcr.RepositoryException;
50  
51  import org.apache.commons.lang3.StringUtils;
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  
55  import com.google.common.collect.Lists;
56  import com.google.common.collect.Ordering;
57  
58  /**
59   * Abstract multi-item Action that defines the default behavior.
60   *
61   * @param <D> the action definition type
62   */
63  public abstract class AbstractMultiItemAction<D extends ActionDefinition> extends AbstractAction<D> {
64  
65      private final Logger log = LoggerFactory.getLogger(getClass());
66  
67      private final List<JcrItemAdapter> items;
68      private Map<JcrItemAdapter, Exception> failedItems;
69      private final UiContext uiContext;
70      // the item that is currently BEING processed
71      private JcrItemAdapter currentItem;
72  
73      protected AbstractMultiItemAction(D definition, JcrItemAdapter item, UiContext uiContext) {
74          this(definition, Lists.newArrayList(item), uiContext);
75      }
76  
77      protected AbstractMultiItemAction(D definition, List<JcrItemAdapter> items, UiContext uiContext) {
78          super(definition);
79          this.items = items;
80          this.uiContext = uiContext;
81      }
82  
83      /**
84       * Executes the action on ONE item.
85       */
86      protected abstract void executeOnItem(JcrItemAdapter item) throws Exception;
87  
88      /**
89       * Returns the message to display, if the execution succeeds on ALL items. May return <code>null</code>,
90       * if the implementing action handles the user notification on its own.
91       */
92      protected abstract String getSuccessMessage();
93  
94      /**
95       * Returns the message to display, if the execution fails on at least ONE item. May return <code>null</code>,
96       * if the implementing action handles the user notification on its own.
97       */
98      protected abstract String getFailureMessage();
99  
100     @Override
101     public void execute() throws ActionExecutionException {
102         failedItems = new LinkedHashMap<JcrItemAdapter, Exception>();
103 
104         for (JcrItemAdapter item : getSortedItems(getItemComparator())) {
105             this.currentItem = item;
106             try {
107                 executeOnItem(item);
108             } catch (Exception ex) {
109                 failedItems.put(item, ex);
110             }
111         }
112         this.currentItem = null;
113 
114         if (failedItems.isEmpty()) {
115             String message = getSuccessMessage();
116             if (StringUtils.isNotBlank(message)) {
117                 uiContext.openNotification(MessageStyleTypeEnum.INFO, true, message);
118             }
119         } else {
120             String message = getErrorNotification();
121             if (StringUtils.isNotBlank(message)) {
122                 uiContext.openNotification(MessageStyleTypeEnum.ERROR, false, message);
123             }
124         }
125     }
126 
127     protected String getErrorNotification() {
128         String failureMessage = getFailureMessage();
129         if (failureMessage != null) {
130             StringBuilder notification = new StringBuilder(failureMessage);
131             notification.append("<ul>");
132             for (JcrItemAdapter item : failedItems.keySet()) {
133                 Exception ex = failedItems.get(item);
134                 notification.append("<li>").append("<b>");
135                 notification.append(JcrItemUtil.getItemPath(item.getJcrItem())).append("</b>: ").append(ex.getMessage());
136                 notification.append("</li>");
137             }
138             notification.append("</ul>");
139             return notification.toString();
140         }
141         return null;
142     }
143 
144     protected List<JcrItemAdapter> getItems() {
145         return this.items;
146     }
147 
148     /**
149      * @return the sorted Items list based on the desired {@link Comparator}.
150      */
151     protected List<JcrItemAdapter> getSortedItems(Comparator<JcrItemAdapter> comparator) {
152         return Ordering.from(comparator).sortedCopy(this.items);
153     }
154 
155     protected UiContext getUiContext() {
156         return this.uiContext;
157     }
158 
159     protected Map<JcrItemAdapter, Exception> getFailedItems() {
160         return this.failedItems;
161     }
162 
163     /**
164      * Returns the item that is currently <b>being</b> processed - i.e. <code>null</code> if the {@link #execute()} method is not running.
165      */
166     protected JcrItemAdapter getCurrentItem() {
167         return this.currentItem;
168     }
169 
170     /**
171      * This method should be used <b>only in tests</b> (when the test does not call the {@link #execute()} method but e.g. only the {@link AbstractCommandAction#onPreExecute()} so the current item hasn't been set.
172      */
173     protected void setCurrentItem(JcrItemAdapter item) {
174         this.currentItem = item;
175     }
176 
177     /**
178      * Create a {@link Comparator} used to sort {@link JcrItemAdapter}.
179      * First element of the list are child items:
180      * - /a/b.property
181      * - /a/b
182      * - /a
183      * - /
184      */
185     protected Comparator<JcrItemAdapter> getItemComparator() {
186         return new Comparator<JcrItemAdapter>() {
187             @Override
188             public int compare(JcrItemAdapter o1, JcrItemAdapter o2) {
189                 try {
190                     int res = o2.getJcrItem().getDepth() - o1.getJcrItem().getDepth();
191                     return res;
192                 } catch (RepositoryException e) {
193                     return 0;
194                 }
195             }
196         };
197     }
198 }