001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.ecm.webengine.app;
018
019import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
020
021import javax.ws.rs.core.Context;
022import javax.ws.rs.core.HttpHeaders;
023import javax.ws.rs.core.Response;
024import javax.ws.rs.core.Response.Status;
025import javax.ws.rs.ext.ExceptionMapper;
026import javax.ws.rs.ext.Provider;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.core.api.validation.DocumentValidationException;
031import org.nuxeo.ecm.webengine.WebException;
032import org.nuxeo.ecm.webengine.model.exceptions.WebResourceNotFoundException;
033import org.nuxeo.runtime.transaction.TransactionHelper;
034
035import com.sun.jersey.api.NotFoundException;
036
037/**
038 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
039 */
040@Provider
041public class WebEngineExceptionMapper implements ExceptionMapper<Throwable> {
042
043    @Context
044    HttpHeaders headers;
045
046    protected static final Log log = LogFactory.getLog(WebEngineExceptionMapper.class);
047
048    @Override
049    public Response toResponse(Throwable cause) {
050        TransactionHelper.setTransactionRollbackOnly();
051        if (headers.getAcceptableMediaTypes().contains(APPLICATION_JSON_TYPE)) {
052            if (cause instanceof DocumentValidationException) {
053                DocumentValidationException dve = (DocumentValidationException) cause;
054                return Response.status(Status.BAD_REQUEST).entity(dve.getReport()).build();
055            }
056        }
057        if (cause instanceof NotFoundException) {
058            NotFoundException nfe = (NotFoundException) cause;
059            log.debug("JAX-RS 404 Not Found: " + nfe.getNotFoundUri());
060        } else if (cause instanceof WebResourceNotFoundException) {
061            WebResourceNotFoundException nfe = (WebResourceNotFoundException) cause;
062            log.debug("JAX-RS 404 Not Found: " + nfe.getMessage());
063        } else {
064            log.warn("Exception in JAX-RS processing", cause);
065        }
066        return WebException.newException(cause.getMessage(), WebException.wrap(cause)).toResponse();
067    }
068
069}