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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.drive.operations.test;
020
021import java.util.concurrent.TimeUnit;
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.nuxeo.common.utils.IdUtils;
025import org.nuxeo.ecm.core.api.CoreSession;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.api.DocumentModelList;
028import org.nuxeo.ecm.core.api.DocumentRef;
029import org.nuxeo.ecm.core.api.NuxeoException;
030import org.nuxeo.ecm.core.api.PathRef;
031import org.nuxeo.ecm.core.work.api.WorkManager;
032import org.nuxeo.ecm.platform.audit.api.AuditLogger;
033import org.nuxeo.ecm.platform.usermanager.UserManager;
034import org.nuxeo.ecm.user.center.profile.UserProfileService;
035import org.nuxeo.runtime.api.Framework;
036
037/**
038 * Helper for the Nuxeo Drive integration tests.
039 *
040 * @author Antoine Taillefer
041 * @see NuxeoDriveSetupIntegrationTests
042 * @see NuxeoDriveTearDownIntegrationTests
043 */
044public final class NuxeoDriveIntegrationTestsHelper {
045
046    static final Log log = LogFactory.getLog(NuxeoDriveIntegrationTestsHelper.class);
047
048    public static final String TEST_USER_NAME_PREFIX = "drive";
049
050    public static final String TEST_WORKSPACE_PARENT_NAME = "workspaces";
051
052    public static final String TEST_WORKSPACE_NAME = "nuxeo-drive-test-workspace";
053
054    public static final String TEST_WORKSPACE_TITLE = "Nuxeo Drive Test Workspace";
055
056    public static final String USER_WORKSPACE_PARENT_NAME = "UserWorkspaces";
057
058    private NuxeoDriveIntegrationTestsHelper() {
059        // Helper class
060    }
061
062    public static void cleanUp(CoreSession session) {
063
064        // Delete test users and their personal workspace if exist
065        UserManager userManager = Framework.getLocalService(UserManager.class);
066        DocumentModelList testUsers = userManager.searchUsers(TEST_USER_NAME_PREFIX);
067        for (DocumentModel testUser : testUsers) {
068            String testUserName = (String) testUser.getPropertyValue(userManager.getUserSchemaName() + ":"
069                    + userManager.getUserIdField());
070            if (userManager.getPrincipal(testUserName) != null) {
071                userManager.deleteUser(testUserName);
072            }
073            String testUserWorkspaceName = IdUtils.generateId(testUserName, "-", false, 30);
074            String testUserWorkspacePath = getDefaultDomainPath(session) + "/" + USER_WORKSPACE_PARENT_NAME + "/"
075                    + testUserWorkspaceName;
076            DocumentRef testUserWorkspaceRef = new PathRef(testUserWorkspacePath);
077            if (session.exists(testUserWorkspaceRef)) {
078                session.removeDocument(testUserWorkspaceRef);
079                session.save();
080            }
081        }
082
083        // Delete test workspace if exists
084        String testWorkspacePath = getDefaultDomainPath(session) + "/" + TEST_WORKSPACE_PARENT_NAME + "/"
085                + TEST_WORKSPACE_NAME;
086        DocumentRef testWorkspaceDocRef = new PathRef(testWorkspacePath);
087        if (session.exists(testWorkspaceDocRef)) {
088            session.removeDocument(testWorkspaceDocRef);
089            session.save();
090        }
091
092        // Invalidate user profile cache
093        Framework.getLocalService(UserProfileService.class).clearCache();
094    }
095
096    public static String getDefaultDomainPath(CoreSession session) {
097        String query = "SELECT * FROM Document where ecm:primaryType = 'Domain'";
098        DocumentModelList results = session.query(query);
099        if (results.isEmpty()) {
100            throw new NuxeoException(String.format("Found no domains in repository %s", session.getRepositoryName()));
101        }
102        if (results.size() > 1) {
103            if (log.isDebugEnabled()) {
104                log.debug(String.format("Found more than one domain in repository %s, using first one.",
105                        session.getRepositoryName()));
106            }
107        }
108        DocumentModel defaultDomain = results.get(0);
109        String defaultDomainPath = defaultDomain.getPathAsString();
110        if (log.isDebugEnabled()) {
111            log.debug(String.format("Using default domain %s", defaultDomainPath));
112        }
113        return defaultDomainPath;
114    }
115
116    public static void checkOperationAllowed() {
117        if (!(Framework.isDevModeSet() || Framework.isTestModeSet() || Framework.getProperty("org.nuxeo.ecm.tester.name") != null)) {
118            throw new UnsupportedOperationException("This operation cannot be run unless test mode is set.");
119        }
120    }
121
122    public static void waitForAsyncCompletion() throws InterruptedException {
123        if (!Framework.getService(WorkManager.class).awaitCompletion(2, TimeUnit.MINUTES)) {
124            throw new AssertionError("Cannot synch with work manager in 2 minutes");
125        }
126    }
127
128    public static void waitForAuditIngestion() throws InterruptedException {
129        if (!Framework.getService(AuditLogger.class).await(2, TimeUnit.MINUTES)) {
130            throw new AssertionError("Cannot synch with audi in 2 minutes");
131        }
132    }
133
134}