View Javadoc
1   /**
2    * This file Copyright (c) 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.databinding;
35  
36  import static java.util.stream.Collectors.*;
37  
38  import info.magnolia.jcr.RuntimeRepositoryException;
39  import info.magnolia.jcr.util.NodeUtil;
40  import info.magnolia.jcr.util.PropertyUtil;
41  import info.magnolia.ui.databinding.JcrItemPropertySet.JcrPropertyDescriptor;
42  import info.magnolia.ui.datasource.jcr.SupportsRenaming;
43  import info.magnolia.util.CollectionConversionCapableBeanUtils;
44  import info.magnolia.util.JcrValueConverter;
45  
46  import java.util.ArrayList;
47  import java.util.Arrays;
48  import java.util.Collection;
49  import java.util.List;
50  import java.util.Objects;
51  import java.util.Optional;
52  import java.util.Set;
53  import java.util.stream.Stream;
54  
55  import javax.jcr.InvalidItemStateException;
56  import javax.jcr.Item;
57  import javax.jcr.ItemNotFoundException;
58  import javax.jcr.Node;
59  import javax.jcr.Property;
60  import javax.jcr.RepositoryException;
61  import javax.jcr.Value;
62  
63  import org.apache.commons.beanutils.BeanUtilsBean;
64  import org.apache.commons.beanutils.ConversionException;
65  import org.apache.commons.lang3.StringUtils;
66  import org.slf4j.Logger;
67  import org.slf4j.LoggerFactory;
68  
69  import lombok.SneakyThrows;
70  
71  /**
72   * Implementation of {@link JcrItemInteractionStrategy}. Base implementation is provided as
73   * an abstract class, the concrete impls are in {@link WithNodes} and {@link WithProperties}.
74   *
75   * @param <I>
76   *     actual type of JCR item
77   */
78  abstract class JcrItemInteractionStrategyImpl<I extends Item> implements JcrItemInteractionStrategy<I> {
79  
80      private static final Logger log = LoggerFactory.getLogger(JcrItemInteractionStrategy.class);
81  
82      private BeanUtilsBean beanUtils = new CollectionConversionCapableBeanUtils();
83  
84      @SneakyThrows(RepositoryException.class)
85      <V> V getPropertyValue(Property property, Class<V> type) {
86          try {
87              boolean multiValue = property.isMultiple();
88  
89              if (multiValue) {
90                  // First un-pack all the values to the objects and collect to a set
91                  final Value[] values = property.getValues();
92                  final Set<Object> unpackedValues =
93                          Stream.of(values)
94                                  .map(JcrValueConverter::read)
95                                  .collect(toSet());
96  
97                  // try to convert set to an actual collection
98                  //noinspection unchecked
99                  return (V) beanUtils.getConvertUtils().convert(unpackedValues, type);
100             } else {
101                 return convertToPresentation(JcrValueConverter.read(property.getValue()), type).orElse(null);
102             }
103         } catch (InvalidItemStateException | ItemNotFoundException e) {
104             log.debug("Failed to get the value of property [{}], returning null", property, e);
105             return null;
106         }
107     }
108 
109     <V> void setPropertyValue(Node node, String name, V value) {
110         if ("jcrName".equals(name)) {
111             if (node instanceof SupportsRenaming) {
112                 ((SupportsRenaming) node).rename(String.valueOf(value));
113             }
114         }
115 
116         try {
117             if (node.hasProperty(name)) {
118                 if (propertyValueEquals(node.getProperty(name), value)) {
119                     return;
120                 }
121             }
122 
123             PropertyUtil.setProperty(node, name, value);
124         } catch (RepositoryException e) {
125             throw new RuntimeRepositoryException(e);
126         }
127     }
128 
129     private <V> boolean propertyValueEquals(Property property, V value) throws RepositoryException {
130         if (!property.isMultiple()) {
131            return Objects.equals(JcrValueConverter.read(property.getValue()), value);
132         } else {
133             final Value[] values = property.getValues();
134             final List<Object> jcrValues = Arrays.stream(values).map(JcrValueConverter::read).collect(toList());
135             return value instanceof Collection && Objects.equals(jcrValues, new ArrayList<>((Collection<?>) value));
136         }
137     }
138 
139     protected <V> Optional<V> convertToPresentation(Object value, Class<V> targetType) {
140         try {
141             //noinspection unchecked
142             return Optional.ofNullable((V) beanUtils.getConvertUtils().convert(value, targetType));
143         } catch (ConversionException e) {
144             return Optional.empty();
145         }
146     }
147 
148     /**
149      * {@link JcrItemInteractionStrategy} implementation for the nodes.
150      */
151     final static class WithNodes extends JcrItemInteractionStrategyImpl<Node> {
152 
153         @Override
154         public <V> V get(Node node, JcrPropertyDescriptor<V> descriptor) {
155             final Property property = PropertyUtil.getPropertyOrNull(node, descriptor.getName());
156             if ("jcrName".equals(descriptor.getName()) && property == null) {
157                 //noinspection unchecked
158                 return (V) NodeUtil.getName(node);
159             }
160             return Optional.ofNullable(property)
161                     .map(prop -> getPropertyValue(prop, descriptor.getType()))
162                     .orElse(null);
163         }
164 
165         @Override
166         public <V> void set(Node node, V value, JcrPropertyDescriptor<V> descriptor) {
167                 if (notNullOrEmptyString(value)) {
168                     setPropertyValue(node, descriptor.getName(), value);
169                 } else {
170                     // property exists but value is null or empty, remove it.
171                     Optional.ofNullable(PropertyUtil.getPropertyOrNull(node, descriptor.getName())).ifPresent(property -> {
172                         try {
173                             property.remove();
174                         } catch (RepositoryException e) {
175                             throw new RuntimeRepositoryException(e);
176                         }
177                     });
178                 }
179         }
180 
181         private boolean notNullOrEmptyString(Object value) {
182             if (value instanceof String) {
183                 return StringUtils.isNotEmpty((String) value);
184             }
185             return  value != null;
186         }
187     }
188 
189     /**
190      * {@link JcrItemInteractionStrategy} implementation for properties.
191      */
192     final static class WithProperties extends JcrItemInteractionStrategyImpl<Property> {
193 
194         @Override
195         @SneakyThrows(RepositoryException.class)
196         public <V> V get(Property property, JcrPropertyDescriptor<V> descriptor) {
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 "jcrName": case "name":
205                 //noinspection unchecked
206                 return (V) property.getName();
207             default:
208                 return null;
209             }
210         }
211 
212         @Override
213         public <V> void set(Property item, V value, JcrPropertyDescriptor<V> descriptor) {
214             try {
215                 switch (descriptor.getName()) {
216                 case "value":
217                     setPropertyValue(item.getParent(), item.getName(), value);
218                     break;
219                 case "jcrName":
220                 case "name":
221                     if (!(value instanceof String) || String.valueOf(value).isEmpty()) {
222                         return;
223                     }
224 
225                     if (item instanceof SupportsRenaming && !Objects.equals(item.getName(), value)) {
226                         ((SupportsRenaming) item).rename(String.valueOf(value));
227                     }
228 
229                     break;
230                 }
231             } catch (RepositoryException e) {
232                 log.warn("Failed to set the value [{}] to [{}]...", e);
233             }
234         }
235     }
236 }