View Javadoc
1   /**
2    * This file Copyright (c) 2012-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.vaadin.integration.jcr;
35  
36  import info.magnolia.cms.core.Path;
37  
38  import javax.jcr.Item;
39  import javax.jcr.Node;
40  import javax.jcr.RepositoryException;
41  
42  import org.apache.commons.lang3.StringUtils;
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  import com.vaadin.v7.data.Property;
47  
48  /**
49   * Used to create a new Node based on an Vaadin Item. This node adapter uses the parent node to
50   * initialize the global properties (workspace, path....). No references is made to an existing JCR
51   * node (except for the parent of the node to create). However, after applying changes to the
52   * item, the reference will be held to the newly created node.
53   */
54  public class JcrNewNodeAdapter extends JcrNodeAdapter {
55  
56      private static final Logger log = LoggerFactory.getLogger(JcrNewNodeAdapter.class);
57      /**
58       * Whether changes were already applied to the node.
59       */
60      private boolean appliedChanges = false;
61  
62      /**
63       * @param parentNode Parent of the node to create.
64       * @param nodeType Type node to create.
65       */
66      public JcrNewNodeAdapter(Node parentNode, String nodeType) {
67          this(parentNode, nodeType, null);
68      }
69  
70      /**
71       * @param parentNode Parent of the node to create.
72       * @param nodeType Type node to create.
73       * @param nodeName Name of the new node.
74       */
75      public JcrNewNodeAdapter(Node parentNode, String nodeType, String nodeName) {
76          super(parentNode);
77          setPrimaryNodeTypeName(nodeType);
78          setNodeName(nodeName);
79          try {
80              JcrItemId parentId = JcrItemUtil.getItemId(parentNode);
81              setItemId(new JcrNewNodeItemId(parentId.getUuid(), parentId.getWorkspace(), nodeType, nodeName));
82          } catch (RepositoryException e) {
83              log.error("Failed to initialize JcrNewNodeAdapter: " + e.getMessage(), e);
84          }
85      }
86  
87  
88      /**
89       * Returns item property of a new node.
90       */
91      @Override
92      public Property getItemProperty(Object propertyId) {
93          // If changes were already applied, behave like a JcrNodeAdapter
94          if (appliedChanges) {
95              return super.getItemProperty(propertyId);
96          }
97          return getChangedProperties().get(propertyId);
98      }
99  
100     /**
101      * Create a new subNode of the parent Node or return the existing one if already created.
102      *
103      * If called a second time, apply changes of {@link JcrNodeAdapter} will be called.
104      */
105     @Override
106     public Node applyChanges() throws RepositoryException {
107         // If changes were already applied, behave like a JcrNodeAdapter
108         if (appliedChanges) {
109             return super.applyChanges();
110         }
111 
112         Node parent = getJcrItem();
113 
114         // Create a Node Name if not defined
115         if (StringUtils.isBlank(getNodeName())) {
116             setNodeName(getUniqueNewItemName(parent));
117         }
118 
119         // Create the new node
120         Node node = parent.addNode(getNodeName(), getPrimaryNodeTypeName());
121         log.debug("create a new node for parent " + parent.getPath() + " with name " + getNodeName());
122 
123         // Update properties
124         updateProperties(node);
125 
126         // Update child nodes
127         if (!getChildren().isEmpty()) {
128             for (AbstractJcrNodeAdapter child : getChildren().values()) {
129                 if (child instanceof JcrNewNodeAdapter) {
130                     // Set parent node (parent could be newly created)
131                     child.initCommonAttributes(node);
132                 }
133                 child.applyChanges();
134             }
135         }
136         // Update parent
137         if (!appliedChanges) {
138             setParent(new JcrNodeAdapter(parent));
139         }
140 
141         appliedChanges = true;
142 
143         // Update itemId to new node
144         setItemId(JcrItemUtil.getItemId(node));
145         return node;
146     }
147 
148     @Override
149     protected void markPropertyForDeletion(String propertyId) {
150         if (appliedChanges) {
151             super.markPropertyForDeletion(propertyId);
152         }
153     }
154 
155     @Override
156     public void setNodeName(String nodeName) {
157         super.setNodeName(nodeName);
158         if (getItemId() instanceof JcrNewNodeItemId) {
159             ((JcrNewNodeItemId) getItemId()).setName(nodeName);
160         }
161     }
162 
163     @Override
164     public void setItemId(JcrItemId itemId) {
165         JcrItemId actualItemId;
166         if (appliedChanges) {
167             actualItemId = new JcrNodeItemId(itemId.getUuid(), itemId.getWorkspace());
168         } else {
169             actualItemId = new JcrNewNodeItemId(itemId.getUuid(), itemId.getWorkspace(), getPrimaryNodeTypeName(), getNodeName());
170         }
171         super.setItemId(actualItemId);
172     }
173 
174     /**
175      * Create a new unique nodeName. If JCR_NAME if part of the properties, use this property as
176      * desired nodeName.
177      */
178     private String getUniqueNewItemName(final Item item) throws RepositoryException {
179         if (item == null) {
180             throw new IllegalArgumentException("Item cannot be null");
181         }
182 
183         String nodeName = "";
184         if (getChangedProperties().containsKey(ModelConstants.JCR_NAME)) {
185             nodeName = (String) getChangedProperties().get(ModelConstants.JCR_NAME).getValue();
186             getChangedProperties().remove(ModelConstants.JCR_NAME);
187             nodeName = Path.getValidatedLabel(nodeName);
188         }
189 
190         return Path.getUniqueLabel(item.getSession(), item.getPath(), nodeName);
191     }
192 
193     @Override
194     public boolean isNew() {
195         // before applying changes getJcrItem() returns the parent of the node being created,
196         // therefore we can't check it for isNew(), as it would always be false (parent already exists in JCR).
197         return !appliedChanges || getJcrItem().isNew();
198     }
199 }