001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.session;
013
014import java.io.PrintWriter;
015import java.io.StringWriter;
016
017import javax.ws.rs.WebApplicationException;
018import javax.ws.rs.core.Response;
019import javax.ws.rs.ext.ExceptionMapper;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.core.api.DocumentNotFoundException;
024import org.nuxeo.ecm.core.api.DocumentSecurityException;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class CoreExceptionMapper implements ExceptionMapper<Throwable> {
030
031    protected static final Log log = LogFactory.getLog(CoreExceptionMapper.class);
032
033    @Override
034    public Response toResponse(Throwable t) {
035        log.error("Exception in JAX-RS processing", t);
036        if (t instanceof WebApplicationException) {
037            return ((WebApplicationException) t).getResponse();
038        } else if (t instanceof DocumentSecurityException) {
039            return getResponse(t, 401);
040        } else if (t instanceof DocumentNotFoundException) {
041            return getResponse(t, 404);
042        }
043        return getResponse(t, 500);
044    }
045
046    public static Response getResponse(Throwable t, int status) {
047        String message = status == 500 ? getStackTrace(t) : null;
048        return Response.status(status).entity(message).build();
049    }
050
051    public static String getStackTrace(Throwable t) {
052        StringWriter sw = new StringWriter();
053        PrintWriter pw = new PrintWriter(sw);
054        t.printStackTrace(pw);
055        pw.close();
056        return sw.toString();
057    }
058
059}