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