View Javadoc
1   /**
2    * This file Copyright (c) 2014-2016 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.form.field.transformer.item;
35  
36  import info.magnolia.cms.beans.runtime.FileProperties;
37  import info.magnolia.cms.core.Path;
38  import info.magnolia.jcr.util.NodeTypes;
39  import info.magnolia.jcr.util.NodeUtil;
40  import info.magnolia.objectfactory.Components;
41  import info.magnolia.ui.form.field.definition.BasicUploadFieldDefinition;
42  import info.magnolia.ui.form.field.transformer.Transformer;
43  import info.magnolia.ui.form.field.upload.UploadReceiver;
44  import info.magnolia.ui.vaadin.integration.jcr.AbstractJcrNodeAdapter;
45  import info.magnolia.ui.vaadin.integration.jcr.DefaultProperty;
46  import info.magnolia.ui.vaadin.integration.jcr.JcrNewNodeAdapter;
47  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;
48  
49  import java.io.FileInputStream;
50  import java.io.InputStream;
51  import java.io.OutputStream;
52  import java.util.ArrayList;
53  import java.util.Date;
54  import java.util.List;
55  import java.util.Locale;
56  
57  import javax.inject.Inject;
58  import javax.jcr.Binary;
59  import javax.jcr.Node;
60  import javax.jcr.RepositoryException;
61  
62  import org.apache.commons.io.IOUtils;
63  import org.apache.jackrabbit.JcrConstants;
64  import org.apache.jackrabbit.value.BinaryImpl;
65  import org.apache.jackrabbit.value.ValueFactoryImpl;
66  import org.slf4j.Logger;
67  import org.slf4j.LoggerFactory;
68  
69  import com.vaadin.data.Item;
70  import com.vaadin.data.Property;
71  
72  /**
73   * Implementation of a {@link Transformer} that handle a Binary Item instead of a simple property.<br>
74   * 
75   * @param <T> property type used by the related field.
76   */
77  public class FileTransformer<T extends UploadReceiver> implements Transformer<T> {
78  
79      private static final Logger log = LoggerFactory.getLogger(FileTransformer.class);
80  
81      protected Item relatedFormItem;
82      protected final BasicUploadFieldDefinition definition;
83      protected final Class<T> type;
84      private Locale locale;
85      // item name
86      protected String basePropertyName;
87      // i18n item name
88      protected String i18NPropertyName;
89  
90      @Inject
91      public FileTransformer(Item relatedFormItem, BasicUploadFieldDefinition definition, Class<T> type) {
92          this.definition = definition;
93          this.relatedFormItem = relatedFormItem;
94          this.type = type;
95          this.basePropertyName = getBasePropertyName();
96          if (hasI18NSupport()) {
97              this.i18NPropertyName = this.basePropertyName;
98          }
99      }
100 
101     /**
102      * Base on the validity of the received property, populate or not the property to the related Item.<br>
103      * Call {@link FileTransformer#populateItem(Object, Item)} in case {@link FileTransformer#isValid(Object, Item)} return true. <br>
104      * Otherwise call {@link FileTransformer#handleInvalid(Object, Item)}.
105      */
106     @Override
107     public void writeToItem(T newValue) {
108         Item item = getOrCreateFileItem();
109         if (isValid(newValue, item)) {
110             populateItem(newValue, item);
111             getRootItem().addChild((AbstractJcrNodeAdapter) item);
112         } else {
113             handleInvalid(newValue, item);
114         }
115     }
116 
117     /**
118      * Get the stored Item, and based of this Item, return {@link FileTransformer#createPropertyFromItem(Item)} .
119      */
120     @Override
121     public T readFromItem() {
122         // Initialize the child node list
123         JcrNodeAdapter rootItem = getRootItem();
124         // The root Item was never populated, add relevant child Item based on the stored nodes.
125         if (!rootItem.hasChildItemChanges()) {
126             populateStoredChildItems(rootItem);
127         }
128         // Get or create the file item.
129         Item item = getOrCreateFileItem();
130         return createPropertyFromItem(item);
131     }
132 
133     /**
134      * @return the existing Item otherwise create an empty new Item.
135      */
136     protected Item getOrCreateFileItem() {
137         String itemName = getItemName();
138         Item child = getRootItem().getChild(itemName);
139         if (child != null) {
140             return child;
141         }
142         Node node = null;
143         try {
144             node = getRootItem().getJcrItem();
145             if (node.hasNode(itemName) && !(getRootItem() instanceof JcrNewNodeAdapter)) {
146                 child = new JcrNodeAdapter(node.getNode(itemName));
147             } else {
148                 child = new JcrNewNodeAdapter(node, NodeTypes.Resource.NAME, itemName);
149             }
150         } catch (RepositoryException e) {
151             log.error("Could get or create a child Item for {} ", NodeUtil.getPathIfPossible(node), e);
152         }
153         return child;
154     }
155 
156     /**
157      * Based on the i18n information, define the item name to use.
158      */
159     protected String getItemName() {
160         if (hasI18NSupport()) {
161             return this.i18NPropertyName;
162         }
163         return this.basePropertyName;
164     }
165 
166     /**
167      * @return related property initialized based on the Item.
168      */
169     public T createPropertyFromItem(Item item) {
170         T uploadReceiver = initializeUploadReceiver();
171 
172         // Set File if the binary Item has data
173         if (item.getItemProperty(JcrConstants.JCR_DATA) != null && item.getItemProperty(JcrConstants.JCR_DATA).getValue() != null) {
174             String fileName = item.getItemProperty(FileProperties.PROPERTY_FILENAME) != null ? (String) item.getItemProperty(FileProperties.PROPERTY_FILENAME).getValue() : "";
175             String MIMEType = item.getItemProperty(FileProperties.PROPERTY_CONTENTTYPE) != null ? String.valueOf(item.getItemProperty(FileProperties.PROPERTY_CONTENTTYPE).getValue()) : "";
176             OutputStream out = uploadReceiver.receiveUpload(fileName, MIMEType);
177             InputStream in;
178             try {
179                 in = ((BinaryImpl) item.getItemProperty(JcrConstants.JCR_DATA).getValue()).getStream();
180                 IOUtils.copy(in, out);
181                 IOUtils.closeQuietly(in);
182                 IOUtils.closeQuietly(out);
183             } catch (Exception e) {
184                 e.printStackTrace();
185             }
186 
187         }
188         return uploadReceiver;
189     }
190 
191     protected T initializeUploadReceiver() {
192         return (T) Components.newInstance(UploadReceiver.class, Path.getTempDirectory());
193     }
194 
195     /**
196      * @return true it the 'newValue' property is valid for being populated to the Item {@link FileTransformer#populateItem(Object, Item)}.
197      */
198     protected boolean isValid(T newValue, Item item) {
199         return newValue != null && !newValue.isEmpty();
200     }
201 
202     /**
203      * Populate the related Item with the values of 'newItem' in case {@link FileTransformer#isValid(Object, Item)} return true.<br>
204      * 
205      * @see {@link FileTransformer#writeToItem(Object)}.
206      */
207     public Item populateItem(T newValue, Item item) {
208         // Populate Data
209         Property<Binary> data = getOrCreateProperty(item, JcrConstants.JCR_DATA, Binary.class);
210         if (newValue != null) {
211             try {
212                 data.setValue(ValueFactoryImpl.getInstance().createBinary(new FileInputStream(newValue.getFile())));
213             } catch (Exception re) {
214                 log.error("Could not get Binary. Upload will not be performed", re);
215                 getRootItem().removeChild((AbstractJcrNodeAdapter) item);
216                 return null;
217             }
218         }
219         getOrCreateProperty(item, FileProperties.PROPERTY_FILENAME, String.class).setValue(newValue.getFileName());
220         getOrCreateProperty(item, FileProperties.PROPERTY_CONTENTTYPE, String.class).setValue(newValue.getMimeType());
221         getOrCreateProperty(item, FileProperties.PROPERTY_LASTMODIFIED, Date.class).setValue(new Date());
222         getOrCreateProperty(item, FileProperties.PROPERTY_SIZE, Long.class).setValue(newValue.getFileSize());
223         getOrCreateProperty(item, FileProperties.PROPERTY_EXTENSION, String.class).setValue(newValue.getExtension());
224         return item;
225     }
226 
227     /**
228      * Handle the related Item in case {@link FileTransformer#isValid(Object, Item)} return false.<br>
229      * 
230      * @see {@link FileTransformer#writeToItem(Object)}.
231      */
232     protected void handleInvalid(T newValue, Item item) {
233         if (((AbstractJcrNodeAdapter) item).getParent() != null) {
234             ((AbstractJcrNodeAdapter) item).getParent().removeChild((AbstractJcrNodeAdapter) item);
235         }
236     }
237 
238     /**
239      * Get the required property from the Item, or create it if it does not exist.
240      */
241     protected Property getOrCreateProperty(Item item, String propertyName, Class<?> type) {
242         if (item.getItemProperty(propertyName) == null) {
243             item.addItemProperty(propertyName, new DefaultProperty(type, null));
244         }
245         return item.getItemProperty(propertyName);
246     }
247 
248     /**
249      * Defines the root item used to retrieve and create child items.
250      */
251     protected JcrNodeAdapter getRootItem() {
252         return (JcrNodeAdapter) relatedFormItem;
253     }
254 
255     /**
256      * Populates the given root item with its child items.
257      */
258     protected void populateStoredChildItems(JcrNodeAdapter rootItem) {
259         List<Node> childNodes = getStoredChildNodes(rootItem);
260         for (Node child : childNodes) {
261             JcrNodeAdapter item = new JcrNodeAdapter(child);
262             item.setParent(rootItem);
263             item.getParent().addChild(item);
264         }
265     }
266 
267     /**
268      * Fetches child nodes of the given parent from JCR, filtered using the {@link NodeUtil#MAGNOLIA_FILTER} predicate.
269      */
270     protected List<Node> getStoredChildNodes(JcrNodeAdapter parent) {
271         try {
272             if (!(parent instanceof JcrNewNodeAdapter) && parent.getJcrItem().hasNodes()) {
273                 return NodeUtil.asList(NodeUtil.getNodes(parent.getJcrItem(), NodeUtil.MAGNOLIA_FILTER));
274             }
275         } catch (RepositoryException re) {
276             log.warn("Not able to access the Child Nodes of the following Node Identifier {}", parent.getItemId(), re);
277         }
278         return new ArrayList<Node>();
279     }
280 
281     @Override
282     public String getBasePropertyName() {
283         return this.definition.getBinaryNodeName();
284     }
285 
286     @Override
287     public Class<T> getType() {
288         return this.type;
289     }
290 
291 
292     /* I18nAwareHandler impl */
293 
294     @Override
295     public boolean hasI18NSupport() {
296         return definition.isI18n();
297     }
298 
299     @Override
300     public void setLocale(Locale locale) {
301         this.locale = locale;
302     }
303 
304     @Override
305     public void setI18NPropertyName(String i18nPropertyName) {
306         this.i18NPropertyName = i18nPropertyName;
307     }
308 
309     @Override
310     public Locale getLocale() {
311         return this.locale;
312     }
313 
314 }