View Javadoc
1   /**
2    * This file Copyright (c) 2021 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.editor;
35  
36  import static java.util.stream.Collectors.*;
37  
38  import info.magnolia.jcr.util.NodeNameHelper;
39  import info.magnolia.jcr.util.NodeTypes;
40  import info.magnolia.jcr.util.NodeUtil;
41  import info.magnolia.jcr.util.PropertyUtil;
42  import info.magnolia.objectfactory.Components;
43  import info.magnolia.ui.editor.JcrItemPropertySet.JcrPropertyDescriptor;
44  import info.magnolia.util.CollectionConversionCapableBeanUtils;
45  
46  import java.io.File;
47  import java.io.IOException;
48  import java.util.ArrayList;
49  import java.util.Collection;
50  import java.util.List;
51  import java.util.Objects;
52  import java.util.Optional;
53  import java.util.stream.Stream;
54  
55  import javax.jcr.Item;
56  import javax.jcr.Node;
57  import javax.jcr.Property;
58  import javax.jcr.PropertyType;
59  import javax.jcr.RepositoryException;
60  
61  import org.apache.commons.beanutils.BeanUtilsBean;
62  import org.apache.commons.beanutils.ConversionException;
63  import org.apache.commons.lang3.StringUtils;
64  
65  import com.machinezoo.noexception.Exceptions;
66  
67  /**
68   * Implementation of {@link JcrItemInteractionStrategy}. Base implementation is provided as
69   * an abstract class, the concrete impls are in {@link WithNodes} and {@link WithProperties}.
70   *
71   * @param <I>
72   *     actual type of JCR item
73   */
74  abstract class JcrItemInteractionStrategyImpl<I extends Item> implements JcrItemInteractionStrategy<I>, JcrBinaryHelper {
75  
76      private static final String JCR_NAME = "jcrName";
77      private final BeanUtilsBean beanUtils = new CollectionConversionCapableBeanUtils();
78  
79      <V> V getPropertyValue(Property property, Class<V> type) {
80          if (!Exceptions.wrap().get(property::isMultiple)) {
81              return convertToPresentation(PropertyUtil.getValueObject(Exceptions.wrap().get(property::getValue)), type).orElse(null);
82          } else {
83              //noinspection unchecked
84              return (V) beanUtils.getConvertUtils().convert(Stream.of(Exceptions.wrap().get(property::getValues))
85                      .map(PropertyUtil::getValueObject)
86                      .collect(toList()), type);
87          }
88      }
89  
90      <V> void setPropertyValue(Node node, String name, V value) throws RepositoryException, IOException {
91          if (value instanceof File) {
92              createBinary(node, (File) value);
93          } else if (node.hasProperty(name) && propertyValueEquals(node.getProperty(name), value)) {
94              //no op
95          } else {
96              PropertyUtil.setProperty(node, name, value);
97          }
98      }
99  
100     private <V> boolean propertyValueEquals(Property property, V value) throws RepositoryException {
101         if (property.isMultiple()) {
102             final List<Object> values = Stream.of(property.getValues())
103                     .map(PropertyUtil::getValueObject)
104                     .collect(toList());
105             return value instanceof Collection && Objects.equals(values, new ArrayList<>((Collection<?>) value));
106         } else {
107             return Objects.equals(PropertyUtil.getValueObject(property.getValue()), value);
108         }
109     }
110 
111     protected <V> Optional<V> convertToPresentation(Object value, Class<V> targetType) {
112         try {
113             //noinspection unchecked
114             return Optional.ofNullable((V) beanUtils.getConvertUtils().convert(value, targetType));
115         } catch (ConversionException e) {
116             return Optional.empty();
117         }
118     }
119 
120     /**
121      * {@link JcrItemInteractionStrategy} implementation for the nodes.
122      */
123     final static class WithNodes extends JcrItemInteractionStrategyImpl<Node> {
124 
125         @Override
126         public <V> V get(Node node, JcrPropertyDescriptor<V> descriptor) {
127             Property property;
128             if (File.class.equals(descriptor.getType())) {
129                 return (V) Exceptions.wrap().get(() -> getBinary(node));
130             } else {
131                 property = PropertyUtil.getPropertyOrNull(node, JCR_NAME.equals(descriptor.getName()) ?
132                         Optional.ofNullable(descriptor.getNodeNameProperty()).orElse(JCR_NAME) : //no need to rename jcrName fields when changing JcrDatasource#nodeNameProperty
133                         descriptor.getName()
134                 );
135             }
136             if (shouldReturnRealNodeName(descriptor, property) && !node.isNew()) {
137                 //noinspection unchecked
138                 return (V) NodeUtil.getName(node);
139             }
140             return Optional.ofNullable(property)
141                     .map(prop -> getPropertyValue(prop, descriptor.getType())).orElse(null);
142         }
143 
144         private boolean shouldReturnRealNodeName(JcrPropertyDescriptor<?> descriptor, Property property) {
145             return isNodeNameProperty(descriptor) && (property == null || descriptor.getNodeNameProperty() == null); //either there is no such property or datasource supports only real node name
146         }
147 
148         @Override
149         public <V> void set(Node node, V value, JcrPropertyDescriptor<V> descriptor) {
150             Optional<Property> property = Optional.ofNullable(PropertyUtil.getPropertyOrNull(node, descriptor.getName()));
151             if (notNullOrEmptyString(value)) {
152                 // update property value only in case it is not marked as
153                 // read-only or if is completely missing in corresponding node
154                 // (i.e. persist a default read-only value to JCR)
155                 if (!descriptor.isReadonly() || !property.isPresent()) {
156                     Exceptions.wrap().run(() -> {
157                         if ((isNodeNameProperty(descriptor))) {
158                             handleJcrItemNameChange(node, descriptor.getNodeNameProperty(), String.valueOf(value));
159                         } else {
160                             setPropertyValue(node, descriptor.getName(), value);
161                         }
162                     });
163                 }
164             } else {
165                 // property exists but value is null or empty, remove it unless it is a system property
166                 property.ifPresent(Exceptions.wrap().consumer(prop -> {
167                     if (!prop.getName().startsWith(NodeTypes.JCR_PREFIX)) {
168                         prop.remove();
169                     }
170                 }));
171             }
172         }
173 
174         private boolean notNullOrEmptyString(Object value) {
175             if (value instanceof String) {
176                 return StringUtils.isNotEmpty((String) value);
177             }
178             return value != null;
179         }
180     }
181 
182     private static boolean isNodeNameProperty(JcrPropertyDescriptor<?> descriptor) {
183         return JCR_NAME.equals(descriptor.getName()) || descriptor.getName().equals(descriptor.getNodeNameProperty());
184     }
185 
186     /**
187      * {@link JcrItemInteractionStrategy} implementation for properties.
188      */
189     final static class WithProperties extends JcrItemInteractionStrategyImpl<Property> {
190 
191         @Override
192         public <V> V get(Property property, JcrPropertyDescriptor<V> descriptor) {
193             if (isNodeNameProperty(descriptor)) {
194                 //noinspection unchecked
195                 return (V) Exceptions.wrap().get(property::getName);
196             }
197             switch (descriptor.getName()) {
198             case "value":
199                 return getPropertyValue(property, descriptor.getType());
200             // properties can only have the name and the value, attempts to bind
201             // e.g. a grid cell to anything else is ignored. One exclusion is the 'jcrName'
202             // property which for the case of JCR property Grid rows will automatically fall back
203             // to Property#getName
204             case "jcrType":
205                 return (V) PropertyType.nameFromValue(Exceptions.wrap().get(property::getType));
206             default:
207                 return null;
208             }
209         }
210 
211         @Override
212         public <V> void set(Property item, V value, JcrPropertyDescriptor<V> descriptor) {
213             Exceptions.wrap().run(() -> {
214                 if (isNodeNameProperty(descriptor)) {
215                     handleJcrItemNameChange(item, descriptor.getNodeNameProperty(), String.valueOf(value));
216                 } else if ("value".equals(descriptor.getName())) {
217                     item.setValue(PropertyUtil.createValue(value, item.getSession().getValueFactory()));
218                 } else {
219                     throw new IllegalArgumentException("Supports setting only value, jcrName or configured node name property: " + descriptor.getName());
220                 }
221             });
222         }
223     }
224 
225     private static final NodeNameHelper nodeNameHelper = Components.getComponent(NodeNameHelper.class);
226 
227     private static void handleJcrItemNameChange(Item jcrItem, String propertyName, String pendingNewName) throws RepositoryException {
228         if (StringUtils.isNotEmpty(pendingNewName)) {
229             final String validatedName = nodeNameHelper.getValidatedName(pendingNewName);
230             if (jcrItem.isNode()) {
231                 final Node item = (Node) jcrItem;
232                 if (!jcrItem.getName().equals(validatedName)) {
233                     NodeUtil.renameNode(item, validatedName);
234                     if (propertyName != null) {
235                         PropertyUtil.setProperty(item, propertyName, pendingNewName);
236                     }
237                 }
238             } else {
239                 if (!jcrItem.getName().equals(validatedName)) {
240                     PropertyUtil.renameProperty((Property) jcrItem, validatedName);
241                 }
242             }
243         }
244     }
245 }