001/*
002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others.
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:tdelprat@nuxeo.com">Tiry</a>
016 *     <a href="mailto:tmartins@nuxeo.com">Thierry Martins</a>
017 */
018
019package org.nuxeo.ecm.quota.size;
020
021import org.nuxeo.ecm.core.api.DocumentModel;
022import org.nuxeo.ecm.core.api.adapter.DocumentAdapterFactory;
023import org.nuxeo.ecm.quota.QuotaUtils;
024
025/**
026 * Simple factory for {@link QuotaAwareDocument} document model adapter
027 *
028 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
029 * @since 5.6
030 */
031public class QuotaAwareDocumentFactory implements DocumentAdapterFactory {
032
033    public static QuotaAwareDocument make(DocumentModel doc, boolean save) {
034        if (!doc.hasFacet(QuotaAwareDocument.DOCUMENTS_SIZE_STATISTICS_FACET)) {
035            doc.addFacet(QuotaAwareDocument.DOCUMENTS_SIZE_STATISTICS_FACET);
036            if (save) {
037                DocumentModel origDoc = doc;
038                // set flags to disable listeners
039                QuotaUtils.disableListeners(doc);
040                doc = doc.getCoreSession().saveDocument(doc);
041                // remove flags as they could be kept in the document for a long time otherwise
042                QuotaUtils.clearContextData(doc);
043                // also remove flags from original doc, which the caller still references
044                QuotaUtils.clearContextData(origDoc);
045            }
046        }
047        return (QuotaAwareDocument) doc.getAdapter(QuotaAware.class);
048    }
049
050    @Override
051    public Object getAdapter(DocumentModel doc, Class<?> adapter) {
052        if (doc.hasFacet(QuotaAwareDocument.DOCUMENTS_SIZE_STATISTICS_FACET)) {
053            return adapter.cast(new QuotaAwareDocument(doc));
054        }
055        return null;
056    }
057}