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.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.ArrayList;
45  import java.util.Comparator;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Map;
49  
50  import javax.jcr.RepositoryException;
51  
52  import org.apache.commons.lang3.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
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          super(definition);
75          this.items = new ArrayList<JcrItemAdapter>(1);
76          this.items.add(item);
77          this.uiContext = uiContext;
78      }
79  
80      protected AbstractMultiItemAction(D definition, List<JcrItemAdapter> items, UiContext uiContext) {
81          super(definition);
82          this.items = items;
83          this.uiContext = uiContext;
84      }
85  
86      /**
87       * Executes the action on ONE item.
88       */
89      protected abstract void executeOnItem(JcrItemAdapter item) throws Exception;
90  
91      /**
92       * Returns the message to display, if the execution succeeds on ALL items. May return <code>null</code>,
93       * if the implementing action handles the user notification on its own.
94       */
95      protected abstract String getSuccessMessage();
96  
97      /**
98       * Returns the message to display, if the execution fails on at least ONE item. May return <code>null</code>,
99       * if the implementing action handles the user notification on its own.
100      */
101     protected abstract String getFailureMessage();
102 
103     @Override
104     public void execute() throws ActionExecutionException {
105         failedItems = new LinkedHashMap<JcrItemAdapter, Exception>();
106 
107         for (JcrItemAdapter item : getSortedItems(getItemComparator())) {
108             this.currentItem = item;
109             try {
110                 executeOnItem(item);
111             } catch (Exception ex) {
112                 failedItems.put(item, ex);
113             }
114         }
115         this.currentItem = null;
116 
117         if (failedItems.isEmpty()) {
118             String message = getSuccessMessage();
119             if (StringUtils.isNotBlank(message)) {
120                 uiContext.openNotification(MessageStyleTypeEnum.INFO, true, message);
121             }
122         } else {
123             String message = getErrorNotification();
124             if (StringUtils.isNotBlank(message)) {
125                 uiContext.openNotification(MessageStyleTypeEnum.ERROR, false, message);
126             }
127         }
128     }
129 
130     protected String getErrorNotification() {
131         String failureMessage = getFailureMessage();
132         if (failureMessage != null) {
133             StringBuilder notification = new StringBuilder(failureMessage);
134             notification.append("<ul>");
135             for (JcrItemAdapter item : failedItems.keySet()) {
136                 Exception ex = failedItems.get(item);
137                 notification.append("<li>").append("<b>");
138                 notification.append(JcrItemUtil.getItemPath(item.getJcrItem())).append("</b>: ").append(ex.getMessage());
139                 notification.append("</li>");
140             }
141             notification.append("</ul>");
142             return notification.toString();
143         }
144         return null;
145     }
146 
147     protected List<JcrItemAdapter> getItems() {
148         return this.items;
149     }
150 
151     /**
152      * @return the sorted Items list based on the desired {@link Comparator}.
153      */
154     protected List<JcrItemAdapter> getSortedItems(Comparator<JcrItemAdapter> comparator) {
155         return Ordering.from(comparator).sortedCopy(this.items);
156     }
157 
158     protected UiContext getUiContext() {
159         return this.uiContext;
160     }
161 
162     protected Map<JcrItemAdapter, Exception> getFailedItems() {
163         return this.failedItems;
164     }
165 
166     /**
167      * Returns the item that is currently <b>being</b> processed - i.e. <code>null</code> if the {@link #execute()} method is not running.
168      */
169     protected JcrItemAdapter getCurrentItem() {
170         return this.currentItem;
171     }
172 
173     /**
174      * 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.
175      */
176     protected void setCurrentItem(JcrItemAdapter item) {
177         this.currentItem = item;
178     }
179 
180     /**
181      * Create a {@link Comparator} used to sort {@link JcrItemAdapter}.
182      * First element of the list are child items:
183      * - /a/b.property
184      * - /a/b
185      * - /a
186      * - /
187      */
188     protected Comparator<JcrItemAdapter> getItemComparator() {
189         return new Comparator<JcrItemAdapter>() {
190             @Override
191             public int compare(JcrItemAdapter o1, JcrItemAdapter o2) {
192                 try {
193                     int res = o2.getJcrItem().getDepth() - o1.getJcrItem().getDepth();
194                     return res;
195                 } catch (RepositoryException e) {
196                     return 0;
197                 }
198             }
199         };
200     }
201 }