001/*
002 * (C) Copyright 2006-2011 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 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.jaxrs.session;
020
021import java.io.PrintWriter;
022import java.io.StringWriter;
023
024import javax.ws.rs.WebApplicationException;
025import javax.ws.rs.core.Response;
026import javax.ws.rs.ext.ExceptionMapper;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.core.api.DocumentNotFoundException;
031import org.nuxeo.ecm.core.api.DocumentSecurityException;
032
033/**
034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
035 */
036public class CoreExceptionMapper implements ExceptionMapper<Throwable> {
037
038    protected static final Log log = LogFactory.getLog(CoreExceptionMapper.class);
039
040    @Override
041    public Response toResponse(Throwable t) {
042        log.error("Exception in JAX-RS processing", t);
043        if (t instanceof WebApplicationException) {
044            return ((WebApplicationException) t).getResponse();
045        } else if (t instanceof DocumentSecurityException) {
046            return getResponse(t, 401);
047        } else if (t instanceof DocumentNotFoundException) {
048            return getResponse(t, 404);
049        }
050        return getResponse(t, 500);
051    }
052
053    public static Response getResponse(Throwable t, int status) {
054        String message = status == 500 ? getStackTrace(t) : null;
055        return Response.status(status).entity(message).build();
056    }
057
058    public static String getStackTrace(Throwable t) {
059        StringWriter sw = new StringWriter();
060        PrintWriter pw = new PrintWriter(sw);
061        t.printStackTrace(pw);
062        pw.close();
063        return sw.toString();
064    }
065
066}