001/*
002 * (C) Copyright 2006-2016 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 *     Nuxeo - initial API and implementation
018 *
019 * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $
020 */
021
022package org.nuxeo.ecm.webapp.documenttemplates;
023
024import static org.jboss.seam.ScopeType.CONVERSATION;
025import static org.jboss.seam.ScopeType.EVENT;
026import static org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_CHILDREN_CHANGED;
027import static org.nuxeo.ecm.webapp.helpers.EventNames.DOMAIN_SELECTION_CHANGED;
028
029import java.io.Serializable;
030import java.util.ArrayList;
031import java.util.List;
032
033import org.apache.commons.logging.Log;
034import org.apache.commons.logging.LogFactory;
035import org.jboss.seam.annotations.Factory;
036import org.jboss.seam.annotations.In;
037import org.jboss.seam.annotations.Name;
038import org.jboss.seam.annotations.Observer;
039import org.jboss.seam.annotations.Scope;
040import org.jboss.seam.annotations.intercept.BypassInterceptors;
041import org.jboss.seam.core.Events;
042import org.jboss.seam.international.StatusMessage;
043import org.nuxeo.ecm.core.api.Blob;
044import org.nuxeo.ecm.core.api.CoreSession;
045import org.nuxeo.ecm.core.api.CoreSession.CopyOption;
046import org.nuxeo.ecm.core.api.DocumentModel;
047import org.nuxeo.ecm.core.api.DocumentModelList;
048import org.nuxeo.ecm.core.api.DocumentRef;
049import org.nuxeo.ecm.core.api.IdRef;
050import org.nuxeo.ecm.core.api.pathsegment.PathSegmentService;
051import org.nuxeo.ecm.core.query.sql.NXQL;
052import org.nuxeo.ecm.webapp.action.TypesTool;
053import org.nuxeo.ecm.webapp.base.InputController;
054import org.nuxeo.ecm.webapp.contentbrowser.DocumentActions;
055import org.nuxeo.ecm.webapp.helpers.EventNames;
056import org.nuxeo.runtime.api.Framework;
057
058/**
059 * Implementation for the documentTemplatesBean component available on the session.
060 */
061@Name("documentTemplatesActions")
062@Scope(CONVERSATION)
063public class DocumentTemplatesActionsBean extends InputController implements DocumentTemplatesActions, Serializable {
064
065    public static final String TemplateRoot = "TemplateRoot";
066
067    private static final Log log = LogFactory.getLog(DocumentTemplatesActionsBean.class);
068
069    private static final long serialVersionUID = -4031259222075515590L;
070
071    @In(create = true, required = false)
072    private transient CoreSession documentManager;
073
074    @In(required = false)
075    private transient DocumentActions documentActions;
076
077    @In(required = false)
078    private TypesTool typesTool;
079
080    @In(required = false)
081    protected DocumentModel changeableDocument;
082
083    // cached list of templates
084    private DocumentModelList templates;
085
086    private String selectedTemplateId;
087
088    private String targetType = "Workspace";
089
090    @Override
091    @Factory(value = "availableTemplates", scope = EVENT)
092    public DocumentModelList templatesListFactory() {
093        templates = getTemplates();
094        return templates;
095    }
096
097    @Override
098    public DocumentModelList getTemplates(String targetTypeName) {
099        if (documentManager == null) {
100            log.error("Unable to access documentManager");
101            return null;
102        }
103
104        String query = "SELECT * FROM Document where ecm:primaryType = '%s' AND ecm:path STARTSWITH %s";
105        DocumentModelList tl = documentManager.query(String.format(query, TemplateRoot,
106                NXQL.escapeString(navigationContext.getCurrentDomainPath())));
107
108        if (tl.isEmpty()) {
109            templates = tl;
110        } else {
111            templates = documentManager.getChildren(tl.get(0).getRef(), targetTypeName);
112            List<DocumentModel> deleted = new ArrayList<>();
113            for (DocumentModel current : templates) {
114                if (current.isTrashed()) {
115                    deleted.add(current);
116                }
117            }
118            templates.removeAll(deleted);
119        }
120        return templates;
121    }
122
123    @Override
124    public DocumentModelList getTemplates() {
125        if (targetType == null || targetType.equals("")) {
126            targetType = typesTool.getSelectedType().getId();
127        }
128        return getTemplates(targetType);
129    }
130
131    @Override
132    public String createDocumentFromTemplate(DocumentModel doc, String templateId) {
133        selectedTemplateId = templateId;
134        return createDocumentFromTemplate(doc);
135    }
136
137    @Override
138    public String createDocumentFromTemplate(DocumentModel doc) {
139
140        if (documentManager == null) {
141            log.error("Unable to access documentManager");
142            return null;
143        }
144
145        // Currently templating works with Workspace only
146        // Hardcoded that way.
147
148        if (selectedTemplateId == null || selectedTemplateId.equals("")) {
149            if (documentActions != null) {
150                return documentActions.saveDocument(doc);
151            } else {
152                log.error("Unable to find documentActions");
153                return null;
154            }
155        }
156
157        // Remove this once it is available from the context
158        DocumentRef currentDocRef = navigationContext.getCurrentDocument().getRef();
159
160        PathSegmentService pss = Framework.getService(PathSegmentService.class);
161        String name = pss.generatePathSegment(doc);
162        DocumentModel created = documentManager.copy(new IdRef(selectedTemplateId), currentDocRef, name,
163                CopyOption.RESET_CREATOR);
164
165        // Update from user input.
166        // This part is for now harcoded for Workspace type.
167        String title = (String) doc.getProperty("dublincore", "title");
168        created.setProperty("dublincore", "title", title);
169
170        String descr = (String) doc.getProperty("dublincore", "description");
171        created.setProperty("dublincore", "description", descr);
172
173        Blob blob = (Blob) doc.getProperty("file", "content");
174        if (blob != null) {
175            created.setProperty("file", "content", blob);
176        }
177
178        created = documentManager.saveDocument(created);
179        documentManager.save();
180
181        selectedTemplateId = "";
182
183        logDocumentWithTitle("Created the document: ", created);
184        facesMessages.add(StatusMessage.Severity.INFO, resourcesAccessor.getMessages().get("document_saved"),
185                resourcesAccessor.getMessages().get(created.getType()));
186        Events.instance().raiseEvent(EventNames.DOCUMENT_CHILDREN_CHANGED, currentDocument);
187        return navigationContext.navigateToDocument(created, "after-create");
188    }
189
190    @Override
191    public String createDocumentFromTemplate() {
192        return createDocumentFromTemplate(changeableDocument);
193    }
194
195    @Override
196    public String getSelectedTemplateId() {
197        return selectedTemplateId;
198    }
199
200    @Override
201    public void setSelectedTemplateId(String requestedId) {
202        selectedTemplateId = requestedId;
203    }
204
205    @Override
206    public String getTargetType() {
207        return targetType;
208    }
209
210    @Override
211    public void setTargetType(String targetType) {
212        this.targetType = targetType;
213    }
214
215    @Override
216    @Observer(value = { DOCUMENT_CHILDREN_CHANGED }, create = false)
217    @BypassInterceptors
218    public void documentChildrenChanged() {
219        if (templates != null) {
220            templates.clear();
221        }
222    }
223
224    @Override
225    @Observer(value = { DOMAIN_SELECTION_CHANGED }, create = false)
226    @BypassInterceptors
227    public void domainChanged() {
228        if (templates != null) {
229            templates.clear();
230        }
231    }
232
233}