001/*
002 * (C) Copyright 2012 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 * Contributors:
016 * Nuxeo - initial API and implementation
017 */
018
019package org.nuxeo.ecm.platform.rendition.url;
020
021import java.io.IOException;
022import java.io.Serializable;
023import java.util.Collections;
024import java.util.Map;
025
026import javax.faces.context.FacesContext;
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029
030import org.apache.commons.logging.Log;
031import org.apache.commons.logging.LogFactory;
032import org.jboss.seam.annotations.Begin;
033import org.jboss.seam.annotations.In;
034import org.jboss.seam.faces.FacesMessages;
035import org.jboss.seam.international.StatusMessage;
036import org.nuxeo.ecm.core.api.Blob;
037import org.nuxeo.ecm.core.api.CoreSession;
038import org.nuxeo.ecm.core.api.DocumentLocation;
039import org.nuxeo.ecm.core.api.DocumentModel;
040import org.nuxeo.ecm.core.api.NuxeoException;
041import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
042import org.nuxeo.ecm.platform.ui.web.tag.fn.DocumentModelFunctions;
043import org.nuxeo.ecm.platform.ui.web.util.ComponentUtils;
044import org.nuxeo.ecm.platform.url.api.DocumentView;
045import org.nuxeo.ecm.platform.util.RepositoryLocation;
046
047/**
048 * Base class for Rendition url codec bindings.
049 * <p>
050 * This class is shared with Template rendering system.
051 *
052 * @since 5.6
053 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
054 */
055public abstract class AbstractRenditionRestHelper implements Serializable {
056
057    private static final long serialVersionUID = 1L;
058
059    protected static final Log log = LogFactory.getLog(AbstractRenditionRestHelper.class);
060
061    @In(create = true, required = false)
062    protected transient CoreSession documentManager;
063
064    @In(create = true)
065    protected transient NavigationContext navigationContext;
066
067    @In(create = true, required = false)
068    protected FacesMessages facesMessages;
069
070    @In(create = true)
071    protected Map<String, String> messages;
072
073    protected abstract Blob renderAsBlob(DocumentModel doc, String renditionName) throws Exception;
074
075    @Begin(id = "#{conversationIdGenerator.nextMainConversationId}", join = true)
076    public void render(DocumentView docView) throws Exception {
077
078        DocumentLocation docLoc = docView.getDocumentLocation();
079        if (documentManager == null) {
080            RepositoryLocation loc = new RepositoryLocation(docLoc.getServerName());
081            navigationContext.setCurrentServerLocation(loc);
082            documentManager = navigationContext.getOrCreateDocumentManager();
083        }
084        DocumentModel doc = documentManager.getDocument(docLoc.getDocRef());
085        if (doc != null) {
086            String renditionName = docView.getParameter(RenditionBasedCodec.RENDITION_PARAM_NAME);
087            FacesContext context = FacesContext.getCurrentInstance();
088            Blob rendered = null;
089            try {
090                rendered = renderAsBlob(doc, renditionName);
091            } catch (NuxeoException e) {
092                log.error("Unable to generate rendition " + renditionName, e);
093                facesMessages.add(StatusMessage.Severity.WARN, messages.get("rendition.not.available"), renditionName);
094                // now we need to redirect
095                // otherwise the page will be rendered via Seam PDF
096                HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
097                String url = DocumentModelFunctions.documentUrl(doc, req);
098
099                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
100                try {
101                    response.sendRedirect(url);
102                    // be sure we block the codec chain
103                    response.flushBuffer();
104                    FacesContext.getCurrentInstance().responseComplete();
105                } catch (IOException ioe) {
106                    log.error("Error while redirecting to standard view", ioe);
107                }
108                return;
109            }
110            if (rendered != null) {
111                if (rendered.getMimeType() != null && rendered.getMimeType().startsWith("text/")) {
112                    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
113                    // add inline download flag
114                    request.setAttribute("inline", "true");
115                }
116                ComponentUtils.download(doc, null, rendered, rendered.getFilename(), "rendition",
117                        Collections.singletonMap("rendition", renditionName));
118            } else {
119                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
120                response.sendError(404, "Unable to find rendition " + renditionName);
121            }
122        }
123    }
124
125}