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