001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
018 */
019package org.nuxeo.ecm.collections.core.adapter;
020
021import java.io.Serializable;
022import java.util.List;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.ecm.collections.api.CollectionConstants;
027import org.nuxeo.ecm.core.api.DocumentModel;
028
029/**
030 * @since 5.9.3
031 */
032public class CollectionMember {
033
034    private static final Log log = LogFactory.getLog(CollectionMember.class);
035
036    protected DocumentModel document;
037
038    public CollectionMember(final DocumentModel doc) {
039        document = doc;
040    }
041
042    public void addToCollection(final String collectionId) {
043        List<String> collectionIds = getCollectionIds();
044        if (!collectionIds.contains(collectionId)) {
045            collectionIds.add(collectionId);
046        }
047        setCollectionIds(collectionIds);
048    }
049
050    public void setCollectionIds(final List<String> collectionIds) {
051        document.setPropertyValue(CollectionConstants.DOCUMENT_COLLECTION_IDS_PROPERTY_NAME,
052                (Serializable) collectionIds);
053    }
054
055    public List<String> getCollectionIds() {
056        @SuppressWarnings("unchecked")
057        List<String> collectionIds = (List<String>) document.getPropertyValue(CollectionConstants.DOCUMENT_COLLECTION_IDS_PROPERTY_NAME);
058        return collectionIds;
059    }
060
061    public DocumentModel getDocument() {
062        return document;
063    }
064
065    public void removeFromCollection(final String documentId) {
066        List<String> collectionIds = getCollectionIds();
067        if (!collectionIds.remove(documentId)) {
068            log.warn(String.format("Element '%s' is not present in the specified collection.", documentId));
069        }
070        setCollectionIds(collectionIds);
071    }
072
073}