001/*
002 * (C) Copyright 2013 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 *     Mariana Cedica <mcedica@nuxeo.com>
016 */
017package org.nuxeo.ecm.quota;
018
019import org.nuxeo.ecm.core.api.CoreSession;
020import org.nuxeo.ecm.core.api.DocumentModel;
021import org.nuxeo.ecm.core.event.Event;
022import org.nuxeo.ecm.core.event.EventContext;
023import org.nuxeo.ecm.core.event.EventListener;
024import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
025import org.nuxeo.ecm.quota.size.QuotaAware;
026import org.nuxeo.ecm.quota.size.QuotaAwareDocumentFactory;
027
028/**
029 * Sets the quota on the user workspace if a global quota was set on all user workspaces
030 *
031 * @since 5.7
032 */
033public class QuotaUserWorkspaceListener implements EventListener {
034
035    @Override
036    public void handleEvent(Event event) {
037
038        EventContext ctx = event.getContext();
039        if (!(ctx instanceof DocumentEventContext)) {
040            return;
041        }
042        if (!"userWorkspaceCreated".equals(event.getName())) {
043            return;
044        }
045        DocumentModel userWorkspace = ((DocumentEventContext) ctx).getSourceDocument();
046        CoreSession session = userWorkspace.getCoreSession();
047        DocumentModel userWorkspacesRoot = session.getDocument(userWorkspace.getParentRef());
048        if (userWorkspacesRoot == null || !"UserWorkspacesRoot".equals(userWorkspacesRoot.getType())) {
049            return;
050        }
051        QuotaAware qaUserWorkspaces = userWorkspacesRoot.getAdapter(QuotaAware.class);
052        if (qaUserWorkspaces == null || qaUserWorkspaces.getMaxQuota() == -1L) {
053            // no global quota activated on user workspaces
054            return;
055        }
056        QuotaAware qa = userWorkspace.getAdapter(QuotaAware.class);
057        if (qa == null) {
058            qa = QuotaAwareDocumentFactory.make(userWorkspace, false);
059        }
060        // skip validation on other children quotas
061        qa.setMaxQuota(qaUserWorkspaces.getMaxQuota(), true, true);
062    }
063}