001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
016 */
017package org.nuxeo.ecm.collections.core.adapter;
018
019import java.io.Serializable;
020import java.util.List;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.nuxeo.ecm.collections.api.CollectionConstants;
025import org.nuxeo.ecm.core.api.DocumentModel;
026
027/**
028 * @since 5.9.3
029 */
030public class CollectionMember {
031
032    private static final Log log = LogFactory.getLog(CollectionMember.class);
033
034    protected DocumentModel document;
035
036    public CollectionMember(final DocumentModel doc) {
037        document = doc;
038    }
039
040    public void addToCollection(final String collectionId) {
041        List<String> collectionIds = getCollectionIds();
042        if (!collectionIds.contains(collectionId)) {
043            collectionIds.add(collectionId);
044        }
045        setCollectionIds(collectionIds);
046    }
047
048    public void setCollectionIds(final List<String> collectionIds) {
049        document.setPropertyValue(CollectionConstants.DOCUMENT_COLLECTION_IDS_PROPERTY_NAME,
050                (Serializable) collectionIds);
051    }
052
053    public List<String> getCollectionIds() {
054        @SuppressWarnings("unchecked")
055        List<String> collectionIds = (List<String>) document.getPropertyValue(CollectionConstants.DOCUMENT_COLLECTION_IDS_PROPERTY_NAME);
056        return collectionIds;
057    }
058
059    public DocumentModel getDocument() {
060        return document;
061    }
062
063    public void removeFromCollection(final String documentId) {
064        List<String> collectionIds = getCollectionIds();
065        if (!collectionIds.remove(documentId)) {
066            log.warn(String.format("Element '%s' is not present in the specified collection.", documentId));
067        }
068        setCollectionIds(collectionIds);
069    }
070
071}