001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 *
019 * Contributors:
020 *     Florent Guillaume
021 */
022package org.nuxeo.ecm.core.opencmis.bindings;
023
024import static javax.servlet.http.HttpServletResponse.SC_OK;
025import static org.apache.chemistry.opencmis.commons.impl.JSONConstants.ERROR_EXCEPTION;
026import static org.apache.chemistry.opencmis.commons.impl.JSONConstants.ERROR_MESSAGE;
027import static org.apache.chemistry.opencmis.commons.impl.JSONConstants.ERROR_STACKTRACE;
028
029import java.io.IOException;
030
031import javax.servlet.ServletException;
032import javax.servlet.http.HttpServletRequest;
033import javax.servlet.http.HttpServletResponse;
034
035import org.apache.chemistry.opencmis.commons.exceptions.CmisBaseException;
036import org.apache.chemistry.opencmis.commons.impl.json.JSONObject;
037import org.apache.chemistry.opencmis.commons.server.CallContext;
038import org.apache.chemistry.opencmis.commons.server.CmisService;
039import org.apache.chemistry.opencmis.server.impl.browser.AbstractBrowserServiceCall;
040import org.apache.chemistry.opencmis.server.impl.browser.BrowserCallContextImpl;
041import org.apache.chemistry.opencmis.server.impl.browser.CmisBrowserBindingServlet;
042import org.apache.chemistry.opencmis.server.shared.Dispatcher;
043import org.apache.chemistry.opencmis.server.shared.ExceptionHelper;
044import org.apache.commons.lang.StringUtils;
045import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisErrorHelper.ErrorInfo;
046import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
047import org.slf4j.Logger;
048import org.slf4j.LoggerFactory;
049
050/**
051 * Subclass NuxeoCmisBrowserBindingServlet to inject a virtual-hosted base URL if needed.
052 */
053public class NuxeoCmisBrowserBindingServlet extends CmisBrowserBindingServlet {
054
055    private static final long serialVersionUID = 1L;
056
057    private static final Logger LOG = LoggerFactory.getLogger(NuxeoCmisBrowserBindingServlet.class);
058
059    public static final NuxeoBrowserServiceCall CALL = new NuxeoBrowserServiceCall();
060
061    @Override
062    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
063            IOException {
064        String baseUrl = VirtualHostHelper.getBaseURL(request);
065        if (baseUrl != null) {
066            baseUrl = StringUtils.stripEnd(baseUrl, "/") + request.getServletPath() + "/"
067                    + AbstractBrowserServiceCall.REPOSITORY_PLACEHOLDER + "/";
068            request.setAttribute(Dispatcher.BASE_URL_ATTRIBUTE, baseUrl);
069        }
070        super.service(request, response);
071    }
072
073    /**
074     * Extracts the error from the exception.
075     *
076     * @param ex the exception
077     * @return the error info
078     * @since 7.1
079     */
080    protected ErrorInfo extractError(Exception ex) {
081        return NuxeoCmisErrorHelper.extractError(ex);
082    }
083
084    @Override
085    public void printError(CallContext context, Exception ex, HttpServletRequest request, HttpServletResponse response) {
086        ErrorInfo errorInfo = extractError(ex);
087        if (response.isCommitted()) {
088            LOG.warn("Failed to send error message to client. " + "Response is already committed.", ex);
089            return;
090        }
091
092        String token = (context instanceof BrowserCallContextImpl ? ((BrowserCallContextImpl) context).getToken()
093                : null);
094
095        if (token == null) {
096            response.resetBuffer();
097            CALL.setStatus(request, response, errorInfo.statusCode);
098
099            String message = ex.getMessage();
100            if (!(ex instanceof CmisBaseException)) {
101                message = "An error occurred!";
102            }
103
104            JSONObject jsonResponse = new JSONObject();
105            jsonResponse.put(ERROR_EXCEPTION, errorInfo.exceptionName);
106            jsonResponse.put(ERROR_MESSAGE, errorInfo.message);
107
108            String st = ExceptionHelper.getStacktraceAsString(ex);
109            if (st != null) {
110                jsonResponse.put(ERROR_STACKTRACE, st);
111            }
112
113            try {
114                CALL.writeJSON(jsonResponse, request, response);
115            } catch (IOException e) {
116                LOG.error(e.getMessage(), e);
117                try {
118                    response.sendError(errorInfo.statusCode, message);
119                } catch (IOException en) {
120                    // there is nothing else we can do
121                }
122            }
123        } else {
124            CALL.setStatus(request, response, SC_OK);
125            response.setContentType(AbstractBrowserServiceCall.HTML_MIME_TYPE);
126            response.setContentLength(0);
127
128            if (context != null) {
129                CALL.setCookie(request, response, context.getRepositoryId(), token,
130                        CALL.createCookieValue(errorInfo.statusCode, null, errorInfo.exceptionName, ex.getMessage()));
131            }
132        }
133    }
134
135    // this class exists in order to call AbstractBrowserServiceCall methods
136    public static class NuxeoBrowserServiceCall extends AbstractBrowserServiceCall {
137        @Override
138        public void serve(CallContext context, CmisService service, String repositoryId, HttpServletRequest request,
139                HttpServletResponse response) {
140            // no implementation
141        }
142    }
143
144}