001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
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 *     dmetzler
016 */
017package org.nuxeo.ecm.restapi.test;
018
019import java.io.File;
020import java.io.IOException;
021import java.util.Arrays;
022import java.util.Calendar;
023import java.util.concurrent.TimeUnit;
024
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.common.utils.FileUtils;
027import org.nuxeo.ecm.automation.core.util.DocumentHelper;
028import org.nuxeo.ecm.core.api.Blob;
029import org.nuxeo.ecm.core.api.Blobs;
030import org.nuxeo.ecm.core.api.CoreSession;
031import org.nuxeo.ecm.core.api.DocumentModel;
032import org.nuxeo.ecm.core.api.NuxeoException;
033import org.nuxeo.ecm.core.api.NuxeoGroup;
034import org.nuxeo.ecm.core.api.NuxeoPrincipal;
035import org.nuxeo.ecm.core.api.PathRef;
036import org.nuxeo.ecm.core.test.annotations.RepositoryInit;
037import org.nuxeo.ecm.core.work.api.WorkManager;
038import org.nuxeo.ecm.platform.usermanager.UserManager;
039import org.nuxeo.ecm.platform.usermanager.exceptions.GroupAlreadyExistsException;
040import org.nuxeo.ecm.platform.usermanager.exceptions.UserAlreadyExistsException;
041import org.nuxeo.runtime.api.Framework;
042import org.nuxeo.runtime.transaction.TransactionHelper;
043
044/**
045 * Repo init to test Rest API
046 *
047 * @since 5.7.2
048 */
049public class RestServerInit implements RepositoryInit {
050
051    /**
052     *
053     */
054    private static final String POWER_USER_LOGIN = "user0";
055
056    public static final String[] FIRSTNAMES = { "Steve", "John", "Georges", "Bill" };
057
058    public static final String[] LASTNAMES = { "Jobs", "Lennon", "Harrisson", "Gates" };
059
060    public static final String[] GROUPNAMES = { "Stark", "Lannister", "Targaryen", "Greyjoy" };
061
062    @Override
063    public void populate(CoreSession session) {
064        // try to prevent NXP-15404
065        // clearRepositoryCaches(session.getRepositoryName());
066        // Create some docs
067        for (int i = 0; i < 5; i++) {
068            DocumentModel doc = session.createDocumentModel("/", "folder_" + i, "Folder");
069            doc.setPropertyValue("dc:title", "Folder " + i);
070            if (i == 0) {
071                // set dc:issued value for queries on dates
072                Calendar cal = Calendar.getInstance();
073                cal.set(Calendar.YEAR, 2007);
074                cal.set(Calendar.MONTH, 1); // 0-based
075                cal.set(Calendar.DAY_OF_MONTH, 17);
076                doc.setPropertyValue("dc:issued", cal);
077            }
078            doc = session.createDocument(doc);
079        }
080
081        for (int i = 0; i < 5; i++) {
082            DocumentModel doc = session.createDocumentModel("/folder_1", "note_" + i, "Note");
083            doc.setPropertyValue("dc:title", "Note " + i);
084            doc.setPropertyValue("dc:source", "Source" + i);
085            doc.setPropertyValue("dc:nature", "Nature" + i % 2);
086            doc.setPropertyValue("dc:coverage", "Coverage" + i % 3);
087            doc.setPropertyValue("note:note", "Note " + i);
088            doc = session.createDocument(doc);
089        }
090
091        // Create a file
092        DocumentModel doc = session.createDocumentModel("/folder_2", "file", "File");
093        doc.setPropertyValue("dc:title", "File");
094        doc = session.createDocument(doc);
095        // upload file blob
096        File fieldAsJsonFile = FileUtils.getResourceFileFromContext("blob.json");
097        try {
098            Blob fb = Blobs.createBlob(fieldAsJsonFile, "image/jpeg");
099            DocumentHelper.addBlob(doc.getProperty("file:content"), fb);
100        } catch (IOException e) {
101            throw new NuxeoException(e);
102        }
103        session.saveDocument(doc);
104
105        TransactionHelper.commitOrRollbackTransaction();
106        TransactionHelper.startTransaction();
107
108        try {
109            Framework.getService(WorkManager.class).awaitCompletion(10, TimeUnit.SECONDS);
110        } catch (InterruptedException cause) {
111            LogFactory.getLog(RestServerInit.class).error("Cannot initialize the rest api test repo in 10 seconds",
112                    cause);
113            Thread.currentThread().interrupt();
114        }
115
116        UserManager um = Framework.getLocalService(UserManager.class);
117        // Create some users
118        if (um != null) {
119            createUsersAndGroups(um);
120        }
121
122    }
123
124    private void createUsersAndGroups(UserManager um) throws UserAlreadyExistsException,
125            GroupAlreadyExistsException {
126        for (int idx = 0; idx < 4; idx++) {
127            String userId = "user" + idx;
128
129            NuxeoPrincipal principal = um.getPrincipal(userId);
130
131            if (principal != null) {
132                um.deleteUser(principal.getModel());
133            }
134
135            DocumentModel userModel = um.getBareUserModel();
136            String schemaName = um.getUserSchemaName();
137            userModel.setProperty(schemaName, "username", userId);
138            userModel.setProperty(schemaName, "firstName", FIRSTNAMES[idx]);
139            userModel.setProperty(schemaName, "lastName", LASTNAMES[idx]);
140            userModel.setProperty(schemaName, "password", userId);
141            userModel = um.createUser(userModel);
142            principal = um.getPrincipal(userId);
143
144        }
145
146        // Create some groups
147        for (int idx = 0; idx < 4; idx++) {
148            String groupId = "group" + idx;
149            String groupLabel = GROUPNAMES[idx];
150            createGroup(um, groupId, groupLabel);
151        }
152
153        // Create the power user group
154        createGroup(um, "powerusers", "Power Users");
155
156        // Add the power user group to user0
157        NuxeoPrincipal principal = um.getPrincipal(POWER_USER_LOGIN);
158        principal.setGroups(Arrays.asList(new String[] { "powerusers" }));
159        um.updateUser(principal.getModel());
160    }
161
162    private void createGroup(UserManager um, String groupId, String groupLabel) throws
163            GroupAlreadyExistsException {
164        NuxeoGroup group = um.getGroup(groupId);
165        if (group != null) {
166            um.deleteGroup(groupId);
167        }
168
169        DocumentModel groupModel = um.getBareGroupModel();
170        String schemaName = um.getGroupSchemaName();
171        groupModel.setProperty(schemaName, "groupname", groupId);
172        groupModel.setProperty(schemaName, "grouplabel", groupLabel);
173        groupModel = um.createGroup(groupModel);
174    }
175
176    public static DocumentModel getFolder(int index, CoreSession session) {
177        return session.getDocument(new PathRef("/folder_" + index));
178    }
179
180    public static DocumentModel getNote(int index, CoreSession session) {
181        return session.getDocument(new PathRef("/folder_1/note_" + index));
182    }
183
184    public static DocumentModel getFile(int index, CoreSession session) {
185        return session.getDocument(new PathRef("/folder_2/file"));
186    }
187
188    public static NuxeoPrincipal getPowerUser() {
189        UserManager um = Framework.getLocalService(UserManager.class);
190        return um.getPrincipal(POWER_USER_LOGIN);
191    }
192
193}