View Javadoc
1   /**
2    * This file Copyright (c) 2014-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.form.field.transformer.multi;
35  
36  import info.magnolia.jcr.util.NodeTypes;
37  import info.magnolia.jcr.util.NodeUtil;
38  import info.magnolia.ui.api.i18n.I18NAuthoringSupport;
39  import info.magnolia.ui.form.field.definition.ConfiguredFieldDefinition;
40  import info.magnolia.ui.form.field.definition.MultiValueFieldDefinition;
41  import info.magnolia.ui.vaadin.integration.jcr.AbstractJcrNodeAdapter;
42  import info.magnolia.ui.vaadin.integration.jcr.JcrNewNodeAdapter;
43  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;
44  
45  import java.util.Collections;
46  import java.util.List;
47  
48  import javax.jcr.Node;
49  import javax.jcr.RepositoryException;
50  
51  import org.apache.commons.beanutils.BeanUtils;
52  import org.apache.commons.beanutils.PropertyUtils;
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  import com.vaadin.v7.data.Item;
58  import com.vaadin.v7.data.util.PropertysetItem;
59  
60  /**
61   * This delegating {@link info.magnolia.ui.form.field.transformer.Transformer Transformer} is dedicated to the {@link info.magnolia.ui.form.field.MultiField MultiField};
62   * it considers entries as child nodes of a sub-node (named after the field) and delegates property handling to their respective sub-fields.
63   * <p>
64   * The storage strategy is that of the {@link info.magnolia.ui.form.field.transformer.multi.MultiValueSubChildrenNodePropertiesTransformer MultiValueSubChildrenNodePropertiesTransformer}:
65   * <ul>
66   * <li>rootItem (relatedFormItem)
67   * <ul>
68   * <li>childNode (single child node for MultiField entries)<br>
69   * <ul>
70   * <li>0 (first entry of the MultiField)<br>
71   * <li>1 (second entry of the MultiField)<br>
72   * <li>...
73   * </ul>
74   * </ul>
75   * </ul>
76   */
77  public class DelegatingMultiValueSubnodeTransformer extends DelegatingMultiValueFieldTransformer {
78  
79      private static final Logger log = LoggerFactory.getLogger(DelegatingMultiValueSubnodeTransformer.class);
80  
81      private JcrNodeAdapter childNode;
82  
83      public DelegatingMultiValueSubnodeTransformer(Item relatedFormItem, ConfiguredFieldDefinition definition, Class<PropertysetItem> type, I18NAuthoringSupport i18NAuthoringSupport) {
84          super(relatedFormItem, definition, type, i18NAuthoringSupport);
85          detectsChildNodeType((MultiValueFieldDefinition) definition);
86      }
87  
88      /**
89       * Overridden to keep only the digit part in child-node names.
90       */
91      @Override
92      protected String getSubItemBaseName() {
93          return "";
94      }
95  
96      /**
97       * Overridden to get an intermediate child node where the multiple nodes are stored, rather than directly under the root node.
98       * <p>
99       * The child node is created if it doesn't exist, and is named after the multi-value field definition.
100      */
101     @Override
102     protected JcrNodeAdapter getRootItem() {
103         if (childNode == null) {
104             JcrNodeAdapter rootItem = super.getRootItem();
105             Node rootJcrItem = rootItem.getJcrItem();
106             try {
107                 final String childNodeName = getChildNodeName();
108                 if (rootJcrItem.hasNode(childNodeName)) {
109                     final AbstractJcrNodeAdapter alreadyExistingChildItem = rootItem.getChild(childNodeName);
110                     if (alreadyExistingChildItem instanceof JcrNodeAdapter) { //don't lose children items by creating a new item when item already exists (happens when switching language)
111                         childNode = (JcrNodeAdapter) alreadyExistingChildItem;
112                     } else {
113                         childNode = new JcrNodeAdapter(rootJcrItem.getNode(childNodeName));
114                     }
115                 } else if (rootItem.getChildren().containsKey(childNodeName)) {
116                     // Initialize an intermediate child node when the child item has been created already but hasn't been persisted yet.
117                     Object childItem = rootItem.getChildren().get(childNodeName);
118                     if (childItem instanceof JcrNodeAdapter) {
119                         childNode = (JcrNodeAdapter) childItem;
120                     }
121                 } else {
122                     childNode = new JcrNewNodeAdapter(rootJcrItem, NodeTypes.ContentNode.NAME, childNodeName);
123                 }
124                 rootItem.addChild(childNode);
125             } catch (RepositoryException e) {
126                 log.warn(String.format("Could not determine whether form item '%s' had a child node named '%s'", rootJcrItem, definition.getName()), e);
127             }
128         }
129         return childNode;
130     }
131 
132     @Override
133     protected List<Node> getStoredChildNodes(JcrNodeAdapter parent) {
134         try {
135             if (!(parent instanceof JcrNewNodeAdapter) && parent.getJcrItem().hasNodes()) {
136                 return NodeUtil.asList(NodeUtil.getNodes(parent.getJcrItem(), childNodeType));
137             }
138         } catch (RepositoryException re) {
139             log.warn("Not able to access the Child Nodes of the following Node Identifier {}", parent.getItemId(), re);
140         }
141         return Collections.emptyList();
142     }
143 
144     protected String getChildNodeName() {
145         return definition.getName();
146     }
147 
148     private void detectsChildNodeType(MultiValueFieldDefinition definition) {
149         try {
150             if (definition.getField() != null && PropertyUtils.isReadable(definition.getField(), "nodeType")) {
151                 childNodeType = StringUtils.defaultIfBlank(BeanUtils.getProperty(definition.getField(), "nodeType"), childNodeType);
152             }
153         } catch (Exception ex) {
154             log.error("Can't read nodeType property from the definition");
155         }
156     }
157 }