001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.fcrepo.kernel.modeshape.utils;
019
020import static java.util.Arrays.asList;
021import static java.util.Arrays.stream;
022import static org.apache.jena.datatypes.xsd.XSDDatatype.XSDstring;
023import static org.fcrepo.kernel.modeshape.FedoraJcrConstants.FIELD_DELIMITER;
024import static org.fcrepo.kernel.modeshape.utils.FedoraTypesUtils.getJcrNode;
025import static org.fcrepo.kernel.modeshape.utils.FedoraTypesUtils.getReferencePropertyName;
026import static org.fcrepo.kernel.modeshape.utils.FedoraTypesUtils.isExternalNode;
027import static org.fcrepo.kernel.modeshape.utils.FedoraTypesUtils.isInternalReferenceProperty;
028import static org.fcrepo.kernel.modeshape.utils.FedoraTypesUtils.isMultivaluedProperty;
029import static org.fcrepo.kernel.modeshape.utils.UncheckedPredicate.uncheck;
030import static org.slf4j.LoggerFactory.getLogger;
031
032import java.util.ArrayList;
033import java.util.List;
034import java.util.concurrent.atomic.AtomicBoolean;
035
036import org.apache.commons.lang3.StringUtils;
037
038import javax.jcr.Node;
039import javax.jcr.Property;
040import javax.jcr.PropertyType;
041import javax.jcr.RepositoryException;
042import javax.jcr.Value;
043
044import org.apache.jena.rdf.model.Resource;
045
046import org.fcrepo.kernel.api.models.FedoraResource;
047import org.fcrepo.kernel.api.exception.IdentifierConversionException;
048import org.fcrepo.kernel.api.exception.NoSuchPropertyDefinitionException;
049import org.fcrepo.kernel.api.identifiers.IdentifierConverter;
050import org.slf4j.Logger;
051
052/**
053 * Tools for replacing, appending and deleting JCR node properties
054 * @author Chris Beer
055 * @author ajs6f
056 * @since May 10, 2013
057 */
058public class NodePropertiesTools {
059
060    private static final Logger LOGGER = getLogger(NodePropertiesTools.class);
061
062    /**
063     * Given a JCR node, property and value, either:
064     *  - if the property is single-valued, replace the existing property with
065     *    the new value
066     *  - if the property is multivalued, append the new value to the property
067     * @param node the JCR node
068     * @param propertyName a name of a JCR property (either pre-existing or
069     *   otherwise)
070     * @param newValue the JCR value to insert
071     * @throws RepositoryException if repository exception occurred
072     */
073    public void appendOrReplaceNodeProperty(final Node node, final String propertyName, final Value newValue)
074        throws RepositoryException {
075
076        final Property property;
077
078        // if it already exists, we can take some shortcuts
079        if (node.hasProperty(propertyName)) {
080
081            property = node.getProperty(propertyName);
082
083            if (property.isMultiple()) {
084                LOGGER.debug("Appending value {} to {} property {}", newValue,
085                             PropertyType.nameFromValue(property.getType()),
086                             propertyName);
087
088                // if the property is multi-valued, go ahead and append to it.
089                final List<Value> newValues = new ArrayList<>(asList(node.getProperty(propertyName).getValues()));
090
091                if (!newValues.contains(newValue)) {
092                    newValues.add(newValue);
093                    property.setValue(newValues.toArray(new Value[newValues.size()]));
094                }
095            } else {
096                // or we'll just overwrite its single value
097                LOGGER.debug("Overwriting {} property {} with new value {}", PropertyType.nameFromValue(property
098                        .getType()), propertyName, newValue);
099                property.setValue(newValue);
100            }
101        } else {
102            // we're creating a new property on this node, so we check whether it should be multi-valued
103            boolean isMultiple = true;
104            try {
105                isMultiple = isMultivaluedProperty(node, propertyName);
106            } catch (final NoSuchPropertyDefinitionException e) {
107                // simply represents a new kind of property on this node
108            }
109            if (isMultiple) {
110                LOGGER.debug("Creating new multivalued {} property {} with " +
111                             "initial value [{}]",
112                             PropertyType.nameFromValue(newValue.getType()),
113                             propertyName, newValue);
114                property = node.setProperty(propertyName, new Value[]{newValue}, newValue.getType());
115            } else {
116                LOGGER.debug("Creating new single-valued {} property {} with " +
117                             "initial value {}",
118                             PropertyType.nameFromValue(newValue.getType()),
119                             propertyName, newValue);
120                property = node.setProperty(propertyName, newValue, newValue.getType());
121            }
122        }
123
124        if (!property.isMultiple() && !isInternalReferenceProperty.test(property)) {
125            final String referencePropertyName = getReferencePropertyName(propertyName);
126            if (node.hasProperty(referencePropertyName)) {
127                node.getProperty(referencePropertyName).remove();
128            }
129        }
130    }
131
132    /**
133     * Add a reference placeholder from one node to another in-domain resource
134     * @param idTranslator the id translator
135     * @param node the node
136     * @param propertyName the property name
137     * @param resource the resource
138     * @throws RepositoryException if repository exception occurred
139     */
140    public void addReferencePlaceholders(final IdentifierConverter<Resource,FedoraResource> idTranslator,
141                                          final Node node,
142                                          final String propertyName,
143                                          final Resource resource) throws RepositoryException {
144
145        try {
146            final Node refNode = getJcrNode(idTranslator.convert(resource));
147
148            if (isExternalNode.test(refNode)) {
149                // we can't apply REFERENCE properties to external resources
150                return;
151            }
152
153            final String referencePropertyName = getReferencePropertyName(propertyName);
154
155            if (!isMultivaluedProperty(node, propertyName)) {
156                if (node.hasProperty(referencePropertyName)) {
157                    node.getProperty(referencePropertyName).remove();
158                }
159
160                if (node.hasProperty(propertyName)) {
161                    node.getProperty(propertyName).remove();
162                }
163            }
164
165            final Value v = node.getSession().getValueFactory().createValue(refNode, true);
166            appendOrReplaceNodeProperty(node, referencePropertyName, v);
167
168        } catch (final IdentifierConversionException e) {
169            // no-op
170        }
171    }
172
173    /**
174     * Remove a reference placeholder that links one node to another in-domain resource
175     * @param idTranslator the id translator
176     * @param node the node
177     * @param propertyName the property name
178     * @param resource the resource
179     * @throws RepositoryException if repository exception occurred
180     */
181    public void removeReferencePlaceholders(final IdentifierConverter<Resource,FedoraResource> idTranslator,
182                                             final Node node,
183                                             final String propertyName,
184                                             final Resource resource) throws RepositoryException {
185
186        final String referencePropertyName = getReferencePropertyName(propertyName);
187
188        final Node refNode = getJcrNode(idTranslator.convert(resource));
189        final Value v = node.getSession().getValueFactory().createValue(refNode, true);
190        removeNodeProperty(node, referencePropertyName, v);
191    }
192    /**
193     * Given a JCR node, property and value, remove the value (if it exists)
194     * from the property, and remove the
195     * property if no values remove
196     *
197     * @param node the JCR node
198     * @param propertyName a name of a JCR property (either pre-existing or
199     *   otherwise)
200     * @param valueToRemove the JCR value to remove
201     * @throws RepositoryException if repository exception occurred
202     */
203    public void removeNodeProperty(final Node node, final String propertyName, final Value valueToRemove)
204        throws RepositoryException {
205        LOGGER.debug("Request to remove {}", valueToRemove);
206        // if the property doesn't exist, we don't need to worry about it.
207        if (node.hasProperty(propertyName)) {
208
209            final Property property = node.getProperty(propertyName);
210            final String strValueToRemove = valueToRemove.getString();
211            final String strValueToRemoveWithoutStringType = strValueToRemove != null ?
212                        strValueToRemove.replace(FIELD_DELIMITER + XSDstring.getURI(), "") : strValueToRemove;
213
214            if (property.isMultiple()) {
215                final AtomicBoolean remove = new AtomicBoolean();
216                final Value[] newValues = stream(node.getProperty(propertyName).getValues()).filter(uncheck(v -> {
217                    final String strVal = v.getString().replace(FIELD_DELIMITER + XSDstring.getURI(), "");
218
219                    LOGGER.debug("v is '{}', valueToRemove is '{}'", v, strValueToRemove );
220                    if (strVal.equals(strValueToRemoveWithoutStringType)) {
221                        remove.set(true);
222                        return false;
223                    }
224
225                    return true;
226                })).toArray(Value[]::new);
227
228                // we only need to update the property if we did anything.
229                if (remove.get()) {
230                    if (newValues.length == 0) {
231                        LOGGER.debug("Removing property '{}'", propertyName);
232                        property.remove();
233                    } else {
234                        LOGGER.debug("Removing value '{}' from property '{}'", strValueToRemove, propertyName);
235                        property.setValue(newValues);
236                    }
237                } else {
238                    LOGGER.debug("Value not removed from property name '{}' (value '{}')", propertyName,
239                            strValueToRemove);
240                    throw new RepositoryException ("Property '" + propertyName + "': Unable to remove value '" +
241                            StringUtils.substring(strValueToRemove, 0, 50) + "...'");
242                }
243            } else {
244
245                final String strPropVal = property.getValue().getString();
246                final String strPropValWithoutStringType =
247                    strPropVal != null ? strPropVal.replace(FIELD_DELIMITER + XSDstring.getURI(), "") : strPropVal;
248
249                LOGGER.debug("Removing string '{}'", strValueToRemove);
250                if (StringUtils.equals(strPropValWithoutStringType, strValueToRemoveWithoutStringType)) {
251                    LOGGER.debug("single value: Removing value from property '{}'", propertyName);
252                    property.remove();
253                } else {
254                    LOGGER.debug("Value not removed from property name '{}' (property value: '{}';compare value: '{}')",
255                            propertyName, strPropVal, strValueToRemove);
256                    throw new RepositoryException("Property '" + propertyName + "': Unable to remove value '" +
257                            StringUtils.substring(strValueToRemove, 0, 50) + "'");
258                }
259            }
260        }
261    }
262}