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