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